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>
102 #include <Instrumentation/HUD/HUD.hxx>
103 #include <Environment/precipitation_mgr.hxx>
104 #include <Environment/environment_mgr.hxx>
105 #include <Environment/ephemeris.hxx>
107 //#include <Main/main.hxx>
109 #include "viewmgr.hxx"
110 #include "splash.hxx"
111 #include "renderer.hxx"
112 #include "CameraGroup.hxx"
113 #include "FGEventHandler.hxx"
118 using namespace simgear;
119 using namespace flightgear;
121 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
123 FGHintUpdateCallback(const char* configNode) :
124 mConfigNode(fgGetNode(configNode, true))
126 virtual void operator()(osg::StateAttribute* stateAttribute,
129 assert(dynamic_cast<osg::Hint*>(stateAttribute));
130 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
132 const char* value = mConfigNode->getStringValue();
134 hint->setMode(GL_DONT_CARE);
135 else if (0 == strcmp(value, "nicest"))
136 hint->setMode(GL_NICEST);
137 else if (0 == strcmp(value, "fastest"))
138 hint->setMode(GL_FASTEST);
140 hint->setMode(GL_DONT_CARE);
143 SGPropertyNode_ptr mConfigNode;
147 class SGPuDrawable : public osg::Drawable {
151 // Dynamic stuff, do not store geometry
152 setUseDisplayList(false);
153 setDataVariance(Object::DYNAMIC);
155 osg::StateSet* stateSet = getOrCreateStateSet();
156 stateSet->setRenderBinDetails(1001, "RenderBin");
157 // speed optimization?
158 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
159 // We can do translucent menus, so why not. :-)
160 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
161 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
162 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
164 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
166 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
167 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
169 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
170 { drawImplementation(*renderInfo.getState()); }
171 void drawImplementation(osg::State& state) const
173 state.setActiveTextureUnit(0);
174 state.setClientActiveTextureUnit(0);
176 state.disableAllVertexArrays();
178 glPushAttrib(GL_ALL_ATTRIB_BITS);
179 glPushClientAttrib(~0u);
187 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
188 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
193 class SGHUDDrawable : public osg::Drawable {
197 // Dynamic stuff, do not store geometry
198 setUseDisplayList(false);
199 setDataVariance(Object::DYNAMIC);
201 osg::StateSet* stateSet = getOrCreateStateSet();
202 stateSet->setRenderBinDetails(1000, "RenderBin");
204 // speed optimization?
205 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
206 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
207 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
208 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
209 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
211 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
213 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
214 { drawImplementation(*renderInfo.getState()); }
215 void drawImplementation(osg::State& state) const
217 state.setActiveTextureUnit(0);
218 state.setClientActiveTextureUnit(0);
219 state.disableAllVertexArrays();
221 glPushAttrib(GL_ALL_ATTRIB_BITS);
222 glPushClientAttrib(~0u);
225 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
234 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
235 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
240 class FGLightSourceUpdateCallback : public osg::NodeCallback {
244 * @param isSun true if the light is the actual sun i.e., for
245 * illuminating the moon.
247 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
248 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
250 : NodeCallback(nc, op), _isSun(nc._isSun)
252 META_Object(flightgear,FGLightSourceUpdateCallback);
254 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
256 assert(dynamic_cast<osg::LightSource*>(node));
257 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
258 osg::Light* light = lightSource->getLight();
260 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
262 // lighting is down during re-init
267 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
268 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
269 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
271 light->setAmbient(toOsg(l->scene_ambient()));
272 light->setDiffuse(toOsg(l->scene_diffuse()));
273 light->setSpecular(toOsg(l->scene_specular()));
275 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
276 light->setPosition(position);
284 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
286 FGWireFrameModeUpdateCallback() :
287 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
289 virtual void operator()(osg::StateAttribute* stateAttribute,
292 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
293 osg::PolygonMode* polygonMode;
294 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
296 if (mWireframe->getBoolValue())
297 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
298 osg::PolygonMode::LINE);
300 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
301 osg::PolygonMode::FILL);
304 SGPropertyNode_ptr mWireframe;
307 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
309 FGLightModelUpdateCallback() :
310 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
312 virtual void operator()(osg::StateAttribute* stateAttribute,
315 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
316 osg::LightModel* lightModel;
317 lightModel = static_cast<osg::LightModel*>(stateAttribute);
320 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
321 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
323 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
325 lightModel->setTwoSided(true);
326 lightModel->setLocalViewer(false);
328 if (mHighlights->getBoolValue()) {
329 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
331 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
335 SGPropertyNode_ptr mHighlights;
338 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
340 FGFogEnableUpdateCallback() :
341 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
343 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
345 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
346 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
348 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
352 SGPropertyNode_ptr mFogEnabled;
355 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
357 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
359 assert(dynamic_cast<SGUpdateVisitor*>(nv));
360 assert(dynamic_cast<osg::Fog*>(sa));
361 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
362 osg::Fog* fog = static_cast<osg::Fog*>(sa);
363 fog->setMode(osg::Fog::EXP2);
364 fog->setColor(toOsg(updateVisitor->getFogColor()));
365 fog->setDensity(updateVisitor->getFogExp2Density());
369 // update callback for the switch node guarding that splash
370 class FGScenerySwitchCallback : public osg::NodeCallback {
372 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
374 assert(dynamic_cast<osg::Switch*>(node));
375 osg::Switch* sw = static_cast<osg::Switch*>(node);
377 bool enabled = scenery_enabled;
378 sw->setValue(0, enabled);
384 static bool scenery_enabled;
387 bool FGScenerySwitchCallback::scenery_enabled = false;
389 FGRenderer::FGRenderer() :
391 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
392 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
393 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
394 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
395 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
396 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
397 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
398 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
399 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
400 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
402 // it's not the real root, whatever that means
403 _root = new osg::Group;
404 _root->setName("fakeRoot");
406 _updateVisitor = new SGUpdateVisitor;
408 // when Rembrandt is enabled, we use this group to access the whole
409 // scene. Since the only child is the _viewerSceneRoot, we could
410 // simply copy the reference, we don't need the additional group.
411 _deferredRealRoot = new osg::Group;
414 _cascadeFar[0] = 5.f;
415 _cascadeFar[1] = 50.f;
416 _cascadeFar[2] = 500.f;
417 _cascadeFar[3] = 5000.f;
420 FGRenderer::~FGRenderer()
422 SGPropertyChangeListenerVec::iterator i = _listeners.begin();
423 for (; i != _listeners.end(); ++i) {
427 // replace the viewer's scene completely
429 getViewer()->setSceneData(new osg::Group);
435 // Initialize various GL/view parameters
436 // XXX This should be called "preinit" or something, as it initializes
437 // critical parts of the scene graph in addition to the splash screen.
439 FGRenderer::splashinit( void )
441 // important that we reset the viewer sceneData here, to ensure the reference
442 // time for everything is in sync; otherwise on reset the Viewer and
443 // GraphicsWindow clocks are out of sync.
444 osgViewer::Viewer* viewer = getViewer();
445 viewer->setName("osgViewer");
446 _viewerSceneRoot = new osg::Group;
447 _viewerSceneRoot->setName("viewerSceneRoot");
448 viewer->setSceneData(_viewerSceneRoot);
450 ref_ptr<Node> splashNode = fgCreateSplashNode();
451 if (_classicalRenderer) {
452 _viewerSceneRoot->addChild(splashNode.get());
454 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
455 ii != CameraGroup::getDefault()->camerasEnd();
458 CameraInfo* info = ii->get();
459 Camera* camera = info->getCamera(DISPLAY_CAMERA);
460 if (camera == 0) continue;
462 camera->addChild(splashNode.get());
466 _frameStamp = new osg::FrameStamp;
467 viewer->setFrameStamp(_frameStamp.get());
468 // Scene doesn't seem to pass the frame stamp to the update
469 // visitor automatically.
470 _updateVisitor->setFrameStamp(_frameStamp.get());
471 viewer->setUpdateVisitor(_updateVisitor.get());
472 fgSetDouble("/sim/startup/splash-alpha", 1.0);
475 class ShadowMapSizeListener : public SGPropertyChangeListener {
477 virtual void valueChanged(SGPropertyNode* node) {
478 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
482 class ShadowEnabledListener : public SGPropertyChangeListener {
484 virtual void valueChanged(SGPropertyNode* node) {
485 globals->get_renderer()->enableShadows(node->getBoolValue());
489 class ShadowNumListener : public SGPropertyChangeListener {
491 virtual void valueChanged(SGPropertyNode* node) {
492 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
496 class ShadowRangeListener : public SGPropertyChangeListener {
498 virtual void valueChanged(SGPropertyNode* node) {
499 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
504 FGRenderer::addChangeListener(SGPropertyChangeListener* l, const char* path)
506 _listeners.push_back(l);
507 fgAddChangeListener(l, path);
511 FGRenderer::init( void )
514 eventHandler = new FGEventHandler();
516 sgUserDataInit( globals->get_props() );
518 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
519 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
520 addChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
521 addChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
522 ShadowRangeListener* srl = new ShadowRangeListener;
523 addChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
524 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
525 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
526 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
527 addChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
528 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
529 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
530 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
531 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
532 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
533 updateCascadeNumber(_numCascades);
534 updateCascadeFar(0, _cascadeFar[0]);
535 updateCascadeFar(1, _cascadeFar[1]);
536 updateCascadeFar(2, _cascadeFar[2]);
537 updateCascadeFar(3, _cascadeFar[3]);
538 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
539 _depthInColor->set( _useColorForDepth );
541 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
542 if (!_classicalRenderer)
543 _pipeline = makeRenderingPipeline(_renderer, 0);
544 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
545 _position_finalized = fgGetNode("/sim/position-finalized", true);
547 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
548 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
550 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
552 _xsize = fgGetNode("/sim/startup/xsize", true);
553 _ysize = fgGetNode("/sim/startup/ysize", true);
554 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
556 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
557 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
558 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
559 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
561 _altitude_ft = fgGetNode("/position/altitude-ft", true);
563 _cloud_status = fgGetNode("/environment/clouds/status", true);
564 _visibility_m = fgGetNode("/environment/visibility-m", true);
566 bool use_point_sprites = _point_sprites->getBoolValue();
567 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
568 bool distance_attenuation = _distance_attenuation->getBoolValue();
570 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
571 distance_attenuation );
573 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
574 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
575 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
576 strcmp(tc, "none") == 0) {
577 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
578 } else if (strcmp(tc, "arb") == 0) {
579 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
580 } else if (strcmp(tc, "dxt1") == 0) {
581 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
582 } else if (strcmp(tc, "dxt3") == 0) {
583 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
584 } else if (strcmp(tc, "dxt5") == 0) {
585 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
587 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
591 // create sky, but can't build until setupView, since we depend
592 // on other subsystems to be inited, eg Ephemeris
595 SGPath texture_path(globals->get_fg_root());
596 texture_path.append("Textures");
597 texture_path.append("Sky");
598 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
599 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
600 _sky->add_cloud_layer(layer);
603 _sky->texture_path( texture_path.str() );
605 if (!_classicalRenderer) {
606 eventHandler->setChangeStatsCameraRenderOrder( true );
610 void installCullVisitor(Camera* camera)
612 osgViewer::Renderer* renderer
613 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
614 for (int i = 0; i < 2; ++i) {
615 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
617 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
618 identifier = sceneView->getCullVisitor()->getIdentifier();
619 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
620 sceneView->getCullVisitor()->setIdentifier(identifier.get());
622 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
623 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
624 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
626 identifier = sceneView->getCullVisitorRight()->getIdentifier();
627 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
628 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
634 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
636 const Matrix& projection,
637 osg::GraphicsContext* gc,
638 bool useMasterSceneData)
640 CameraInfo* info = 0;
641 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
642 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
647 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
648 _classicalRenderer = true;
649 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
654 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
655 const osg::Matrix& view,
656 const osg::Matrix& projection,
657 bool useMasterSceneData)
659 CameraInfo* info = new CameraInfo(flags);
660 // The camera group will always update the camera
661 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
662 info->name = "classic";
664 Camera* farCamera = 0;
665 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
666 farCamera = new Camera;
667 farCamera->setName("farCamera");
668 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
669 farCamera->setGraphicsContext(camera->getGraphicsContext());
670 farCamera->setCullingMode(camera->getCullingMode());
671 farCamera->setInheritanceMask(camera->getInheritanceMask());
672 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
673 // Each camera's viewport is written when the window is
674 // resized; if the the viewport isn't copied here, it gets updated
675 // twice and ends up with the wrong value.
676 farCamera->setViewport(simgear::clone(camera->getViewport()));
677 farCamera->setDrawBuffer(camera->getDrawBuffer());
678 farCamera->setReadBuffer(camera->getReadBuffer());
679 farCamera->setRenderTargetImplementation(
680 camera->getRenderTargetImplementation());
681 const Camera::BufferAttachmentMap& bufferMap
682 = camera->getBufferAttachmentMap();
683 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
685 Camera::COLOR_BUFFER,
686 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
688 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
689 installCullVisitor(farCamera);
690 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
691 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
692 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
693 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
694 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
696 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
697 installCullVisitor(camera);
698 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
699 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
700 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
701 cgroup->addCamera(info);
705 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
707 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
708 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
709 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
710 osg::Camera* camera = static_cast<osg::Camera*>(n);
712 cv->clearBufferList();
713 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
714 cv->addBuffer(ii->first, ii->second.texture);
717 if ( !info->getRenderStageInfo(kind).fullscreen )
718 info->setMatrices( camera );
721 osg::Matrix projInverse;
722 info->projInverse->get( projInverse );
724 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
725 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
726 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
729 cv->traverse( *camera );
731 if ( kind == GEOMETRY_CAMERA ) {
732 // Remove transparent bins. They will be renderer in the additional light stage (side effect)
733 osgUtil::RenderStage* renderStage = cv->getRenderStage();
734 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
735 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
736 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
742 } else if ( kind == LIGHTING_CAMERA ) {
743 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
744 if (mainShadowCamera.valid()) {
745 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
746 for (int i = 0; i < 4; ++i ) {
747 if (!grp->getValue(i))
750 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
751 osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
752 cascadeCam->getViewMatrix() *
753 cascadeCam->getProjectionMatrix() *
754 osg::Matrix::translate(1.0, 1.0, 1.0) *
755 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
757 info->shadowMatrix[i]->set( shadowMatrix );
769 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
771 osg::Texture2D* tex = new osg::Texture2D;
772 tex->setResizeNonPowerOfTwoHint( false );
773 tex->setInternalFormat( internalFormat );
774 tex->setShadowComparison(shadowComparison);
775 if (shadowComparison) {
776 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
777 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
779 tex->setSourceFormat(sourceFormat);
780 tex->setSourceType(sourceType);
781 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
782 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
783 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
784 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
788 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
790 camera->attach( c, info->getBuffer(bk) );
791 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
794 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
795 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
796 if (attachment->valid())
797 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
801 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
803 osg::Camera* camera = new osg::Camera;
804 info->addCamera(name, camera );
806 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
807 camera->setName( "GeometryC" );
808 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
809 camera->setGraphicsContext( gc );
810 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
811 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
812 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
813 camera->setClearDepth( 1.0 );
814 camera->setColorMask(true, true, true, true);
815 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
816 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
817 camera->setViewport( new osg::Viewport );
818 buildAttachments(info, camera, name, attachments);
819 camera->setDrawBuffer(GL_FRONT);
820 camera->setReadBuffer(GL_FRONT);
822 osg::StateSet* ss = camera->getOrCreateStateSet();
823 ss->addUniform( _depthInColor );
825 camera->addChild( _deferredRealRoot.get() );
830 static void setShadowCascadeStateSet( osg::Camera* cam ) {
831 osg::StateSet* ss = cam->getOrCreateStateSet();
832 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
833 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
834 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
835 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
836 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
837 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
838 osg::Program* program = new osg::Program;
839 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
840 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
841 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
842 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
843 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
844 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
845 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
846 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
847 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
850 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
851 osg::Camera* cascadeCam = new osg::Camera;
852 setShadowCascadeStateSet( cascadeCam );
854 std::ostringstream oss;
855 oss << "CascadeCamera" << (no + 1);
856 cascadeCam->setName( oss.str() );
857 cascadeCam->setClearMask(0);
858 cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
859 cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
860 cascadeCam->setAllowEventFocus(false);
861 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
862 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
863 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
864 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
868 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
870 osg::Camera* mainShadowCamera = new osg::Camera;
871 info->addCamera(name, mainShadowCamera, 0.0f );
873 mainShadowCamera->setName( "ShadowC" );
874 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
875 mainShadowCamera->setClearDepth( 1.0 );
876 mainShadowCamera->setAllowEventFocus(false);
877 mainShadowCamera->setGraphicsContext(gc);
878 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
879 buildAttachments(info, mainShadowCamera, name, attachments);
880 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
881 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
882 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
883 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
884 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
885 mainShadowCamera->setDrawBuffer(GL_FRONT);
886 mainShadowCamera->setReadBuffer(GL_FRONT);
887 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
889 osg::Switch* shadowSwitch = new osg::Switch;
890 mainShadowCamera->addChild( shadowSwitch );
892 for (int i = 0; i < 4; ++i ) {
893 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
894 cascadeCam->addChild( _deferredRealRoot.get() );
895 shadowSwitch->addChild( cascadeCam );
897 if (fgGetBool("/sim/rendering/shadows/enabled", true))
898 shadowSwitch->setAllChildrenOn();
900 shadowSwitch->setAllChildrenOff();
902 return mainShadowCamera;
905 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)
907 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
908 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
909 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
911 osg::BoundingSphere bs;
912 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
913 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
914 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
915 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
917 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
919 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
920 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
921 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
924 osg::Vec3 FGRenderer::getSunDirection() const
927 _sunDirection->get( val );
931 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
933 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
934 if (mainShadowCamera.valid()) {
935 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
936 osg::Vec3d up = position,
937 dir = getSunDirection();
940 // cos(100 deg) == -0.17
941 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
942 shadowSwitch->setAllChildrenOff();
944 double left,right,bottom,top,zNear,zFar;
945 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
946 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
948 shadowSwitch->setAllChildrenOn();
949 if (_numCascades == 1) {
950 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
951 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
953 for (int no = 0; no < 4; ++no) {
954 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
955 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
958 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
959 if (_numCascades > 1) {
960 shadowSwitch->setValue(1, true);
961 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
963 shadowSwitch->setValue(1, false);
965 if (_numCascades > 2) {
966 shadowSwitch->setValue(2, true);
967 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
969 shadowSwitch->setValue(2, false);
971 if (_numCascades > 3) {
972 shadowSwitch->setValue(3, true);
973 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
975 shadowSwitch->setValue(3, false);
978 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
980 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
982 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
983 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
989 void FGRenderer::updateShadowMapSize(int mapSize)
991 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
992 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
995 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
996 ii != CameraGroup::getDefault()->camerasEnd();
999 CameraInfo* info = ii->get();
1000 Camera* camera = info->getCamera(SHADOW_CAMERA);
1001 if (camera == 0) continue;
1003 Texture2D* tex = info->getBuffer("shadow");
1004 if (tex == 0) continue;
1006 tex->setTextureSize( mapSize, mapSize );
1007 tex->dirtyTextureObject();
1009 Viewport* vp = camera->getViewport();
1010 vp->width() = mapSize;
1011 vp->height() = mapSize;
1013 osgViewer::Renderer* renderer
1014 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1015 for (int i = 0; i < 2; ++i) {
1016 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1017 sceneView->getRenderStage()->setFrameBufferObject(0);
1018 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1019 if (sceneView->getRenderStageLeft()) {
1020 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1021 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1023 if (sceneView->getRenderStageRight()) {
1024 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1025 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1029 int cascadeSize = mapSize / 2;
1030 Group* grp = camera->getChild(0)->asGroup();
1031 for (int i = 0; i < 4; ++i ) {
1032 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1033 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1036 _shadowMapSize = mapSize;
1040 void FGRenderer::enableShadows(bool enabled)
1042 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1043 ii != CameraGroup::getDefault()->camerasEnd();
1046 CameraInfo* info = ii->get();
1047 Camera* camera = info->getCamera(SHADOW_CAMERA);
1048 if (camera == 0) continue;
1050 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1052 shadowSwitch->setAllChildrenOn();
1054 shadowSwitch->setAllChildrenOff();
1058 void FGRenderer::updateCascadeFar(int index, float far_m)
1060 if (index < 0 || index > 3)
1062 _cascadeFar[index] = far_m;
1063 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1066 void FGRenderer::updateCascadeNumber(size_t num)
1068 if (num < 1 || num > 4)
1071 _shadowNumber->set( (int)_numCascades );
1074 class DebugPassListener : public SGPropertyChangeListener {
1076 DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1077 virtual void valueChanged(SGPropertyNode* node) {
1078 _switch->setValue(_index, node->getBoolValue());
1082 osg::ref_ptr<osg::Switch> _switch;
1087 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1089 osg::Camera* camera = new osg::Camera;
1090 info->addCamera(stage->name, camera );
1092 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1093 camera->setAllowEventFocus(false);
1094 camera->setGraphicsContext(gc);
1095 camera->setViewport(new Viewport);
1096 camera->setName(stage->name+"C");
1097 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1098 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1099 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1100 camera->setViewport( new osg::Viewport );
1101 buildAttachments(info, camera, stage->name, stage->attachments);
1102 camera->setDrawBuffer(GL_FRONT);
1103 camera->setReadBuffer(GL_FRONT);
1104 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1105 osg::StateSet* ss = camera->getOrCreateStateSet();
1106 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1107 ss->addUniform( _depthInColor );
1109 osg::Switch* lightingGroup = new osg::Switch;
1111 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1112 ref_ptr<Node> node = buildPass(info, pass);
1114 lightingGroup->addChild(node);
1115 if (!pass->debugProperty.empty()) {
1116 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1117 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1122 camera->addChild( lightingGroup );
1128 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1129 const osg::Matrix& view,
1130 const osg::Matrix& projection,
1131 osg::GraphicsContext* gc)
1133 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1137 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1139 osg::Camera* camera = new osg::Camera;
1141 camera->setClearMask( 0 );
1142 camera->setAllowEventFocus(false);
1143 camera->setName(pass->name+"C");
1144 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1145 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1146 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1147 camera->setViewMatrix(osg::Matrix::identity());
1148 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1150 osg::StateSet* ss = camera->getOrCreateStateSet();
1151 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1152 ss->addUniform( info->projInverse );
1153 ss->addUniform( info->viewInverse );
1154 ss->addUniform( info->view );
1155 ss->addUniform( info->bufferSize );
1156 ss->addUniform( info->worldPosCart );
1157 ss->addUniform( info->worldPosGeod );
1158 ss->addUniform( info->shadowMatrix[0] );
1159 ss->addUniform( info->shadowMatrix[1] );
1160 ss->addUniform( info->shadowMatrix[2] );
1161 ss->addUniform( info->shadowMatrix[3] );
1162 ss->addUniform( _ambientFactor );
1163 ss->addUniform( _sunDiffuse );
1164 ss->addUniform( _sunSpecular );
1165 ss->addUniform( _sunDirection );
1166 ss->addUniform( _planes );
1167 ss->addUniform( _shadowNumber );
1168 ss->addUniform( _shadowDistances );
1169 ss->addUniform( _fogColor );
1170 ss->addUniform( _fogDensity );
1172 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1173 g->setUseDisplayList(false);
1174 simgear::EffectGeode* eg = new simgear::EffectGeode;
1175 osg::ref_ptr<SGReaderWriterOptions> opt;
1176 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1177 opt->setPropertyNode(globals->get_props());
1178 simgear::Effect* effect = simgear::makeEffect(pass->effect, true, opt.get());
1180 eg->setEffect( effect );
1183 eg->setName(pass->name+"Quad");
1184 eg->setCullingActive(false);
1186 camera->addChild(eg);
1192 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1194 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1195 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1197 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1198 camera->setGraphicsContext(gc);
1199 camera->setViewport(new Viewport);
1200 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1201 buildAttachments(info, camera, stage->name, stage->attachments);
1202 camera->setDrawBuffer(GL_FRONT);
1203 camera->setReadBuffer(GL_FRONT);
1204 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1205 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1206 camera->setViewMatrix(osg::Matrix::identity());
1207 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1209 osg::StateSet* ss = camera->getOrCreateStateSet();
1210 if (stage->needsDuDv) {
1211 ss->addUniform( info->du );
1212 ss->addUniform( info->dv );
1219 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1221 camera->setName( "DisplayC" );
1222 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1223 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1224 camera->setAllowEventFocus(false);
1225 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1226 g->setUseDisplayList(false); //DEBUG
1227 simgear::EffectGeode* eg = new simgear::EffectGeode;
1228 osg::ref_ptr<SGReaderWriterOptions> opt;
1229 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1230 opt->setPropertyNode(globals->get_props());
1231 simgear::Effect* effect = simgear::makeEffect(stage->effect, true, opt.get());
1233 SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1236 eg->setEffect(effect);
1237 eg->setCullingActive(false);
1239 camera->setViewMatrix(osg::Matrix::identity());
1240 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1241 camera->addChild(eg);
1243 osg::StateSet* ss = camera->getOrCreateStateSet();
1244 ss->addUniform( _depthInColor );
1245 ss->addUniform( info->projInverse );
1246 ss->addUniform( info->viewInverse );
1247 ss->addUniform( info->view );
1248 ss->addUniform( info->bufferSize );
1249 ss->addUniform( info->worldPosCart );
1250 ss->addUniform( info->worldPosGeod );
1251 ss->addUniform( info->shadowMatrix[0] );
1252 ss->addUniform( info->shadowMatrix[1] );
1253 ss->addUniform( info->shadowMatrix[2] );
1254 ss->addUniform( info->shadowMatrix[3] );
1255 ss->addUniform( _ambientFactor );
1256 ss->addUniform( _sunDiffuse );
1257 ss->addUniform( _sunSpecular );
1258 ss->addUniform( _sunDirection );
1259 ss->addUniform( _planes );
1260 ss->addUniform( _shadowNumber );
1261 ss->addUniform( _shadowDistances );
1262 ss->addUniform( _fogColor );
1263 ss->addUniform( _fogDensity );
1267 FGRenderer::buildStage(CameraInfo* info,
1268 FGRenderingPipeline::Stage* stage,
1269 CameraGroup* cgroup,
1270 osg::Camera* mainCamera,
1271 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1273 if (!stage->valid())
1276 ref_ptr<Camera> camera;
1277 bool needOffsets = false;
1278 if (stage->type == "geometry") {
1279 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1281 } else if (stage->type == "lighting") {
1282 camera = buildDeferredLightingCamera(info, gc, stage);
1284 } else if (stage->type == "shadow")
1285 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1286 else if (stage->type == "fullscreen")
1287 camera = buildDeferredFullscreenCamera(info, gc, stage);
1288 else if (stage->type == "display") {
1289 camera = mainCamera;
1290 buildDeferredDisplayCamera(camera, info, stage, gc);
1292 throw sg_exception("Stage type is not supported");
1295 cgroup->getViewer()->addSlave(camera, projection, view, false);
1297 cgroup->getViewer()->addSlave(camera, false);
1298 installCullVisitor(camera);
1299 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1300 if (stage->type == "display")
1301 info->addCamera( stage->type, camera, slaveIndex, true );
1302 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1306 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1308 Group* group = new Group;
1309 group->setName("skyCloudsGroup");
1310 group->setNodeMask(simgear::BACKGROUND_BIT);
1312 StateSet* ss = group->getOrCreateStateSet();
1313 ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1314 group->addChild( _sky->getPreRoot() );
1315 group->addChild( _sky->getCloudRoot() );
1320 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1322 osg::Camera* lightCam = new osg::Camera;
1323 StateSet* ss = lightCam->getOrCreateStateSet();
1324 ss->addUniform( _planes );
1325 ss->addUniform( info->bufferSize );
1326 ss->addUniform( _fogColor );
1327 ss->addUniform( _fogDensity );
1328 lightCam->setName( "LightCamera" );
1329 lightCam->setClearMask(0);
1330 lightCam->setAllowEventFocus(false);
1331 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1332 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1333 lightCam->setViewMatrix(osg::Matrix::identity());
1334 lightCam->setProjectionMatrix(osg::Matrix::identity());
1335 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1336 lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1337 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1338 lightCam->addChild( _deferredRealRoot.get() );
1344 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1350 if (pass->type == "sky-clouds")
1351 node = buildLightingSkyCloudsPass(pass);
1352 else if (pass->type == "fullscreen")
1353 node = buildDeferredFullscreenCamera(info, pass);
1354 else if (pass->type == "lights")
1355 node = buildLightingLightsPass(info, pass);
1357 throw sg_exception("Pass type is not supported");
1359 return node.release();
1363 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1365 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1366 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1367 if (buffer->valid()) {
1368 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1369 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1370 buffer->sourceFormat,
1373 buffer->shadowComparison),
1374 fullscreen ? buffer->scaleFactor : 0.0f);
1376 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1382 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1383 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1385 CameraInfo* info = new CameraInfo(flags);
1386 buildBuffers(rpipe, info);
1388 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1389 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1390 buildStage(info, stage, cgroup, camera, view, projection, gc);
1393 cgroup->addCamera(info);
1398 void FGRenderer::setupRoot()
1400 osg::StateSet* stateSet = _root->getOrCreateStateSet();
1402 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1404 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1405 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1407 stateSet->setAttribute(new osg::BlendFunc);
1408 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1410 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1412 // this will be set below
1413 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1415 osg::Material* material = new osg::Material;
1416 stateSet->setAttribute(material);
1418 stateSet->setTextureAttribute(0, new osg::TexEnv);
1419 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1421 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1422 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1423 stateSet->setAttribute(hint);
1424 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1425 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1426 stateSet->setAttribute(hint);
1427 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1428 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1429 stateSet->setAttribute(hint);
1430 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1431 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1432 stateSet->setAttribute(hint);
1433 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1434 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1435 stateSet->setAttribute(hint);
1439 FGRenderer::setupView( void )
1441 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1442 osg::initNotifyLevel();
1444 // The number of polygon-offset "units" to place between layers. In
1445 // principle, one is supposed to be enough. In practice, I find that
1446 // my hardware/driver requires many more.
1447 osg::PolygonOffset::setUnitsMultiplier(1);
1448 osg::PolygonOffset::setFactorMultiplier(1);
1453 Ephemeris* ephemerisSub = globals->get_subsystem<Ephemeris>();
1456 // The sun and moon diameters are scaled down numbers of the
1457 // actual diameters. This was needed to fit both the sun and the
1458 // moon within the distance to the far clip plane.
1459 // Moon diameter: 3,476 kilometers
1460 // Sun diameter: 1,390,000 kilometers
1461 osg::ref_ptr<SGReaderWriterOptions> opt;
1462 opt = SGReaderWriterOptions::fromPath(globals->get_fg_root());
1463 opt->setPropertyNode(globals->get_props());
1464 _sky->build( 80000.0, 80000.0,
1466 *ephemerisSub->data(),
1467 fgGetNode("/environment", true),
1471 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1474 // need to update the light on every frame
1475 // OSG LightSource objects are rather confusing. OSG only supports
1476 // the 10 lights specified by OpenGL itself; if more than one
1477 // LightSource in the scene graph have the same light number, it's
1478 // indeterminate which values will be used to render geometry that
1479 // has that light number enabled. Also, adding children to a
1480 // LightSource is just a shortcut for setting up a state set that
1481 // has the corresponding OpenGL light enabled: a LightSource will
1482 // affect geometry anywhere in the scene graph that has its light
1483 // number enabled in a state set.
1484 osg::ref_ptr<LightSource> lightSource = new LightSource;
1485 lightSource->setName("FGLightSource");
1486 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1487 // relative because of CameraView being just a clever transform node
1488 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1489 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1490 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1491 _viewerSceneRoot->addChild(lightSource);
1493 // we need a white diffuse light for the phase of the moon
1494 osg::ref_ptr<LightSource> sunLight = new osg::LightSource;
1495 sunLight->setName("sunLightSource");
1496 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1497 sunLight->getLight()->setLightNum(1);
1498 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1499 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1500 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1502 // Hang a StateSet above the sky subgraph in order to turn off
1504 Group* skyGroup = _sky->getPreRoot();
1505 StateSet* skySS = skyGroup->getOrCreateStateSet();
1506 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1507 sunLight->addChild(skyGroup);
1509 if ( _classicalRenderer ) {
1510 _root->addChild(sunLight);
1513 osg::Group* sceneGroup = globals->get_scenery()->get_scene_graph();
1514 sceneGroup->setName("rendererScene");
1515 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1516 _root->addChild(sceneGroup);
1518 // setup state-set for main scenery (including models and aircraft)
1519 osg::StateSet* stateSet = sceneGroup->getOrCreateStateSet();
1520 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1521 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1523 // enable disable specular highlights.
1524 // is the place where we might plug in an other fragment shader ...
1525 osg::LightModel* lightModel = new osg::LightModel;
1526 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1527 stateSet->setAttribute(lightModel);
1529 // switch to enable wireframe
1530 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1531 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1532 stateSet->setAttributeAndModes(polygonMode);
1534 // scene fog handling
1535 osg::Fog* fog = new osg::Fog;
1536 fog->setUpdateCallback(new FGFogUpdateCallback);
1537 stateSet->setAttributeAndModes(fog);
1538 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1541 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1543 osg::Geode* geode = new osg::Geode;
1544 geode->addDrawable(new SGHUDDrawable);
1545 geode->addDrawable(new SGPuDrawable);
1547 // Draw first (eg. before Canvas GUI)
1548 guiCamera->insertChild(0, geode);
1549 guiCamera->insertChild(0, FGPanelNode::create2DPanelNode());
1552 osg::Switch* sw = new osg::Switch;
1553 sw->setName("scenerySwitch");
1554 sw->setUpdateCallback(new FGScenerySwitchCallback);
1555 sw->addChild(_root.get());
1556 _viewerSceneRoot->addChild(sw);
1557 // The clouds are attached directly to the scene graph root
1558 // because, in theory, they don't want the same default state set
1559 // as the rest of the scene. This may not be true in practice.
1560 if ( _classicalRenderer ) {
1561 _viewerSceneRoot->addChild(_sky->getCloudRoot());
1562 _viewerSceneRoot->addChild(FGCreateRedoutNode());
1565 // Attach empty program to the scene root so that shader programs
1566 // don't leak into state sets (effects) that shouldn't have one.
1567 stateSet = _viewerSceneRoot->getOrCreateStateSet();
1568 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1570 if ( !_classicalRenderer ) {
1571 _deferredRealRoot->addChild( _viewerSceneRoot.get() );
1575 // Update all Visuals (redraws anything graphics related)
1577 FGRenderer::update( ) {
1578 if (!_position_finalized || !_scenery_loaded->getBoolValue())
1580 _splash_alpha->setDoubleValue(1.0);
1583 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1585 if (_splash_alpha->getDoubleValue()>0.0)
1587 // Fade out the splash screen
1588 const double fade_time = 0.5;
1589 const double fade_steps_per_sec = 10;
1590 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1591 (SGTimeStamp::now() - _splash_time).toSecs());
1592 _splash_time = SGTimeStamp::now();
1593 double sAlpha = _splash_alpha->getDoubleValue();
1594 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1595 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1596 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1598 syncPausePopupState();
1601 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1602 if (!_classicalRenderer ) {
1603 _ambientFactor->set( toOsg(l->scene_ambient()) );
1604 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1605 _sunSpecular->set( toOsg(l->scene_specular()) );
1606 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1609 // update fog params
1610 double actual_visibility;
1611 if (_cloud_status->getBoolValue()) {
1612 actual_visibility = _sky->get_visibility();
1614 actual_visibility = _visibility_m->getDoubleValue();
1617 // idle_state is now 1000 meaning we've finished all our
1618 // initializations and are running the main loop, so this will
1619 // now work without seg faulting the system.
1621 flightgear::View *current__view = globals->get_current_view();
1622 // Force update of center dependent values ...
1623 current__view->set_dirty();
1625 osg::Camera *camera = viewer->getCamera();
1627 osg::Vec4 clear_color = _altitude_ft->getDoubleValue() < 250000
1628 ? toOsg(l->adj_fog_color())
1629 // skydome ends at ~262000ft (default rendering)
1630 // ~328000 ft (ALS) and would produce a strange
1631 // looking greyish space -> black looks much
1633 : osg::Vec4(0, 0, 0, 1);
1634 camera->setClearColor(clear_color);
1638 // need to call the update visitor once
1639 _frameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1640 _updateVisitor->setViewData(current__view->getViewPosition(),
1641 current__view->getViewOrientation());
1642 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1643 _updateVisitor->setLight(direction, l->scene_ambient(),
1644 l->scene_diffuse(), l->scene_specular(),
1646 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1647 _updateVisitor->setVisibility(actual_visibility);
1648 simgear::GroundLightManager::instance()->update(_updateVisitor.get());
1649 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1650 cullMask |= simgear::GroundLightManager::instance()
1651 ->getLightNodeMask(_updateVisitor.get());
1652 if (_panel_hotspots->getBoolValue())
1653 cullMask |= simgear::PICK_BIT;
1654 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1655 if ( !_classicalRenderer ) {
1656 _fogColor->set( toOsg( l->adj_fog_color() ) );
1657 _fogDensity->set( float( _updateVisitor->getFogExp2Density() ) );
1662 FGRenderer::updateSky()
1664 // update fog params if visibility has changed
1665 double visibility_meters = _visibility_m->getDoubleValue();
1666 _sky->set_visibility(visibility_meters);
1668 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1669 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1671 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1673 // The sun and moon distances are scaled down versions
1674 // of the actual distance to get both the moon and the sun
1675 // within the range of the far clip plane.
1676 // Moon distance: 384,467 kilometers
1677 // Sun distance: 150,000,000 kilometers
1679 double sun_horiz_eff, moon_horiz_eff;
1680 if (_horizon_effect->getBoolValue()) {
1682 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1686 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1690 sun_horiz_eff = moon_horiz_eff = 1.0;
1696 sstate.pos = globals->get_current_view()->getViewPosition();
1697 sstate.pos_geod = globals->get_current_view()->getPosition();
1698 sstate.ori = globals->get_current_view()->getViewOrientation();
1699 sstate.spin = l->get_sun_rotation();
1700 sstate.gst = globals->get_time_params()->getGst();
1701 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1702 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1703 sstate.sun_angle = l->get_sun_angle();
1706 scolor.sky_color = SGVec3f(l->sky_color().data());
1707 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1708 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1709 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1710 scolor.sun_angle = l->get_sun_angle();
1711 scolor.moon_angle = l->get_moon_angle();
1713 Ephemeris* ephemerisSub = globals->get_subsystem<Ephemeris>();
1714 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1715 _sky->reposition( sstate, *ephemerisSub->data(), delta_time_sec );
1716 _sky->repaint( scolor, *ephemerisSub->data() );
1720 FGRenderer::resize( int width, int height )
1722 int curWidth = _xsize->getIntValue(),
1723 curHeight = _ysize->getIntValue();
1724 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1725 if ((curHeight != height) || (curWidth != width)) {
1726 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1727 _xsize->setIntValue(width);
1728 _ysize->setIntValue(height);
1732 typedef osgUtil::LineSegmentIntersector::Intersection Intersection;
1733 SGVec2d uvFromIntersection(const Intersection& hit)
1735 // Taken from http://trac.openscenegraph.org/projects/osg/browser/OpenSceneGraph/trunk/examples/osgmovie/osgmovie.cpp
1737 osg::Drawable* drawable = hit.drawable.get();
1738 osg::Geometry* geometry = drawable ? drawable->asGeometry() : 0;
1739 osg::Vec3Array* vertices =
1740 geometry ? dynamic_cast<osg::Vec3Array*>(geometry->getVertexArray()) : 0;
1744 SG_LOG(SG_INPUT, SG_WARN, "Unable to get vertices for intersection.");
1745 return SGVec2d(-9999,-9999);
1748 // get the vertex indices.
1749 const Intersection::IndexList& indices = hit.indexList;
1750 const Intersection::RatioList& ratios = hit.ratioList;
1752 if( indices.size() != 3 || ratios.size() != 3 )
1756 "Intersection has insufficient indices to work with." );
1757 return SGVec2d(-9999,-9999);
1760 unsigned int i1 = indices[0];
1761 unsigned int i2 = indices[1];
1762 unsigned int i3 = indices[2];
1764 float r1 = ratios[0];
1765 float r2 = ratios[1];
1766 float r3 = ratios[2];
1768 osg::Array* texcoords =
1769 (geometry->getNumTexCoordArrays() > 0) ? geometry->getTexCoordArray(0) : 0;
1770 osg::Vec2Array* texcoords_Vec2Array =
1771 dynamic_cast<osg::Vec2Array*>(texcoords);
1773 if( !texcoords_Vec2Array )
1775 SG_LOG(SG_INPUT, SG_WARN, "Unable to get texcoords for intersection.");
1776 return SGVec2d(-9999,-9999);
1779 // we have tex coord array so now we can compute the final tex coord at the
1780 // point of intersection.
1781 osg::Vec2 tc1 = (*texcoords_Vec2Array)[i1];
1782 osg::Vec2 tc2 = (*texcoords_Vec2Array)[i2];
1783 osg::Vec2 tc3 = (*texcoords_Vec2Array)[i3];
1785 return toSG( osg::Vec2d(tc1 * r1 + tc2 * r2 + tc3 * r3) );
1789 FGRenderer::pick(std::vector<SGSceneryPick>& pickList, const osg::Vec2& windowPos)
1791 // wipe out the return ...
1793 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1794 Intersections intersections;
1796 if (!computeIntersections(CameraGroup::getDefault(), windowPos, intersections))
1798 for (Intersections::iterator hit = intersections.begin(),
1799 e = intersections.end();
1802 const osg::NodePath& np = hit->nodePath;
1803 osg::NodePath::const_reverse_iterator npi;
1805 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1806 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1807 if (!ud || (ud->getNumPickCallbacks() == 0))
1810 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1811 SGPickCallback* pickCallback = ud->getPickCallback(i);
1814 SGSceneryPick sceneryPick;
1815 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1816 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1818 if( pickCallback->needsUV() )
1819 sceneryPick.info.uv = uvFromIntersection(*hit);
1821 sceneryPick.callback = pickCallback;
1822 pickList.push_back(sceneryPick);
1823 } // of installed pick callbacks iteration
1824 } // of reverse node path walk
1827 return !pickList.empty();
1831 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1837 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1839 eventHandler = eventHandler_;
1843 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1845 _viewerSceneRoot->addChild(camera);
1849 FGRenderer::removeCamera(osg::Camera* camera)
1851 _viewerSceneRoot->removeChild(camera);
1855 FGRenderer::setPlanes( double zNear, double zFar )
1857 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1861 fgDumpSceneGraphToFile(const char* filename)
1863 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1864 return osgDB::writeNodeFile(*viewer->getSceneData(), filename);
1868 fgDumpTerrainBranchToFile(const char* filename)
1870 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1876 fgDumpNodeToFile(osg::Node* node, const char* filename)
1878 return osgDB::writeNodeFile(*node, filename);
1881 namespace flightgear
1883 using namespace osg;
1885 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1888 VisibleSceneInfoVistor()
1889 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1891 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1892 | CullSettings::VIEW_FRUSTUM_CULLING);
1893 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1896 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1900 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1902 typedef std::map<const std::string,int> InfoMap;
1904 void getNodeInfo(Node* node)
1906 const char* typeName = typeid(*node).name();
1907 classInfo[typeName]++;
1908 const std::string& nodeName = node->getName();
1909 if (!nodeName.empty())
1910 nodeInfo[nodeName]++;
1915 using namespace std;
1916 typedef vector<InfoMap::iterator> FreqVector;
1917 cout << "class info:\n";
1919 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1922 classes.push_back(itr);
1923 sort(classes.begin(), classes.end(), freqComp);
1924 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1927 cout << (*itr)->first << " " << (*itr)->second << "\n";
1929 cout << "\nnode info:\n";
1931 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1934 nodes.push_back(itr);
1936 sort (nodes.begin(), nodes.end(), freqComp);
1937 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1940 cout << (*itr)->first << " " << (*itr)->second << "\n";
1945 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1947 ref_ptr<RefMatrix> projection
1948 = createOrReuseMatrix(camera->getProjectionMatrix());
1949 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1951 viewport = camera->getViewport();
1953 pushViewport(viewport);
1954 pushProjectionMatrix(projection.get());
1955 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1956 root->accept(*this);
1957 popModelViewMatrix();
1958 popProjectionMatrix();
1964 void apply(Node& node)
1973 void apply(Group& node)
1983 void apply(Transform& node)
1988 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1989 node.computeLocalToWorldMatrix(*matrix,this);
1990 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1993 popModelViewMatrix();
1997 void apply(Camera& camera)
1999 // Save current cull settings
2000 CullSettings saved_cull_settings(*this);
2002 // set cull settings from this Camera
2003 setCullSettings(camera);
2004 // inherit the settings from above
2005 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
2007 // set the cull mask.
2008 unsigned int savedTraversalMask = getTraversalMask();
2009 bool mustSetCullMask = (camera.getInheritanceMask()
2010 & osg::CullSettings::CULL_MASK) == 0;
2011 if (mustSetCullMask)
2012 setTraversalMask(camera.getCullMask());
2014 osg::RefMatrix* projection = 0;
2015 osg::RefMatrix* modelview = 0;
2017 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
2018 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
2019 projection = createOrReuseMatrix(*getProjectionMatrix()
2020 *camera.getProjectionMatrix());
2021 modelview = createOrReuseMatrix(*getModelViewMatrix()
2022 * camera.getViewMatrix());
2024 else { // pre multiply
2025 projection = createOrReuseMatrix(camera.getProjectionMatrix()
2026 * (*getProjectionMatrix()));
2027 modelview = createOrReuseMatrix(camera.getViewMatrix()
2028 * (*getModelViewMatrix()));
2031 // an absolute reference frame
2032 projection = createOrReuseMatrix(camera.getProjectionMatrix());
2033 modelview = createOrReuseMatrix(camera.getViewMatrix());
2035 if (camera.getViewport())
2036 pushViewport(camera.getViewport());
2038 pushProjectionMatrix(projection);
2039 pushModelViewMatrix(modelview, camera.getReferenceFrame());
2043 // restore the previous model view matrix.
2044 popModelViewMatrix();
2046 // restore the previous model view matrix.
2047 popProjectionMatrix();
2049 if (camera.getViewport()) popViewport();
2051 // restore the previous traversal mask settings
2052 if (mustSetCullMask)
2053 setTraversalMask(savedTraversalMask);
2055 // restore the previous cull settings
2056 setCullSettings(saved_cull_settings);
2061 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
2063 return lhs->second > rhs->second;
2069 bool printVisibleSceneInfo(FGRenderer* renderer)
2071 osgViewer::Viewer* viewer = renderer->getViewer();
2072 VisibleSceneInfoVistor vsv;
2074 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
2075 const osg::View::Slave& slave = viewer->getSlave(0);
2076 vp = slave._camera->getViewport();
2078 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2083 // end of renderer.cxx