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/model/animation.hxx>
74 #include <simgear/scene/model/placement.hxx>
75 #include <simgear/scene/sky/sky.hxx>
76 #include <simgear/scene/util/SGUpdateVisitor.hxx>
77 #include <simgear/scene/util/RenderConstants.hxx>
78 #include <simgear/scene/util/SGSceneUserData.hxx>
79 #include <simgear/scene/tgdb/GroundLightManager.hxx>
80 #include <simgear/scene/tgdb/pt_lights.hxx>
81 #include <simgear/structure/OSGUtils.hxx>
82 #include <simgear/props/props.hxx>
83 #include <simgear/timing/sg_time.hxx>
84 #include <simgear/ephemeris/ephemeris.hxx>
85 #include <simgear/math/sg_random.h>
87 #include <simgear/screen/jpgfactory.hxx>
90 #include <Time/light.hxx>
91 #include <Time/light.hxx>
92 #include <Cockpit/panel.hxx>
94 #include <Model/panelnode.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/redout.hxx>
99 #include <GUI/new_gui.hxx>
100 #include <Instrumentation/HUD/HUD.hxx>
101 #include <Environment/precipitation_mgr.hxx>
102 #include <Environment/environment_mgr.hxx>
104 //#include <Main/main.hxx>
105 #include "viewer.hxx"
106 #include "viewmgr.hxx"
107 #include "splash.hxx"
108 #include "renderer.hxx"
109 #include "CameraGroup.hxx"
110 #include "FGEventHandler.hxx"
113 using namespace simgear;
114 using namespace flightgear;
116 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
118 FGHintUpdateCallback(const char* configNode) :
119 mConfigNode(fgGetNode(configNode, true))
121 virtual void operator()(osg::StateAttribute* stateAttribute,
124 assert(dynamic_cast<osg::Hint*>(stateAttribute));
125 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
127 const char* value = mConfigNode->getStringValue();
129 hint->setMode(GL_DONT_CARE);
130 else if (0 == strcmp(value, "nicest"))
131 hint->setMode(GL_NICEST);
132 else if (0 == strcmp(value, "fastest"))
133 hint->setMode(GL_FASTEST);
135 hint->setMode(GL_DONT_CARE);
138 SGPropertyNode_ptr mConfigNode;
142 class SGPuDrawable : public osg::Drawable {
146 // Dynamic stuff, do not store geometry
147 setUseDisplayList(false);
148 setDataVariance(Object::DYNAMIC);
150 osg::StateSet* stateSet = getOrCreateStateSet();
151 stateSet->setRenderBinDetails(1001, "RenderBin");
152 // speed optimization?
153 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
154 // We can do translucent menus, so why not. :-)
155 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
156 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
157 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
159 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
161 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
162 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
164 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
165 { drawImplementation(*renderInfo.getState()); }
166 void drawImplementation(osg::State& state) const
168 state.setActiveTextureUnit(0);
169 state.setClientActiveTextureUnit(0);
171 state.disableAllVertexArrays();
173 glPushAttrib(GL_ALL_ATTRIB_BITS);
174 glPushClientAttrib(~0u);
182 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
183 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
188 class SGHUDDrawable : public osg::Drawable {
192 // Dynamic stuff, do not store geometry
193 setUseDisplayList(false);
194 setDataVariance(Object::DYNAMIC);
196 osg::StateSet* stateSet = getOrCreateStateSet();
197 stateSet->setRenderBinDetails(1000, "RenderBin");
199 // speed optimization?
200 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
201 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
202 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
203 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
204 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
206 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
208 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
209 { drawImplementation(*renderInfo.getState()); }
210 void drawImplementation(osg::State& state) const
212 state.setActiveTextureUnit(0);
213 state.setClientActiveTextureUnit(0);
214 state.disableAllVertexArrays();
216 glPushAttrib(GL_ALL_ATTRIB_BITS);
217 glPushClientAttrib(~0u);
219 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
226 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
227 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
232 class FGLightSourceUpdateCallback : public osg::NodeCallback {
236 * @param isSun true if the light is the actual sun i.e., for
237 * illuminating the moon.
239 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
240 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
242 : NodeCallback(nc, op), _isSun(nc._isSun)
244 META_Object(flightgear,FGLightSourceUpdateCallback);
246 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
248 assert(dynamic_cast<osg::LightSource*>(node));
249 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
250 osg::Light* light = lightSource->getLight();
252 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
254 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
255 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
256 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
258 light->setAmbient(toOsg(l->scene_ambient()));
259 light->setDiffuse(toOsg(l->scene_diffuse()));
260 light->setSpecular(toOsg(l->scene_specular()));
262 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
263 light->setPosition(position);
271 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
273 FGWireFrameModeUpdateCallback() :
274 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
276 virtual void operator()(osg::StateAttribute* stateAttribute,
279 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
280 osg::PolygonMode* polygonMode;
281 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
283 if (mWireframe->getBoolValue())
284 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
285 osg::PolygonMode::LINE);
287 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
288 osg::PolygonMode::FILL);
291 SGPropertyNode_ptr mWireframe;
294 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
296 FGLightModelUpdateCallback() :
297 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
299 virtual void operator()(osg::StateAttribute* stateAttribute,
302 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
303 osg::LightModel* lightModel;
304 lightModel = static_cast<osg::LightModel*>(stateAttribute);
307 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
308 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
310 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
312 lightModel->setTwoSided(true);
313 lightModel->setLocalViewer(false);
315 if (mHighlights->getBoolValue()) {
316 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
318 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
322 SGPropertyNode_ptr mHighlights;
325 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
327 FGFogEnableUpdateCallback() :
328 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
330 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
332 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
333 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
335 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
339 SGPropertyNode_ptr mFogEnabled;
342 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
344 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
346 assert(dynamic_cast<SGUpdateVisitor*>(nv));
347 assert(dynamic_cast<osg::Fog*>(sa));
348 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
349 osg::Fog* fog = static_cast<osg::Fog*>(sa);
350 fog->setMode(osg::Fog::EXP2);
351 fog->setColor(toOsg(updateVisitor->getFogColor()));
352 fog->setDensity(updateVisitor->getFogExp2Density());
356 // update callback for the switch node guarding that splash
357 class FGScenerySwitchCallback : public osg::NodeCallback {
359 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
361 assert(dynamic_cast<osg::Switch*>(node));
362 osg::Switch* sw = static_cast<osg::Switch*>(node);
364 bool enabled = scenery_enabled;
365 sw->setValue(0, enabled);
371 static bool scenery_enabled;
374 bool FGScenerySwitchCallback::scenery_enabled = false;
376 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
377 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
379 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
380 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
382 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
384 static osg::ref_ptr<osg::Switch> panelSwitch;
387 // update callback for the switch node controlling the 2D panel
388 class FGPanelSwitchCallback : public osg::NodeCallback {
390 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
392 assert(dynamic_cast<osg::Switch*>(node));
393 osg::Switch* sw = static_cast<osg::Switch*>(node);
395 bool enabled = fgPanelVisible();
396 sw->setValue(0, enabled);
403 #ifdef FG_JPEG_SERVER
404 static void updateRenderer()
406 globals->get_renderer()->update();
410 FGRenderer::FGRenderer() :
412 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
413 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
414 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
415 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
416 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
417 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
418 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
419 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
420 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
421 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
423 #ifdef FG_JPEG_SERVER
424 jpgRenderFrame = updateRenderer;
426 eventHandler = new FGEventHandler;
429 _cascadeFar[0] = 5.f;
430 _cascadeFar[1] = 50.f;
431 _cascadeFar[2] = 500.f;
432 _cascadeFar[3] = 5000.f;
435 FGRenderer::~FGRenderer()
437 #ifdef FG_JPEG_SERVER
438 jpgRenderFrame = NULL;
443 // Initialize various GL/view parameters
444 // XXX This should be called "preinit" or something, as it initializes
445 // critical parts of the scene graph in addition to the splash screen.
447 FGRenderer::splashinit( void ) {
448 osgViewer::Viewer* viewer = getViewer();
449 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
450 ref_ptr<Node> splashNode = fgCreateSplashNode();
451 if (_classicalRenderer) {
452 mRealRoot->addChild(splashNode.get());
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());
465 mFrameStamp = viewer->getFrameStamp();
466 // Scene doesn't seem to pass the frame stamp to the update
467 // visitor automatically.
468 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
469 viewer->setUpdateVisitor(mUpdateVisitor.get());
470 fgSetDouble("/sim/startup/splash-alpha", 1.0);
473 class ShadowMapSizeListener : public SGPropertyChangeListener {
475 virtual void valueChanged(SGPropertyNode* node) {
476 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
480 class ShadowEnabledListener : public SGPropertyChangeListener {
482 virtual void valueChanged(SGPropertyNode* node) {
483 globals->get_renderer()->enableShadows(node->getBoolValue());
487 class ShadowNumListener : public SGPropertyChangeListener {
489 virtual void valueChanged(SGPropertyNode* node) {
490 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
494 class ShadowRangeListener : public SGPropertyChangeListener {
496 virtual void valueChanged(SGPropertyNode* node) {
497 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
502 FGRenderer::init( void )
504 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt", false);
505 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
506 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
507 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
508 ShadowRangeListener* srl = new ShadowRangeListener;
509 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
510 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
511 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
512 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
513 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
514 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
515 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
516 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
517 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
518 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
519 updateCascadeNumber(_numCascades);
520 updateCascadeFar(0, _cascadeFar[0]);
521 updateCascadeFar(1, _cascadeFar[1]);
522 updateCascadeFar(2, _cascadeFar[2]);
523 updateCascadeFar(3, _cascadeFar[3]);
524 _useColorForDepth = fgGetBool( "/sim/rendering/use-color-for-depth", false );
525 _depthInColor->set( _useColorForDepth );
527 _renderer = fgGetString("/sim/rendering/renderer", "");
528 if (!_classicalRenderer && !_renderer.empty())
529 _pipeline = makeRenderingPipeline(_renderer, 0);
530 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
531 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
532 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
533 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
535 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
537 _xsize = fgGetNode("/sim/startup/xsize", true);
538 _ysize = fgGetNode("/sim/startup/ysize", true);
539 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
541 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
542 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
543 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
544 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
545 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
546 _textures = fgGetNode("/sim/rendering/textures", true);
548 _altitude_ft = fgGetNode("/position/altitude-ft", true);
550 _cloud_status = fgGetNode("/environment/clouds/status", true);
551 _visibility_m = fgGetNode("/environment/visibility-m", true);
553 bool use_point_sprites = _point_sprites->getBoolValue();
554 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
555 bool distance_attenuation = _distance_attenuation->getBoolValue();
557 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
558 distance_attenuation );
560 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
561 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
562 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
563 strcmp(tc, "none") == 0) {
564 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
565 } else if (strcmp(tc, "arb") == 0) {
566 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
567 } else if (strcmp(tc, "dxt1") == 0) {
568 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
569 } else if (strcmp(tc, "dxt3") == 0) {
570 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
571 } else if (strcmp(tc, "dxt5") == 0) {
572 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
574 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
578 // create sky, but can't build until setupView, since we depend
579 // on other subsystems to be inited, eg Ephemeris
582 SGPath texture_path(globals->get_fg_root());
583 texture_path.append("Textures");
584 texture_path.append("Sky");
585 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
586 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
587 _sky->add_cloud_layer(layer);
590 _sky->texture_path( texture_path.str() );
592 if (!_classicalRenderer) {
593 eventHandler->setChangeStatsCameraRenderOrder( true );
597 void installCullVisitor(Camera* camera)
599 osgViewer::Renderer* renderer
600 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
601 for (int i = 0; i < 2; ++i) {
602 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
603 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
604 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
606 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
607 identifier = sceneView->getCullVisitor()->getIdentifier();
608 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
609 sceneView->getCullVisitor()->setIdentifier(identifier.get());
611 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
612 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
613 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
615 identifier = sceneView->getCullVisitorRight()->getIdentifier();
616 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
617 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
622 flightgear::CameraInfo*
623 FGRenderer::buildRenderingPipeline(flightgear::CameraGroup* cgroup, unsigned flags, Camera* camera,
625 const Matrix& projection,
626 osg::GraphicsContext* gc,
627 bool useMasterSceneData)
629 flightgear::CameraInfo* info = 0;
630 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
631 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
636 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
637 _classicalRenderer = true;
638 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
642 flightgear::CameraInfo*
643 FGRenderer::buildClassicalPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
644 const osg::Matrix& view,
645 const osg::Matrix& projection,
646 bool useMasterSceneData)
648 CameraInfo* info = new CameraInfo(flags);
649 // The camera group will always update the camera
650 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
652 Camera* farCamera = 0;
653 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
654 farCamera = new Camera;
655 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
656 farCamera->setGraphicsContext(camera->getGraphicsContext());
657 farCamera->setCullingMode(camera->getCullingMode());
658 farCamera->setInheritanceMask(camera->getInheritanceMask());
659 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
660 // Each camera's viewport is written when the window is
661 // resized; if the the viewport isn't copied here, it gets updated
662 // twice and ends up with the wrong value.
663 farCamera->setViewport(simgear::clone(camera->getViewport()));
664 farCamera->setDrawBuffer(camera->getDrawBuffer());
665 farCamera->setReadBuffer(camera->getReadBuffer());
666 farCamera->setRenderTargetImplementation(
667 camera->getRenderTargetImplementation());
668 const Camera::BufferAttachmentMap& bufferMap
669 = camera->getBufferAttachmentMap();
670 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
672 Camera::COLOR_BUFFER,
673 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
675 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
676 installCullVisitor(farCamera);
677 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
678 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
679 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
680 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
681 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
683 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
684 installCullVisitor(camera);
685 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
686 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
687 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
688 cgroup->addCamera(info);
692 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
694 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i ) : kind( k ), info( i ) {}
695 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
696 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
697 osg::Camera* camera = static_cast<osg::Camera*>(n);
699 cv->clearBufferList();
700 cv->addBuffer("depth", info->getBuffer( "depth" ) );
701 cv->addBuffer("normal", info->getBuffer( "normal" ) );
702 cv->addBuffer("diffuse", info->getBuffer( "diffuse" ) );
703 cv->addBuffer("spec-emis", info->getBuffer( "spec-emis" ) );
704 cv->addBuffer("lighting", info->getBuffer( "lighting" ) );
705 cv->addBuffer("shadow", info->getBuffer( "shadow" ) );
706 // cv->addBuffer(simgear::Effect::AO_BUFFER, info->gBuffer->aoBuffer[2]);
708 if ( !info->getRenderStageInfo(kind).fullscreen )
709 info->setMatrices( camera );
711 cv->traverse( *camera );
713 if ( kind == flightgear::GEOMETRY_CAMERA ) {
714 // Save transparent bins to render later
715 osgUtil::RenderStage* renderStage = cv->getRenderStage();
716 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
717 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
718 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
719 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
725 } else if ( kind == flightgear::LIGHTING_CAMERA ) {
726 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
727 if (mainShadowCamera.valid()) {
728 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
729 for (int i = 0; i < 4; ++i ) {
730 if (!grp->getValue(i))
732 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
733 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
735 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
736 // compute the matrix which takes a vertex from view coords into tex coords
737 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
738 osg::Matrix::translate(1.0,1.0,1.0) *
739 osg::Matrix::scale(0.5f,0.5f,0.5f) );
741 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
743 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
746 // Render saved transparent render bins
747 osgUtil::RenderStage* renderStage = cv->getRenderStage();
748 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
749 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
750 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
752 info->savedTransparentBins.clear();
761 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
763 osg::Texture2D* tex = new osg::Texture2D;
764 tex->setResizeNonPowerOfTwoHint( false );
765 tex->setInternalFormat( internalFormat );
766 tex->setShadowComparison(shadowComparison);
767 if (shadowComparison) {
768 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
769 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
771 tex->setSourceFormat(sourceFormat);
772 tex->setSourceType(sourceType);
773 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
774 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
775 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
776 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
780 void buildDeferredBuffers( flightgear::CameraInfo* info, int shadowMapSize, bool useColorForDepth )
782 if (useColorForDepth) {
783 info->addBuffer("real-depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
784 info->addBuffer("depth", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
787 info->addBuffer("depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
789 info->addBuffer("normal", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
790 info->addBuffer("diffuse", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
791 info->addBuffer("spec-emis", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
792 info->addBuffer("lighting", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
793 info->addBuffer("shadow", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER, true), 0.0f );
794 info->getBuffer("shadow")->setTextureSize(shadowMapSize,shadowMapSize);
797 void attachBufferToCamera( flightgear::CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
799 camera->attach( c, info->getBuffer(bk) );
800 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
803 osg::Camera* FGRenderer::buildDefaultDeferredGeometryCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
805 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
806 if (_useColorForDepth) {
807 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "real-depth") );
808 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER3, "depth") );
810 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "depth") );
812 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER0, "normal") );
813 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER1, "diffuse") );
814 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER2, "spec-emis") );
815 return buildDeferredGeometryCamera(info, gc, attachments);
818 osg::Camera* FGRenderer::buildDeferredGeometryCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
820 osg::Camera* camera = new osg::Camera;
821 info->addCamera(flightgear::GEOMETRY_CAMERA, camera );
823 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
824 camera->setName( "GeometryC" );
825 camera->setGraphicsContext( gc );
826 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::GEOMETRY_CAMERA, info ) );
827 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
828 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
829 camera->setClearDepth( 1.0 );
830 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
831 camera->setViewport( new osg::Viewport );
832 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
833 attachBufferToCamera( info, camera, attachment->component, flightgear::GEOMETRY_CAMERA, attachment->buffer );
835 camera->setDrawBuffer(GL_FRONT);
836 camera->setReadBuffer(GL_FRONT);
838 osg::StateSet* ss = camera->getOrCreateStateSet();
839 ss->addUniform( _depthInColor );
841 camera->addChild( mDeferredRealRoot.get() );
846 static void setShadowCascadeStateSet( osg::Camera* cam ) {
847 osg::StateSet* ss = cam->getOrCreateStateSet();
848 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
849 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
850 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
851 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
852 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
853 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
854 osg::Program* program = new osg::Program;
855 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
856 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
857 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
858 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
859 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
860 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
861 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
862 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
863 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
866 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
867 osg::Camera* cascadeCam = new osg::Camera;
868 setShadowCascadeStateSet( cascadeCam );
870 std::ostringstream oss;
871 oss << "CascadeCamera" << (no + 1);
872 cascadeCam->setName( oss.str() );
873 cascadeCam->setClearMask(0);
874 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
875 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
876 cascadeCam->setAllowEventFocus(false);
877 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
878 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
879 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
880 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
884 osg::Camera* FGRenderer::buildDefaultDeferredShadowCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
886 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
887 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "shadow") );
888 return buildDeferredShadowCamera(info, gc, attachments);
891 osg::Camera* FGRenderer::buildDeferredShadowCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
893 osg::Camera* mainShadowCamera = new osg::Camera;
894 info->addCamera(flightgear::SHADOW_CAMERA, mainShadowCamera, 0.0f );
896 mainShadowCamera->setName( "ShadowC" );
897 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
898 mainShadowCamera->setClearDepth( 1.0 );
899 mainShadowCamera->setAllowEventFocus(false);
900 mainShadowCamera->setGraphicsContext(gc);
901 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
902 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
903 attachBufferToCamera( info, mainShadowCamera, attachment->component, flightgear::SHADOW_CAMERA, attachment->buffer );
905 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
906 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
907 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
908 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
909 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
910 mainShadowCamera->setDrawBuffer(GL_FRONT);
911 mainShadowCamera->setReadBuffer(GL_FRONT);
913 osg::Switch* shadowSwitch = new osg::Switch;
914 mainShadowCamera->addChild( shadowSwitch );
916 for (int i = 0; i < 4; ++i ) {
917 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
918 cascadeCam->addChild( mDeferredRealRoot.get() );
919 shadowSwitch->addChild( cascadeCam );
920 info->shadowTexGen[i] = new osg::TexGen;
922 if (fgGetBool("/sim/rendering/shadows/enabled", true))
923 shadowSwitch->setAllChildrenOn();
925 shadowSwitch->setAllChildrenOff();
927 return mainShadowCamera;
930 void FGRenderer::updateShadowCascade(const CameraInfo* info, osg::Camera* camera, osg::Group* grp, int idx, double left, double right, double bottom, double top, double zNear, double f1, double f2)
932 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
933 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
934 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
936 osg::BoundingSphere bs;
937 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
938 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
939 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
940 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
942 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
944 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
945 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
946 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
949 osg::Vec3 FGRenderer::getSunDirection() const
952 _sunDirection->get( val );
956 void FGRenderer::updateShadowCamera(const flightgear::CameraInfo* info, const osg::Vec3d& position)
958 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
959 if (mainShadowCamera.valid()) {
960 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
961 osg::Vec3d up = position,
962 dir = getSunDirection();
965 // cos(100 deg) == -0.17
966 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
967 shadowSwitch->setAllChildrenOff();
969 double left,right,bottom,top,zNear,zFar;
970 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
971 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
973 shadowSwitch->setAllChildrenOn();
974 if (_numCascades == 1) {
975 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
976 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
978 for (int no = 0; no < 4; ++no) {
979 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
980 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
983 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
984 if (_numCascades > 1) {
985 shadowSwitch->setValue(1, true);
986 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
988 shadowSwitch->setValue(1, false);
990 if (_numCascades > 2) {
991 shadowSwitch->setValue(2, true);
992 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
994 shadowSwitch->setValue(2, false);
996 if (_numCascades > 3) {
997 shadowSwitch->setValue(3, true);
998 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
1000 shadowSwitch->setValue(3, false);
1003 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
1005 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
1007 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
1008 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
1014 void FGRenderer::updateShadowMapSize(int mapSize)
1016 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
1017 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
1020 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1021 ii != CameraGroup::getDefault()->camerasEnd();
1024 CameraInfo* info = ii->get();
1025 Camera* camera = info->getCamera(SHADOW_CAMERA);
1026 if (camera == 0) continue;
1028 Texture2D* tex = info->getBuffer("shadow");
1029 if (tex == 0) continue;
1031 tex->setTextureSize( mapSize, mapSize );
1032 tex->dirtyTextureObject();
1034 Viewport* vp = camera->getViewport();
1035 vp->width() = mapSize;
1036 vp->height() = mapSize;
1038 osgViewer::Renderer* renderer
1039 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1040 for (int i = 0; i < 2; ++i) {
1041 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1042 sceneView->getRenderStage()->setFrameBufferObject(0);
1043 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1044 if (sceneView->getRenderStageLeft()) {
1045 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1046 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1048 if (sceneView->getRenderStageRight()) {
1049 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1050 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1054 int cascadeSize = mapSize / 2;
1055 Group* grp = camera->getChild(0)->asGroup();
1056 for (int i = 0; i < 4; ++i ) {
1057 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1058 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1061 _shadowMapSize = mapSize;
1065 void FGRenderer::enableShadows(bool enabled)
1067 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1068 ii != CameraGroup::getDefault()->camerasEnd();
1071 CameraInfo* info = ii->get();
1072 Camera* camera = info->getCamera(SHADOW_CAMERA);
1073 if (camera == 0) continue;
1075 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1077 shadowSwitch->setAllChildrenOn();
1079 shadowSwitch->setAllChildrenOff();
1083 void FGRenderer::updateCascadeFar(int index, float far_m)
1085 if (index < 0 || index > 3)
1087 _cascadeFar[index] = far_m;
1088 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1091 void FGRenderer::updateCascadeNumber(size_t num)
1093 if (num < 1 || num > 4)
1096 _shadowNumber->set( (int)_numCascades );
1099 osg::Camera* FGRenderer::buildDefaultDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
1101 std::vector<ref_ptr<FGRenderingPipeline::Attachment> > attachments;
1102 if (_useColorForDepth) {
1103 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "real-depth") );
1105 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::DEPTH_BUFFER, "depth") );
1107 attachments.push_back(new FGRenderingPipeline::Attachment(osg::Camera::COLOR_BUFFER0, "lighting") );
1108 return buildDeferredLightingCamera( info, gc, attachments );
1111 osg::Camera* FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
1113 osg::Camera* camera = new osg::Camera;
1114 info->addCamera(flightgear::LIGHTING_CAMERA, camera );
1116 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::LIGHTING_CAMERA, info ) );
1117 camera->setAllowEventFocus(false);
1118 camera->setGraphicsContext(gc);
1119 camera->setViewport(new Viewport);
1120 camera->setName("LightingC");
1121 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1122 camera->setRenderOrder(osg::Camera::POST_RENDER, 50);
1123 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1124 camera->setViewport( new osg::Viewport );
1125 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
1126 attachBufferToCamera( info, camera, attachment->component, flightgear::LIGHTING_CAMERA, attachment->buffer );
1128 camera->setDrawBuffer(GL_FRONT);
1129 camera->setReadBuffer(GL_FRONT);
1130 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1131 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1132 osg::StateSet* ss = camera->getOrCreateStateSet();
1133 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1134 ss->addUniform( _depthInColor );
1136 osg::Group* lightingGroup = new osg::Group;
1138 osg::Camera* quadCam1 = new osg::Camera;
1139 quadCam1->setName( "QuadCamera1" );
1140 quadCam1->setClearMask(0);
1141 quadCam1->setAllowEventFocus(false);
1142 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1143 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1144 quadCam1->setViewMatrix(osg::Matrix::identity());
1145 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1146 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1147 ss = quadCam1->getOrCreateStateSet();
1148 ss->addUniform( _ambientFactor );
1149 ss->addUniform( info->projInverse );
1150 ss->addUniform( info->viewInverse );
1151 ss->addUniform( info->view );
1152 ss->addUniform( _sunDiffuse );
1153 ss->addUniform( _sunSpecular );
1154 ss->addUniform( _sunDirection );
1155 ss->addUniform( _planes );
1156 ss->addUniform( _shadowNumber );
1157 ss->addUniform( _shadowDistances );
1159 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1160 g->setUseDisplayList(false);
1161 simgear::EffectGeode* eg = new simgear::EffectGeode;
1162 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1164 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1167 eg->setEffect( effect );
1168 g->setName( "AmbientQuad" );
1169 eg->setName("AmbientQuad");
1170 eg->setCullingActive(false);
1172 quadCam1->addChild( eg );
1174 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1175 g->setUseDisplayList(false);
1176 g->setName( "SunlightQuad" );
1177 eg = new simgear::EffectGeode;
1178 effect = simgear::makeEffect("Effects/sunlight", true);
1180 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1183 eg->setEffect( effect );
1184 eg->setName("SunlightQuad");
1185 eg->setCullingActive(false);
1187 quadCam1->addChild( eg );
1189 osg::Camera* lightCam = new osg::Camera;
1190 ss = lightCam->getOrCreateStateSet();
1191 ss->addUniform( _planes );
1192 ss->addUniform( info->bufferSize );
1193 lightCam->setName( "LightCamera" );
1194 lightCam->setClearMask(0);
1195 lightCam->setAllowEventFocus(false);
1196 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1197 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1198 lightCam->setViewMatrix(osg::Matrix::identity());
1199 lightCam->setProjectionMatrix(osg::Matrix::identity());
1200 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1201 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1202 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1203 lightCam->addChild( mDeferredRealRoot.get() );
1206 osg::Camera* quadCam2 = new osg::Camera;
1207 quadCam2->setName( "QuadCamera1" );
1208 quadCam2->setClearMask(0);
1209 quadCam2->setAllowEventFocus(false);
1210 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1211 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1212 quadCam2->setViewMatrix(osg::Matrix::identity());
1213 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1214 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1215 ss = quadCam2->getOrCreateStateSet();
1216 ss->addUniform( _ambientFactor );
1217 ss->addUniform( info->projInverse );
1218 ss->addUniform( info->viewInverse );
1219 ss->addUniform( info->view );
1220 ss->addUniform( _sunDiffuse );
1221 ss->addUniform( _sunSpecular );
1222 ss->addUniform( _sunDirection );
1223 ss->addUniform( _fogColor );
1224 ss->addUniform( _fogDensity );
1225 ss->addUniform( _planes );
1227 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1228 g->setUseDisplayList(false);
1229 g->setName( "FogQuad" );
1230 eg = new simgear::EffectGeode;
1231 effect = simgear::makeEffect("Effects/fog", true);
1233 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1236 eg->setEffect( effect );
1237 eg->setName("FogQuad");
1238 eg->setCullingActive(false);
1240 quadCam2->addChild( eg );
1242 lightingGroup->addChild( _sky->getPreRoot() );
1243 lightingGroup->addChild( _sky->getCloudRoot() );
1244 lightingGroup->addChild( quadCam1 );
1245 lightingGroup->addChild( lightCam );
1246 lightingGroup->addChild( quadCam2 );
1248 camera->addChild( lightingGroup );
1253 namespace flightgear {
1254 flightgear::CameraInfo* buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1255 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc);
1258 flightgear::CameraInfo*
1259 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1260 const osg::Matrix& view,
1261 const osg::Matrix& projection,
1262 osg::GraphicsContext* gc)
1264 if (_renderer.empty() || !_pipeline.valid())
1265 return buildDefaultDeferredPipeline(cgroup, flags, camera, view, projection, gc);
1266 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1269 flightgear::CameraInfo*
1270 FGRenderer::buildDefaultDeferredPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1271 const osg::Matrix& view,
1272 const osg::Matrix& projection,
1273 osg::GraphicsContext* gc)
1275 CameraInfo* info = new CameraInfo(flags);
1276 buildDeferredBuffers(info, _shadowMapSize, _useColorForDepth);
1278 osg::Camera* geometryCamera = buildDefaultDeferredGeometryCamera( info, gc );
1279 cgroup->getViewer()->addSlave(geometryCamera, false);
1280 installCullVisitor(geometryCamera);
1281 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1282 info->getRenderStageInfo(GEOMETRY_CAMERA).slaveIndex = slaveIndex;
1284 Camera* shadowCamera = buildDefaultDeferredShadowCamera( info, gc );
1285 cgroup->getViewer()->addSlave(shadowCamera, false);
1286 installCullVisitor(shadowCamera);
1287 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1288 info->getRenderStageInfo(SHADOW_CAMERA).slaveIndex = slaveIndex;
1290 osg::Camera* lightingCamera = buildDefaultDeferredLightingCamera( info, gc );
1291 cgroup->getViewer()->addSlave(lightingCamera, false);
1292 installCullVisitor(lightingCamera);
1293 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1294 info->getRenderStageInfo(LIGHTING_CAMERA).slaveIndex = slaveIndex;
1296 camera->setName( "DisplayC" );
1297 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::DISPLAY_CAMERA, info ) );
1298 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1299 camera->setAllowEventFocus(false);
1300 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1301 g->setUseDisplayList(false); //DEBUG
1302 simgear::EffectGeode* eg = new simgear::EffectGeode;
1303 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1305 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1308 eg->setEffect(effect);
1309 eg->setCullingActive(false);
1311 camera->setViewMatrix(osg::Matrix::identity());
1312 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1313 camera->addChild(eg);
1315 osg::StateSet* ss = camera->getOrCreateStateSet();
1316 ss->addUniform( _depthInColor );
1318 cgroup->getViewer()->addSlave(camera, false);
1319 installCullVisitor(camera);
1320 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1321 info->addCamera( DISPLAY_CAMERA, camera, slaveIndex, true );
1322 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1323 cgroup->addCamera(info);
1329 FGRenderer::setupView( void )
1331 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1332 osg::initNotifyLevel();
1334 // The number of polygon-offset "units" to place between layers. In
1335 // principle, one is supposed to be enough. In practice, I find that
1336 // my hardware/driver requires many more.
1337 osg::PolygonOffset::setUnitsMultiplier(1);
1338 osg::PolygonOffset::setFactorMultiplier(1);
1340 // Go full screen if requested ...
1341 if ( fgGetBool("/sim/startup/fullscreen") )
1345 // The sun and moon diameters are scaled down numbers of the
1346 // actual diameters. This was needed to fit both the sun and the
1347 // moon within the distance to the far clip plane.
1348 // Moon diameter: 3,476 kilometers
1349 // Sun diameter: 1,390,000 kilometers
1350 _sky->build( 80000.0, 80000.0,
1352 *globals->get_ephem(),
1353 fgGetNode("/environment", true));
1356 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1358 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1360 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1362 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1363 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1365 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1366 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1367 stateSet->setAttribute(new osg::BlendFunc);
1368 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1370 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1372 // this will be set below
1373 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1375 osg::Material* material = new osg::Material;
1376 stateSet->setAttribute(material);
1378 stateSet->setTextureAttribute(0, new osg::TexEnv);
1379 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1381 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1382 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1383 stateSet->setAttribute(hint);
1384 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1385 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1386 stateSet->setAttribute(hint);
1387 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1388 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1389 stateSet->setAttribute(hint);
1390 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1391 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1392 stateSet->setAttribute(hint);
1393 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1394 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1395 stateSet->setAttribute(hint);
1397 osg::Group* sceneGroup = new osg::Group;
1398 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1399 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1401 //sceneGroup->addChild(thesky->getCloudRoot());
1403 stateSet = sceneGroup->getOrCreateStateSet();
1404 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1406 // need to update the light on every frame
1407 // OSG LightSource objects are rather confusing. OSG only supports
1408 // the 10 lights specified by OpenGL itself; if more than one
1409 // LightSource in the scene graph have the same light number, it's
1410 // indeterminate which values will be used to render geometry that
1411 // has that light number enabled. Also, adding children to a
1412 // LightSource is just a shortcut for setting up a state set that
1413 // has the corresponding OpenGL light enabled: a LightSource will
1414 // affect geometry anywhere in the scene graph that has its light
1415 // number enabled in a state set.
1416 LightSource* lightSource = new LightSource;
1417 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1418 // relative because of CameraView being just a clever transform node
1419 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1420 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1421 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1422 mRealRoot->addChild(lightSource);
1423 // we need a white diffuse light for the phase of the moon
1424 osg::LightSource* sunLight = new osg::LightSource;
1425 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1426 sunLight->getLight()->setLightNum(1);
1427 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1428 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1429 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1431 // Hang a StateSet above the sky subgraph in order to turn off
1433 Group* skyGroup = new Group;
1434 StateSet* skySS = skyGroup->getOrCreateStateSet();
1435 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1436 skyGroup->addChild(_sky->getPreRoot());
1437 sunLight->addChild(skyGroup);
1438 mRoot->addChild(sceneGroup);
1439 if ( _classicalRenderer )
1440 mRoot->addChild(sunLight);
1442 // Clouds are added to the scene graph later
1443 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1444 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1445 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1446 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1448 // enable disable specular highlights.
1449 // is the place where we might plug in an other fragment shader ...
1450 osg::LightModel* lightModel = new osg::LightModel;
1451 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1452 stateSet->setAttribute(lightModel);
1454 // switch to enable wireframe
1455 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1456 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1457 stateSet->setAttributeAndModes(polygonMode);
1459 // scene fog handling
1460 osg::Fog* fog = new osg::Fog;
1461 fog->setUpdateCallback(new FGFogUpdateCallback);
1462 stateSet->setAttributeAndModes(fog);
1463 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1466 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1469 osg::Geode* geode = new osg::Geode;
1470 geode->addDrawable(new SGPuDrawable);
1471 geode->addDrawable(new SGHUDDrawable);
1472 guiCamera->addChild(geode);
1474 panelSwitch = new osg::Switch;
1475 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1476 stateSet->setRenderBinDetails(1000, "RenderBin");
1478 // speed optimization?
1479 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1480 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1481 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1482 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1483 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1486 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1489 guiCamera->addChild(panelSwitch.get());
1492 osg::Switch* sw = new osg::Switch;
1493 sw->setUpdateCallback(new FGScenerySwitchCallback);
1494 sw->addChild(mRoot.get());
1495 mRealRoot->addChild(sw);
1496 // The clouds are attached directly to the scene graph root
1497 // because, in theory, they don't want the same default state set
1498 // as the rest of the scene. This may not be true in practice.
1499 if ( _classicalRenderer ) {
1500 mRealRoot->addChild(_sky->getCloudRoot());
1501 mRealRoot->addChild(FGCreateRedoutNode());
1503 // Attach empty program to the scene root so that shader programs
1504 // don't leak into state sets (effects) that shouldn't have one.
1505 stateSet = mRealRoot->getOrCreateStateSet();
1506 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1508 mDeferredRealRoot->addChild( mRealRoot.get() );
1511 void FGRenderer::panelChanged()
1517 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1518 if (panelSwitch->getNumChildren()) {
1519 panelSwitch->setChild(0, n);
1521 panelSwitch->addChild(n);
1525 // Update all Visuals (redraws anything graphics related)
1527 FGRenderer::update( ) {
1528 if (!(_scenery_loaded->getBoolValue() ||
1529 _scenery_override->getBoolValue()))
1531 _splash_alpha->setDoubleValue(1.0);
1534 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1536 if (_splash_alpha->getDoubleValue()>0.0)
1538 // Fade out the splash screen
1539 const double fade_time = 0.5;
1540 const double fade_steps_per_sec = 10;
1541 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1542 (SGTimeStamp::now() - _splash_time).toSecs());
1543 _splash_time = SGTimeStamp::now();
1544 double sAlpha = _splash_alpha->getDoubleValue();
1545 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1546 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1547 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1550 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1551 if (!_classicalRenderer ) {
1552 _ambientFactor->set( toOsg(l->scene_ambient()) );
1553 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1554 _sunSpecular->set( toOsg(l->scene_specular()) );
1555 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1558 // update fog params
1559 double actual_visibility;
1560 if (_cloud_status->getBoolValue()) {
1561 actual_visibility = _sky->get_visibility();
1563 actual_visibility = _visibility_m->getDoubleValue();
1566 // idle_state is now 1000 meaning we've finished all our
1567 // initializations and are running the main loop, so this will
1568 // now work without seg faulting the system.
1570 FGViewer *current__view = globals->get_current_view();
1571 // Force update of center dependent values ...
1572 current__view->set_dirty();
1574 osg::Camera *camera = viewer->getCamera();
1576 bool skyblend = _skyblend->getBoolValue();
1579 if ( _textures->getBoolValue() ) {
1580 SGVec4f clearColor(l->adj_fog_color());
1581 camera->setClearColor(toOsg(clearColor));
1584 SGVec4f clearColor(l->sky_color());
1585 camera->setClearColor(toOsg(clearColor));
1588 // update fog params if visibility has changed
1589 double visibility_meters = _visibility_m->getDoubleValue();
1590 _sky->set_visibility(visibility_meters);
1592 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1593 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1595 // update the sky dome
1598 // The sun and moon distances are scaled down versions
1599 // of the actual distance to get both the moon and the sun
1600 // within the range of the far clip plane.
1601 // Moon distance: 384,467 kilometers
1602 // Sun distance: 150,000,000 kilometers
1604 double sun_horiz_eff, moon_horiz_eff;
1605 if (_horizon_effect->getBoolValue()) {
1607 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1611 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1615 sun_horiz_eff = moon_horiz_eff = 1.0;
1619 sstate.pos = current__view->getViewPosition();
1620 sstate.pos_geod = current__view->getPosition();
1621 sstate.ori = current__view->getViewOrientation();
1622 sstate.spin = l->get_sun_rotation();
1623 sstate.gst = globals->get_time_params()->getGst();
1624 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1625 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1626 sstate.sun_angle = l->get_sun_angle();
1629 scolor.sky_color = SGVec3f(l->sky_color().data());
1630 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1631 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1632 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1633 scolor.sun_angle = l->get_sun_angle();
1634 scolor.moon_angle = l->get_moon_angle();
1636 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1637 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1638 _sky->repaint( scolor, *globals->get_ephem() );
1641 // shadows->setupShadows(
1642 // current__view->getLongitude_deg(),
1643 // current__view->getLatitude_deg(),
1644 // globals->get_time_params()->getGst(),
1645 // globals->get_ephem()->getSunRightAscension(),
1646 // globals->get_ephem()->getSunDeclination(),
1647 // l->get_sun_angle());
1651 // sgEnviro.setLight(l->adj_fog_color());
1652 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1653 // current__view->get_world_up(),
1654 // current__view->getLongitude_deg(),
1655 // current__view->getLatitude_deg(),
1656 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1660 // sgEnviro.drawLightning();
1662 // double current_view_origin_airspeed_horiz_kt =
1663 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1664 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1665 // * SGD_DEGREES_TO_RADIANS);
1668 // if( is_internal )
1669 // shadows->endOfFrame();
1671 // need to call the update visitor once
1672 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1673 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1674 current__view->getViewOrientation());
1675 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1676 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1677 l->scene_diffuse(), l->scene_specular(),
1679 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1680 mUpdateVisitor->setVisibility(actual_visibility);
1681 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1682 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1683 cullMask |= simgear::GroundLightManager::instance()
1684 ->getLightNodeMask(mUpdateVisitor.get());
1685 if (_panel_hotspots->getBoolValue())
1686 cullMask |= simgear::PICK_BIT;
1687 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1688 if ( !_classicalRenderer ) {
1689 _fogColor->set( toOsg( l->adj_fog_color() ) );
1690 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1695 FGRenderer::resize( int width, int height )
1697 int curWidth = _xsize->getIntValue(),
1698 curHeight = _ysize->getIntValue();
1699 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1700 if ((curHeight != height) || (curWidth != width)) {
1701 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1702 _xsize->setIntValue(width);
1703 _ysize->setIntValue(height);
1708 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1709 const osgGA::GUIEventAdapter* ea)
1711 // wipe out the return ...
1713 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1714 Intersections intersections;
1716 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1718 for (Intersections::iterator hit = intersections.begin(),
1719 e = intersections.end();
1722 const osg::NodePath& np = hit->nodePath;
1723 osg::NodePath::const_reverse_iterator npi;
1724 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1725 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1728 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1729 SGPickCallback* pickCallback = ud->getPickCallback(i);
1732 SGSceneryPick sceneryPick;
1733 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1734 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1735 sceneryPick.callback = pickCallback;
1736 pickList.push_back(sceneryPick);
1740 return !pickList.empty();
1744 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1750 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1752 eventHandler = eventHandler_;
1756 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1758 mRealRoot->addChild(camera);
1762 FGRenderer::removeCamera(osg::Camera* camera)
1764 mRealRoot->removeChild(camera);
1768 FGRenderer::setPlanes( double zNear, double zFar )
1770 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1774 fgDumpSceneGraphToFile(const char* filename)
1776 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1780 fgDumpTerrainBranchToFile(const char* filename)
1782 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1788 fgDumpNodeToFile(osg::Node* node, const char* filename)
1790 return osgDB::writeNodeFile(*node, filename);
1793 namespace flightgear
1795 using namespace osg;
1797 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1800 VisibleSceneInfoVistor()
1801 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1803 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1804 | CullSettings::VIEW_FRUSTUM_CULLING);
1805 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1808 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1812 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1814 typedef std::map<const std::string,int> InfoMap;
1816 void getNodeInfo(Node* node)
1818 const char* typeName = typeid(*node).name();
1819 classInfo[typeName]++;
1820 const std::string& nodeName = node->getName();
1821 if (!nodeName.empty())
1822 nodeInfo[nodeName]++;
1827 using namespace std;
1828 typedef vector<InfoMap::iterator> FreqVector;
1829 cout << "class info:\n";
1831 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1834 classes.push_back(itr);
1835 sort(classes.begin(), classes.end(), freqComp);
1836 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1839 cout << (*itr)->first << " " << (*itr)->second << "\n";
1841 cout << "\nnode info:\n";
1843 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1846 nodes.push_back(itr);
1848 sort (nodes.begin(), nodes.end(), freqComp);
1849 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1852 cout << (*itr)->first << " " << (*itr)->second << "\n";
1857 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1859 ref_ptr<RefMatrix> projection
1860 = createOrReuseMatrix(camera->getProjectionMatrix());
1861 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1863 viewport = camera->getViewport();
1865 pushViewport(viewport);
1866 pushProjectionMatrix(projection.get());
1867 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1868 root->accept(*this);
1869 popModelViewMatrix();
1870 popProjectionMatrix();
1876 void apply(Node& node)
1885 void apply(Group& node)
1895 void apply(Transform& node)
1900 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1901 node.computeLocalToWorldMatrix(*matrix,this);
1902 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1905 popModelViewMatrix();
1909 void apply(Camera& camera)
1911 // Save current cull settings
1912 CullSettings saved_cull_settings(*this);
1914 // set cull settings from this Camera
1915 setCullSettings(camera);
1916 // inherit the settings from above
1917 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1919 // set the cull mask.
1920 unsigned int savedTraversalMask = getTraversalMask();
1921 bool mustSetCullMask = (camera.getInheritanceMask()
1922 & osg::CullSettings::CULL_MASK) == 0;
1923 if (mustSetCullMask)
1924 setTraversalMask(camera.getCullMask());
1926 osg::RefMatrix* projection = 0;
1927 osg::RefMatrix* modelview = 0;
1929 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1930 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1931 projection = createOrReuseMatrix(*getProjectionMatrix()
1932 *camera.getProjectionMatrix());
1933 modelview = createOrReuseMatrix(*getModelViewMatrix()
1934 * camera.getViewMatrix());
1936 else { // pre multiply
1937 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1938 * (*getProjectionMatrix()));
1939 modelview = createOrReuseMatrix(camera.getViewMatrix()
1940 * (*getModelViewMatrix()));
1943 // an absolute reference frame
1944 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1945 modelview = createOrReuseMatrix(camera.getViewMatrix());
1947 if (camera.getViewport())
1948 pushViewport(camera.getViewport());
1950 pushProjectionMatrix(projection);
1951 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1955 // restore the previous model view matrix.
1956 popModelViewMatrix();
1958 // restore the previous model view matrix.
1959 popProjectionMatrix();
1961 if (camera.getViewport()) popViewport();
1963 // restore the previous traversal mask settings
1964 if (mustSetCullMask)
1965 setTraversalMask(savedTraversalMask);
1967 // restore the previous cull settings
1968 setCullSettings(saved_cull_settings);
1973 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1975 return lhs->second > rhs->second;
1981 bool printVisibleSceneInfo(FGRenderer* renderer)
1983 osgViewer::Viewer* viewer = renderer->getViewer();
1984 VisibleSceneInfoVistor vsv;
1986 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1987 const View::Slave& slave = viewer->getSlave(0);
1988 vp = slave._camera->getViewport();
1990 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1994 void buildBuffers(FGRenderingPipeline* rpipe, flightgear::CameraInfo* info)
1996 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1997 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1998 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1999 buffer->sourceFormat,
2002 buffer->shadowComparison) );
2006 void buildStage(FGRenderingPipeline* rpipe, flightgear::CameraInfo* info,
2007 FGRenderingPipeline::Stage* stage,
2008 flightgear::CameraGroup* cgroup,
2009 osg::Camera* camera,
2010 const osg::Matrix& view,
2011 const osg::Matrix& projection,
2012 osg::GraphicsContext* gc)
2014 osg::ref_ptr<osg::Camera> stageCamera;
2015 if (stage->type == "main-camera")
2016 stageCamera = camera;
2018 stageCamera = new osg::Camera;
2020 stageCamera->setName(stage->name);
2021 stageCamera->setGraphicsContext(gc);
2022 //stageCamera->setCullCallback(new FGStageCameraCullCallback(stage, info));
2023 if (stage->type != "main-camera")
2024 stageCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
2027 void buildMainCamera(FGRenderingPipeline* rpipe, flightgear::CameraInfo* info,
2028 FGRenderingPipeline::Stage* stage,
2029 flightgear::CameraGroup* cgroup,
2030 osg::Camera* camera,
2031 const osg::Matrix& view,
2032 const osg::Matrix& projection,
2033 osg::GraphicsContext* gc)
2037 flightgear::CameraInfo* buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
2038 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
2040 flightgear::CameraInfo* info = new flightgear::CameraInfo(flags);
2041 buildBuffers(rpipe, info);
2043 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
2044 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
2045 buildStage(rpipe, info, stage, cgroup, camera, view, projection, gc);
2052 // end of renderer.cxx