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 <osg/ref_ptr>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
42 #include <osg/CullFace>
43 #include <osg/CullStack>
49 #include <osg/LightModel>
50 #include <osg/LightSource>
51 #include <osg/Material>
53 #include <osg/NodeCallback>
55 #include <osg/PolygonMode>
56 #include <osg/PolygonOffset>
57 #include <osg/Program>
58 #include <osg/Version>
61 #include <osgUtil/LineSegmentIntersector>
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65 #include <osgViewer/Renderer>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/material/EffectCullVisitor.hxx>
69 #include <simgear/scene/material/Effect.hxx>
70 #include <simgear/scene/material/EffectGeode.hxx>
71 #include <simgear/scene/model/animation.hxx>
72 #include <simgear/scene/model/placement.hxx>
73 #include <simgear/scene/sky/sky.hxx>
74 #include <simgear/scene/util/SGUpdateVisitor.hxx>
75 #include <simgear/scene/util/RenderConstants.hxx>
76 #include <simgear/scene/util/SGSceneUserData.hxx>
77 #include <simgear/scene/tgdb/GroundLightManager.hxx>
78 #include <simgear/scene/tgdb/pt_lights.hxx>
79 #include <simgear/structure/OSGUtils.hxx>
80 #include <simgear/props/props.hxx>
81 #include <simgear/timing/sg_time.hxx>
82 #include <simgear/ephemeris/ephemeris.hxx>
83 #include <simgear/math/sg_random.h>
85 #include <simgear/screen/jpgfactory.hxx>
88 #include <Time/light.hxx>
89 #include <Time/light.hxx>
90 #include <Cockpit/panel.hxx>
92 #include <Model/panelnode.hxx>
93 #include <Model/modelmgr.hxx>
94 #include <Model/acmodel.hxx>
95 #include <Scenery/scenery.hxx>
96 #include <Scenery/redout.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Instrumentation/HUD/HUD.hxx>
99 #include <Environment/precipitation_mgr.hxx>
100 #include <Environment/environment_mgr.hxx>
102 //#include <Main/main.hxx>
103 #include "viewer.hxx"
104 #include "viewmgr.hxx"
105 #include "splash.hxx"
106 #include "renderer.hxx"
107 #include "CameraGroup.hxx"
108 #include "FGEventHandler.hxx"
111 using namespace simgear;
112 using namespace flightgear;
114 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
116 FGHintUpdateCallback(const char* configNode) :
117 mConfigNode(fgGetNode(configNode, true))
119 virtual void operator()(osg::StateAttribute* stateAttribute,
122 assert(dynamic_cast<osg::Hint*>(stateAttribute));
123 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
125 const char* value = mConfigNode->getStringValue();
127 hint->setMode(GL_DONT_CARE);
128 else if (0 == strcmp(value, "nicest"))
129 hint->setMode(GL_NICEST);
130 else if (0 == strcmp(value, "fastest"))
131 hint->setMode(GL_FASTEST);
133 hint->setMode(GL_DONT_CARE);
136 SGPropertyNode_ptr mConfigNode;
140 class SGPuDrawable : public osg::Drawable {
144 // Dynamic stuff, do not store geometry
145 setUseDisplayList(false);
146 setDataVariance(Object::DYNAMIC);
148 osg::StateSet* stateSet = getOrCreateStateSet();
149 stateSet->setRenderBinDetails(1001, "RenderBin");
150 // speed optimization?
151 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
152 // We can do translucent menus, so why not. :-)
153 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
154 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
155 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
157 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
159 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
160 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
162 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
163 { drawImplementation(*renderInfo.getState()); }
164 void drawImplementation(osg::State& state) const
166 state.setActiveTextureUnit(0);
167 state.setClientActiveTextureUnit(0);
169 state.disableAllVertexArrays();
171 glPushAttrib(GL_ALL_ATTRIB_BITS);
172 glPushClientAttrib(~0u);
180 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
181 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
186 class SGHUDDrawable : public osg::Drawable {
190 // Dynamic stuff, do not store geometry
191 setUseDisplayList(false);
192 setDataVariance(Object::DYNAMIC);
194 osg::StateSet* stateSet = getOrCreateStateSet();
195 stateSet->setRenderBinDetails(1000, "RenderBin");
197 // speed optimization?
198 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
199 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
200 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
201 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
202 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
204 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
206 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
207 { drawImplementation(*renderInfo.getState()); }
208 void drawImplementation(osg::State& state) const
210 state.setActiveTextureUnit(0);
211 state.setClientActiveTextureUnit(0);
212 state.disableAllVertexArrays();
214 glPushAttrib(GL_ALL_ATTRIB_BITS);
215 glPushClientAttrib(~0u);
217 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
224 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
225 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
230 class FGLightSourceUpdateCallback : public osg::NodeCallback {
234 * @param isSun true if the light is the actual sun i.e., for
235 * illuminating the moon.
237 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
238 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
240 : NodeCallback(nc, op), _isSun(nc._isSun)
242 META_Object(flightgear,FGLightSourceUpdateCallback);
244 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
246 assert(dynamic_cast<osg::LightSource*>(node));
247 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
248 osg::Light* light = lightSource->getLight();
250 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
252 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
253 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
254 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
256 light->setAmbient(toOsg(l->scene_ambient()));
257 light->setDiffuse(toOsg(l->scene_diffuse()));
258 light->setSpecular(toOsg(l->scene_specular()));
260 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
261 light->setPosition(position);
269 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
271 FGWireFrameModeUpdateCallback() :
272 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
274 virtual void operator()(osg::StateAttribute* stateAttribute,
277 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
278 osg::PolygonMode* polygonMode;
279 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
281 if (mWireframe->getBoolValue())
282 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
283 osg::PolygonMode::LINE);
285 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
286 osg::PolygonMode::FILL);
289 SGPropertyNode_ptr mWireframe;
292 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
294 FGLightModelUpdateCallback() :
295 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
297 virtual void operator()(osg::StateAttribute* stateAttribute,
300 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
301 osg::LightModel* lightModel;
302 lightModel = static_cast<osg::LightModel*>(stateAttribute);
305 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
306 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
308 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
310 lightModel->setTwoSided(true);
311 lightModel->setLocalViewer(false);
313 if (mHighlights->getBoolValue()) {
314 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
316 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
320 SGPropertyNode_ptr mHighlights;
323 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
325 FGFogEnableUpdateCallback() :
326 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
328 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
330 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
331 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
333 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
337 SGPropertyNode_ptr mFogEnabled;
340 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
342 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
344 assert(dynamic_cast<SGUpdateVisitor*>(nv));
345 assert(dynamic_cast<osg::Fog*>(sa));
346 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
347 osg::Fog* fog = static_cast<osg::Fog*>(sa);
348 fog->setMode(osg::Fog::EXP2);
349 fog->setColor(toOsg(updateVisitor->getFogColor()));
350 fog->setDensity(updateVisitor->getFogExp2Density());
354 // update callback for the switch node guarding that splash
355 class FGScenerySwitchCallback : public osg::NodeCallback {
357 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
359 assert(dynamic_cast<osg::Switch*>(node));
360 osg::Switch* sw = static_cast<osg::Switch*>(node);
362 bool enabled = scenery_enabled;
363 sw->setValue(0, enabled);
369 static bool scenery_enabled;
372 bool FGScenerySwitchCallback::scenery_enabled = false;
374 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
375 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
377 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
378 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
380 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
382 static osg::ref_ptr<osg::Switch> panelSwitch;
385 // update callback for the switch node controlling the 2D panel
386 class FGPanelSwitchCallback : public osg::NodeCallback {
388 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
390 assert(dynamic_cast<osg::Switch*>(node));
391 osg::Switch* sw = static_cast<osg::Switch*>(node);
393 bool enabled = fgPanelVisible();
394 sw->setValue(0, enabled);
401 #ifdef FG_JPEG_SERVER
402 static void updateRenderer()
404 globals->get_renderer()->update();
408 FGRenderer::FGRenderer() :
410 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
411 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
412 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
413 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
414 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
415 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
416 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
417 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
418 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
419 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
421 #ifdef FG_JPEG_SERVER
422 jpgRenderFrame = updateRenderer;
424 eventHandler = new FGEventHandler;
427 _cascadeFar[0] = 5.f;
428 _cascadeFar[1] = 50.f;
429 _cascadeFar[2] = 500.f;
430 _cascadeFar[3] = 5000.f;
433 FGRenderer::~FGRenderer()
435 #ifdef FG_JPEG_SERVER
436 jpgRenderFrame = NULL;
441 // Initialize various GL/view parameters
442 // XXX This should be called "preinit" or something, as it initializes
443 // critical parts of the scene graph in addition to the splash screen.
445 FGRenderer::splashinit( void ) {
446 osgViewer::Viewer* viewer = getViewer();
447 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
448 ref_ptr<Node> splashNode = fgCreateSplashNode();
449 if (_classicalRenderer) {
450 mRealRoot->addChild(splashNode.get());
452 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
453 ii != CameraGroup::getDefault()->camerasEnd();
456 CameraInfo* info = ii->get();
457 Camera* camera = info->getCamera(DISPLAY_CAMERA);
458 if (camera == 0) continue;
460 camera->addChild(splashNode.get());
463 mFrameStamp = viewer->getFrameStamp();
464 // Scene doesn't seem to pass the frame stamp to the update
465 // visitor automatically.
466 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
467 viewer->setUpdateVisitor(mUpdateVisitor.get());
468 fgSetDouble("/sim/startup/splash-alpha", 1.0);
471 class ShadowMapSizeListener : public SGPropertyChangeListener {
473 virtual void valueChanged(SGPropertyNode* node) {
474 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
478 class ShadowEnabledListener : public SGPropertyChangeListener {
480 virtual void valueChanged(SGPropertyNode* node) {
481 globals->get_renderer()->enableShadows(node->getBoolValue());
485 class ShadowNumListener : public SGPropertyChangeListener {
487 virtual void valueChanged(SGPropertyNode* node) {
488 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
492 class ShadowRangeListener : public SGPropertyChangeListener {
494 virtual void valueChanged(SGPropertyNode* node) {
495 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
500 FGRenderer::init( void )
502 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt", false);
503 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
504 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
505 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
506 ShadowRangeListener* srl = new ShadowRangeListener;
507 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
508 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
509 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
510 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
511 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
512 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
513 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
514 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
515 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
516 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
517 updateCascadeNumber(_numCascades);
518 updateCascadeFar(0, _cascadeFar[0]);
519 updateCascadeFar(1, _cascadeFar[1]);
520 updateCascadeFar(2, _cascadeFar[2]);
521 updateCascadeFar(3, _cascadeFar[3]);
522 _useColorForDepth = fgGetBool( "/sim/rendering/use-color-for-depth", false );
523 _depthInColor->set( _useColorForDepth );
525 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
526 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
527 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
528 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
530 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
532 _xsize = fgGetNode("/sim/startup/xsize", true);
533 _ysize = fgGetNode("/sim/startup/ysize", true);
534 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
536 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
537 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
538 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
539 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
540 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
541 _textures = fgGetNode("/sim/rendering/textures", true);
543 _altitude_ft = fgGetNode("/position/altitude-ft", true);
545 _cloud_status = fgGetNode("/environment/clouds/status", true);
546 _visibility_m = fgGetNode("/environment/visibility-m", true);
548 bool use_point_sprites = _point_sprites->getBoolValue();
549 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
550 bool distance_attenuation = _distance_attenuation->getBoolValue();
552 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
553 distance_attenuation );
555 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
556 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
557 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
558 strcmp(tc, "none") == 0) {
559 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
560 } else if (strcmp(tc, "arb") == 0) {
561 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
562 } else if (strcmp(tc, "dxt1") == 0) {
563 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
564 } else if (strcmp(tc, "dxt3") == 0) {
565 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
566 } else if (strcmp(tc, "dxt5") == 0) {
567 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
569 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
573 // create sky, but can't build until setupView, since we depend
574 // on other subsystems to be inited, eg Ephemeris
577 SGPath texture_path(globals->get_fg_root());
578 texture_path.append("Textures");
579 texture_path.append("Sky");
580 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
581 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
582 _sky->add_cloud_layer(layer);
585 _sky->texture_path( texture_path.str() );
587 if (!_classicalRenderer) {
588 eventHandler->setChangeStatsCameraRenderOrder( true );
592 void installCullVisitor(Camera* camera)
594 osgViewer::Renderer* renderer
595 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
596 for (int i = 0; i < 2; ++i) {
597 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
598 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
599 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
601 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
602 identifier = sceneView->getCullVisitor()->getIdentifier();
603 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
604 sceneView->getCullVisitor()->setIdentifier(identifier.get());
606 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
607 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
608 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
610 identifier = sceneView->getCullVisitorRight()->getIdentifier();
611 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
612 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
617 flightgear::CameraInfo*
618 FGRenderer::buildRenderingPipeline(flightgear::CameraGroup* cgroup, unsigned flags, Camera* camera,
620 const Matrix& projection,
621 osg::GraphicsContext* gc,
622 bool useMasterSceneData)
624 flightgear::CameraInfo* info = 0;
625 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
626 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
631 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
632 _classicalRenderer = true;
633 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
637 flightgear::CameraInfo*
638 FGRenderer::buildClassicalPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
639 const osg::Matrix& view,
640 const osg::Matrix& projection,
641 bool useMasterSceneData)
643 CameraInfo* info = new CameraInfo(flags);
644 // The camera group will always update the camera
645 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
647 Camera* farCamera = 0;
648 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
649 farCamera = new Camera;
650 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
651 farCamera->setGraphicsContext(camera->getGraphicsContext());
652 farCamera->setCullingMode(camera->getCullingMode());
653 farCamera->setInheritanceMask(camera->getInheritanceMask());
654 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
655 // Each camera's viewport is written when the window is
656 // resized; if the the viewport isn't copied here, it gets updated
657 // twice and ends up with the wrong value.
658 farCamera->setViewport(simgear::clone(camera->getViewport()));
659 farCamera->setDrawBuffer(camera->getDrawBuffer());
660 farCamera->setReadBuffer(camera->getReadBuffer());
661 farCamera->setRenderTargetImplementation(
662 camera->getRenderTargetImplementation());
663 const Camera::BufferAttachmentMap& bufferMap
664 = camera->getBufferAttachmentMap();
665 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
667 Camera::COLOR_BUFFER,
668 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
670 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
671 installCullVisitor(farCamera);
672 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
673 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
674 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
675 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
676 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
678 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
679 installCullVisitor(camera);
680 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
681 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
682 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
683 cgroup->addCamera(info);
687 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
689 FGDeferredRenderingCameraCullCallback( flightgear::CameraKind k, CameraInfo* i ) : kind( k ), info( i ) {}
690 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
691 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
692 osg::Camera* camera = static_cast<osg::Camera*>(n);
694 cv->clearBufferList();
695 cv->addBuffer("depth", info->getBuffer( "depth" ) );
696 cv->addBuffer("normal", info->getBuffer( "normal" ) );
697 cv->addBuffer("diffuse", info->getBuffer( "diffuse" ) );
698 cv->addBuffer("spec-emis", info->getBuffer( "spec-emis" ) );
699 cv->addBuffer("lighting", info->getBuffer( "lighting" ) );
700 cv->addBuffer("shadow", info->getBuffer( "shadow" ) );
701 // cv->addBuffer(simgear::Effect::AO_BUFFER, info->gBuffer->aoBuffer[2]);
703 if ( !info->getRenderStageInfo(kind).fullscreen )
704 info->setMatrices( camera );
706 cv->traverse( *camera );
708 if ( kind == flightgear::GEOMETRY_CAMERA ) {
709 // Save transparent bins to render later
710 osgUtil::RenderStage* renderStage = cv->getRenderStage();
711 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
712 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
713 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
714 info->savedTransparentBins.insert( std::make_pair( rbi->first, rbi->second ) );
720 } else if ( kind == flightgear::LIGHTING_CAMERA ) {
721 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
722 if (mainShadowCamera.valid()) {
723 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
724 for (int i = 0; i < 4; ++i ) {
725 if (!grp->getValue(i))
727 osg::TexGen* shadowTexGen = info->shadowTexGen[i];
728 shadowTexGen->setMode(osg::TexGen::EYE_LINEAR);
730 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
731 // compute the matrix which takes a vertex from view coords into tex coords
732 shadowTexGen->setPlanesFromMatrix( cascadeCam->getProjectionMatrix() *
733 osg::Matrix::translate(1.0,1.0,1.0) *
734 osg::Matrix::scale(0.5f,0.5f,0.5f) );
736 osg::RefMatrix * refMatrix = new osg::RefMatrix( cascadeCam->getInverseViewMatrix() * *cv->getModelViewMatrix() );
738 cv->getRenderStage()->getPositionalStateContainer()->addPositionedTextureAttribute( i+1, refMatrix, shadowTexGen );
741 // Render saved transparent render bins
742 osgUtil::RenderStage* renderStage = cv->getRenderStage();
743 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
744 for (osgUtil::RenderBin::RenderBinList::iterator rbi = info->savedTransparentBins.begin(); rbi != info->savedTransparentBins.end(); ++rbi ){
745 rbl.insert( std::make_pair( rbi->first + 10000, rbi->second ) );
747 info->savedTransparentBins.clear();
752 flightgear::CameraKind kind;
756 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, osg::Texture::WrapMode wrapMode, bool shadowComparison = false)
758 osg::Texture2D* tex = new osg::Texture2D;
759 tex->setResizeNonPowerOfTwoHint( false );
760 tex->setInternalFormat( internalFormat );
761 tex->setShadowComparison(shadowComparison);
762 if (shadowComparison) {
763 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
764 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
766 tex->setSourceFormat(sourceFormat);
767 tex->setSourceType(sourceType);
768 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
769 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
770 tex->setWrap( osg::Texture::WRAP_S, wrapMode );
771 tex->setWrap( osg::Texture::WRAP_T, wrapMode );
775 void buildDeferredBuffers( flightgear::CameraInfo* info, int shadowMapSize, bool useColorForDepth )
777 if (useColorForDepth) {
778 info->addBuffer("real-depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
779 info->addBuffer("depth", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
782 info->addBuffer("depth", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER) );
784 info->addBuffer("normal", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
785 info->addBuffer("diffuse", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
786 info->addBuffer("spec-emis", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
787 info->addBuffer("lighting", buildDeferredBuffer( GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE, osg::Texture::CLAMP_TO_BORDER) );
788 info->addBuffer("shadow", buildDeferredBuffer( GL_DEPTH_COMPONENT32, GL_DEPTH_COMPONENT, GL_FLOAT, osg::Texture::CLAMP_TO_BORDER, true), 0.0f );
789 info->getBuffer("shadow")->setTextureSize(shadowMapSize,shadowMapSize);
792 void attachBufferToCamera( flightgear::CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, flightgear::CameraKind ck, const std::string& bk )
794 camera->attach( c, info->getBuffer(bk) );
795 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
798 osg::Camera* FGRenderer::buildDeferredGeometryCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
800 osg::Camera* camera = new osg::Camera;
801 info->addCamera(flightgear::GEOMETRY_CAMERA, camera );
803 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
804 camera->setName( "GeometryC" );
805 camera->setGraphicsContext( gc );
806 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::GEOMETRY_CAMERA, info ) );
807 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
808 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
809 camera->setClearDepth( 1.0 );
810 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
811 camera->setViewport( new osg::Viewport );
812 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER0, flightgear::GEOMETRY_CAMERA, "normal" );
813 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER1, flightgear::GEOMETRY_CAMERA, "diffuse" );
814 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER2, flightgear::GEOMETRY_CAMERA, "spec-emis" );
815 if (_useColorForDepth) {
816 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "real-depth" );
817 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER3, flightgear::GEOMETRY_CAMERA, "depth" );
819 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "depth" );
821 camera->setDrawBuffer(GL_FRONT);
822 camera->setReadBuffer(GL_FRONT);
824 osg::StateSet* ss = camera->getOrCreateStateSet();
825 ss->addUniform( _depthInColor );
827 camera->addChild( mDeferredRealRoot.get() );
832 static void setShadowCascadeStateSet( osg::Camera* cam ) {
833 osg::StateSet* ss = cam->getOrCreateStateSet();
834 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
835 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
836 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
837 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
838 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
839 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
840 osg::Program* program = new osg::Program;
841 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
842 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
843 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
844 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
845 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
846 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
847 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
848 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
849 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
852 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
853 osg::Camera* cascadeCam = new osg::Camera;
854 setShadowCascadeStateSet( cascadeCam );
856 std::ostringstream oss;
857 oss << "CascadeCamera" << (no + 1);
858 cascadeCam->setName( oss.str() );
859 cascadeCam->setClearMask(0);
860 cascadeCam->setCullMask(~( simgear::MODELLIGHT_BIT /* | simgear::NO_SHADOW_BIT */ ) );
861 cascadeCam->setCullingMode( cascadeCam->getCullingMode() & ~osg::CullSettings::SMALL_FEATURE_CULLING );
862 cascadeCam->setAllowEventFocus(false);
863 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
864 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
865 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
866 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
870 osg::Camera* FGRenderer::buildDeferredShadowCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
872 osg::Camera* mainShadowCamera = new osg::Camera;
873 info->addCamera(flightgear::SHADOW_CAMERA, mainShadowCamera, 0.0f );
875 mainShadowCamera->setName( "ShadowC" );
876 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
877 mainShadowCamera->setClearDepth( 1.0 );
878 mainShadowCamera->setAllowEventFocus(false);
879 mainShadowCamera->setGraphicsContext(gc);
880 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
881 attachBufferToCamera( info, mainShadowCamera, osg::Camera::DEPTH_BUFFER, flightgear::SHADOW_CAMERA, "shadow" );
882 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
883 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
884 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
885 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
886 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
887 mainShadowCamera->setDrawBuffer(GL_FRONT);
888 mainShadowCamera->setReadBuffer(GL_FRONT);
890 osg::Switch* shadowSwitch = new osg::Switch;
891 mainShadowCamera->addChild( shadowSwitch );
893 for (int i = 0; i < 4; ++i ) {
894 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
895 cascadeCam->addChild( mDeferredRealRoot.get() );
896 shadowSwitch->addChild( cascadeCam );
897 info->shadowTexGen[i] = new osg::TexGen;
899 if (fgGetBool("/sim/rendering/shadows/enabled", true))
900 shadowSwitch->setAllChildrenOn();
902 shadowSwitch->setAllChildrenOff();
904 return mainShadowCamera;
907 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)
909 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
910 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
911 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
913 osg::BoundingSphere bs;
914 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
915 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
916 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
917 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
919 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
921 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
922 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
923 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
926 osg::Vec3 FGRenderer::getSunDirection() const
929 _sunDirection->get( val );
933 void FGRenderer::updateShadowCamera(const flightgear::CameraInfo* info, const osg::Vec3d& position)
935 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
936 if (mainShadowCamera.valid()) {
937 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
938 osg::Vec3d up = position,
939 dir = getSunDirection();
942 // cos(100 deg) == -0.17
943 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
944 shadowSwitch->setAllChildrenOff();
946 double left,right,bottom,top,zNear,zFar;
947 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
948 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
950 shadowSwitch->setAllChildrenOn();
951 if (_numCascades == 1) {
952 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
953 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
955 for (int no = 0; no < 4; ++no) {
956 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
957 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
960 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
961 if (_numCascades > 1) {
962 shadowSwitch->setValue(1, true);
963 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
965 shadowSwitch->setValue(1, false);
967 if (_numCascades > 2) {
968 shadowSwitch->setValue(2, true);
969 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
971 shadowSwitch->setValue(2, false);
973 if (_numCascades > 3) {
974 shadowSwitch->setValue(3, true);
975 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
977 shadowSwitch->setValue(3, false);
980 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
982 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
984 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
985 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
991 void FGRenderer::updateShadowMapSize(int mapSize)
993 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
994 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
997 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
998 ii != CameraGroup::getDefault()->camerasEnd();
1001 CameraInfo* info = ii->get();
1002 Camera* camera = info->getCamera(SHADOW_CAMERA);
1003 if (camera == 0) continue;
1005 Texture2D* tex = info->getBuffer("shadow");
1006 if (tex == 0) continue;
1008 tex->setTextureSize( mapSize, mapSize );
1009 tex->dirtyTextureObject();
1011 Viewport* vp = camera->getViewport();
1012 vp->width() = mapSize;
1013 vp->height() = mapSize;
1015 osgViewer::Renderer* renderer
1016 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
1017 for (int i = 0; i < 2; ++i) {
1018 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
1019 sceneView->getRenderStage()->setFrameBufferObject(0);
1020 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
1021 if (sceneView->getRenderStageLeft()) {
1022 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
1023 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
1025 if (sceneView->getRenderStageRight()) {
1026 sceneView->getRenderStageRight()->setFrameBufferObject(0);
1027 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1031 int cascadeSize = mapSize / 2;
1032 Group* grp = camera->getChild(0)->asGroup();
1033 for (int i = 0; i < 4; ++i ) {
1034 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1035 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1038 _shadowMapSize = mapSize;
1042 void FGRenderer::enableShadows(bool enabled)
1044 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1045 ii != CameraGroup::getDefault()->camerasEnd();
1048 CameraInfo* info = ii->get();
1049 Camera* camera = info->getCamera(SHADOW_CAMERA);
1050 if (camera == 0) continue;
1052 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1054 shadowSwitch->setAllChildrenOn();
1056 shadowSwitch->setAllChildrenOff();
1060 void FGRenderer::updateCascadeFar(int index, float far_m)
1062 if (index < 0 || index > 3)
1064 _cascadeFar[index] = far_m;
1065 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1068 void FGRenderer::updateCascadeNumber(size_t num)
1070 if (num < 1 || num > 4)
1073 _shadowNumber->set( (int)_numCascades );
1076 osg::Camera* FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc )
1078 osg::Camera* camera = new osg::Camera;
1079 info->addCamera(flightgear::LIGHTING_CAMERA, camera );
1081 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::LIGHTING_CAMERA, info ) );
1082 camera->setAllowEventFocus(false);
1083 camera->setGraphicsContext(gc);
1084 camera->setViewport(new Viewport);
1085 camera->setName("LightingC");
1086 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1087 camera->setRenderOrder(osg::Camera::POST_RENDER, 50);
1088 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1089 camera->setViewport( new osg::Viewport );
1090 attachBufferToCamera( info, camera, osg::Camera::COLOR_BUFFER, flightgear::LIGHTING_CAMERA, "lighting" );
1091 if (_useColorForDepth) {
1092 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "real-depth" );
1094 attachBufferToCamera( info, camera, osg::Camera::DEPTH_BUFFER, flightgear::GEOMETRY_CAMERA, "depth" );
1096 camera->setDrawBuffer(GL_FRONT);
1097 camera->setReadBuffer(GL_FRONT);
1098 camera->setClearColor( osg::Vec4( 0., 0., 0., 1. ) );
1099 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1100 osg::StateSet* ss = camera->getOrCreateStateSet();
1101 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1102 ss->addUniform( _depthInColor );
1104 osg::Group* lightingGroup = new osg::Group;
1106 osg::Camera* quadCam1 = new osg::Camera;
1107 quadCam1->setName( "QuadCamera1" );
1108 quadCam1->setClearMask(0);
1109 quadCam1->setAllowEventFocus(false);
1110 quadCam1->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1111 quadCam1->setRenderOrder(osg::Camera::NESTED_RENDER);
1112 quadCam1->setViewMatrix(osg::Matrix::identity());
1113 quadCam1->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1114 quadCam1->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1115 ss = quadCam1->getOrCreateStateSet();
1116 ss->addUniform( _ambientFactor );
1117 ss->addUniform( info->projInverse );
1118 ss->addUniform( info->viewInverse );
1119 ss->addUniform( info->view );
1120 ss->addUniform( _sunDiffuse );
1121 ss->addUniform( _sunSpecular );
1122 ss->addUniform( _sunDirection );
1123 ss->addUniform( _planes );
1124 ss->addUniform( _shadowNumber );
1125 ss->addUniform( _shadowDistances );
1127 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1128 g->setUseDisplayList(false);
1129 simgear::EffectGeode* eg = new simgear::EffectGeode;
1130 simgear::Effect* effect = simgear::makeEffect("Effects/ambient", true);
1132 SG_LOG(SG_VIEW, SG_ALERT, "Effects/ambient not found");
1135 eg->setEffect( effect );
1136 g->setName( "AmbientQuad" );
1137 eg->setName("AmbientQuad");
1138 eg->setCullingActive(false);
1140 quadCam1->addChild( eg );
1142 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1143 g->setUseDisplayList(false);
1144 g->setName( "SunlightQuad" );
1145 eg = new simgear::EffectGeode;
1146 effect = simgear::makeEffect("Effects/sunlight", true);
1148 SG_LOG(SG_VIEW, SG_ALERT, "Effects/sunlight not found");
1151 eg->setEffect( effect );
1152 eg->setName("SunlightQuad");
1153 eg->setCullingActive(false);
1155 quadCam1->addChild( eg );
1157 osg::Camera* lightCam = new osg::Camera;
1158 ss = lightCam->getOrCreateStateSet();
1159 ss->addUniform( _planes );
1160 ss->addUniform( info->bufferSize );
1161 lightCam->setName( "LightCamera" );
1162 lightCam->setClearMask(0);
1163 lightCam->setAllowEventFocus(false);
1164 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1165 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,1);
1166 lightCam->setViewMatrix(osg::Matrix::identity());
1167 lightCam->setProjectionMatrix(osg::Matrix::identity());
1168 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1169 lightCam->setCullMask( simgear::MODELLIGHT_BIT );
1170 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1171 lightCam->addChild( mDeferredRealRoot.get() );
1174 osg::Camera* quadCam2 = new osg::Camera;
1175 quadCam2->setName( "QuadCamera1" );
1176 quadCam2->setClearMask(0);
1177 quadCam2->setAllowEventFocus(false);
1178 quadCam2->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1179 quadCam2->setRenderOrder(osg::Camera::NESTED_RENDER,2);
1180 quadCam2->setViewMatrix(osg::Matrix::identity());
1181 quadCam2->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1182 quadCam2->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1183 ss = quadCam2->getOrCreateStateSet();
1184 ss->addUniform( _ambientFactor );
1185 ss->addUniform( info->projInverse );
1186 ss->addUniform( info->viewInverse );
1187 ss->addUniform( info->view );
1188 ss->addUniform( _sunDiffuse );
1189 ss->addUniform( _sunSpecular );
1190 ss->addUniform( _sunDirection );
1191 ss->addUniform( _fogColor );
1192 ss->addUniform( _fogDensity );
1193 ss->addUniform( _planes );
1195 g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1196 g->setUseDisplayList(false);
1197 g->setName( "FogQuad" );
1198 eg = new simgear::EffectGeode;
1199 effect = simgear::makeEffect("Effects/fog", true);
1201 SG_LOG(SG_VIEW, SG_ALERT, "Effects/fog not found");
1204 eg->setEffect( effect );
1205 eg->setName("FogQuad");
1206 eg->setCullingActive(false);
1208 quadCam2->addChild( eg );
1210 lightingGroup->addChild( _sky->getPreRoot() );
1211 lightingGroup->addChild( _sky->getCloudRoot() );
1212 lightingGroup->addChild( quadCam1 );
1213 lightingGroup->addChild( lightCam );
1214 lightingGroup->addChild( quadCam2 );
1216 camera->addChild( lightingGroup );
1221 flightgear::CameraInfo*
1222 FGRenderer::buildDeferredPipeline(flightgear::CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1223 const osg::Matrix& view,
1224 const osg::Matrix& projection,
1225 osg::GraphicsContext* gc)
1227 CameraInfo* info = new CameraInfo(flags);
1228 buildDeferredBuffers(info, _shadowMapSize, _useColorForDepth);
1230 osg::Camera* geometryCamera = buildDeferredGeometryCamera( info, gc );
1231 cgroup->getViewer()->addSlave(geometryCamera, false);
1232 installCullVisitor(geometryCamera);
1233 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1234 info->getRenderStageInfo(GEOMETRY_CAMERA).slaveIndex = slaveIndex;
1236 Camera* shadowCamera = buildDeferredShadowCamera( info, gc );
1237 cgroup->getViewer()->addSlave(shadowCamera, false);
1238 installCullVisitor(shadowCamera);
1239 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1240 info->getRenderStageInfo(SHADOW_CAMERA).slaveIndex = slaveIndex;
1242 osg::Camera* lightingCamera = buildDeferredLightingCamera( info, gc );
1243 cgroup->getViewer()->addSlave(lightingCamera, false);
1244 installCullVisitor(lightingCamera);
1245 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1246 info->getRenderStageInfo(LIGHTING_CAMERA).slaveIndex = slaveIndex;
1248 camera->setName( "DisplayC" );
1249 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( flightgear::DISPLAY_CAMERA, info ) );
1250 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1251 camera->setAllowEventFocus(false);
1252 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1253 g->setUseDisplayList(false); //DEBUG
1254 simgear::EffectGeode* eg = new simgear::EffectGeode;
1255 simgear::Effect* effect = simgear::makeEffect("Effects/display", true);
1257 SG_LOG(SG_VIEW, SG_ALERT, "Effects/display not found");
1260 eg->setEffect(effect);
1261 eg->setCullingActive(false);
1263 camera->setViewMatrix(osg::Matrix::identity());
1264 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1265 camera->addChild(eg);
1267 osg::StateSet* ss = camera->getOrCreateStateSet();
1268 ss->addUniform( _depthInColor );
1270 cgroup->getViewer()->addSlave(camera, false);
1271 installCullVisitor(camera);
1272 slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1273 info->addCamera( DISPLAY_CAMERA, camera, slaveIndex, true );
1274 camera->setRenderOrder(Camera::POST_RENDER, 99+slaveIndex); //FIXME
1275 cgroup->addCamera(info);
1281 FGRenderer::setupView( void )
1283 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1284 osg::initNotifyLevel();
1286 // The number of polygon-offset "units" to place between layers. In
1287 // principle, one is supposed to be enough. In practice, I find that
1288 // my hardware/driver requires many more.
1289 osg::PolygonOffset::setUnitsMultiplier(1);
1290 osg::PolygonOffset::setFactorMultiplier(1);
1292 // Go full screen if requested ...
1293 if ( fgGetBool("/sim/startup/fullscreen") )
1297 // The sun and moon diameters are scaled down numbers of the
1298 // actual diameters. This was needed to fit both the sun and the
1299 // moon within the distance to the far clip plane.
1300 // Moon diameter: 3,476 kilometers
1301 // Sun diameter: 1,390,000 kilometers
1302 _sky->build( 80000.0, 80000.0,
1304 *globals->get_ephem(),
1305 fgGetNode("/environment", true));
1308 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1310 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1312 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1314 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1315 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1317 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1318 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1319 stateSet->setAttribute(new osg::BlendFunc);
1320 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1322 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1324 // this will be set below
1325 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1327 osg::Material* material = new osg::Material;
1328 stateSet->setAttribute(material);
1330 stateSet->setTextureAttribute(0, new osg::TexEnv);
1331 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1333 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1334 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1335 stateSet->setAttribute(hint);
1336 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1337 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1338 stateSet->setAttribute(hint);
1339 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1340 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1341 stateSet->setAttribute(hint);
1342 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1343 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1344 stateSet->setAttribute(hint);
1345 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1346 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1347 stateSet->setAttribute(hint);
1349 osg::Group* sceneGroup = new osg::Group;
1350 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1351 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1353 //sceneGroup->addChild(thesky->getCloudRoot());
1355 stateSet = sceneGroup->getOrCreateStateSet();
1356 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1358 // need to update the light on every frame
1359 // OSG LightSource objects are rather confusing. OSG only supports
1360 // the 10 lights specified by OpenGL itself; if more than one
1361 // LightSource in the scene graph have the same light number, it's
1362 // indeterminate which values will be used to render geometry that
1363 // has that light number enabled. Also, adding children to a
1364 // LightSource is just a shortcut for setting up a state set that
1365 // has the corresponding OpenGL light enabled: a LightSource will
1366 // affect geometry anywhere in the scene graph that has its light
1367 // number enabled in a state set.
1368 LightSource* lightSource = new LightSource;
1369 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1370 // relative because of CameraView being just a clever transform node
1371 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1372 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1373 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1374 mRealRoot->addChild(lightSource);
1375 // we need a white diffuse light for the phase of the moon
1376 osg::LightSource* sunLight = new osg::LightSource;
1377 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1378 sunLight->getLight()->setLightNum(1);
1379 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1380 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1381 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1383 // Hang a StateSet above the sky subgraph in order to turn off
1385 Group* skyGroup = new Group;
1386 StateSet* skySS = skyGroup->getOrCreateStateSet();
1387 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1388 skyGroup->addChild(_sky->getPreRoot());
1389 sunLight->addChild(skyGroup);
1390 mRoot->addChild(sceneGroup);
1391 if ( _classicalRenderer )
1392 mRoot->addChild(sunLight);
1394 // Clouds are added to the scene graph later
1395 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1396 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1397 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1398 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1400 // enable disable specular highlights.
1401 // is the place where we might plug in an other fragment shader ...
1402 osg::LightModel* lightModel = new osg::LightModel;
1403 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1404 stateSet->setAttribute(lightModel);
1406 // switch to enable wireframe
1407 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1408 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1409 stateSet->setAttributeAndModes(polygonMode);
1411 // scene fog handling
1412 osg::Fog* fog = new osg::Fog;
1413 fog->setUpdateCallback(new FGFogUpdateCallback);
1414 stateSet->setAttributeAndModes(fog);
1415 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1418 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1421 osg::Geode* geode = new osg::Geode;
1422 geode->addDrawable(new SGPuDrawable);
1423 geode->addDrawable(new SGHUDDrawable);
1424 guiCamera->addChild(geode);
1426 panelSwitch = new osg::Switch;
1427 osg::StateSet* stateSet = panelSwitch->getOrCreateStateSet();
1428 stateSet->setRenderBinDetails(1000, "RenderBin");
1430 // speed optimization?
1431 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
1432 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
1433 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
1434 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1435 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1438 panelSwitch->setUpdateCallback(new FGPanelSwitchCallback);
1441 guiCamera->addChild(panelSwitch.get());
1444 osg::Switch* sw = new osg::Switch;
1445 sw->setUpdateCallback(new FGScenerySwitchCallback);
1446 sw->addChild(mRoot.get());
1447 mRealRoot->addChild(sw);
1448 // The clouds are attached directly to the scene graph root
1449 // because, in theory, they don't want the same default state set
1450 // as the rest of the scene. This may not be true in practice.
1451 if ( _classicalRenderer ) {
1452 mRealRoot->addChild(_sky->getCloudRoot());
1453 mRealRoot->addChild(FGCreateRedoutNode());
1455 // Attach empty program to the scene root so that shader programs
1456 // don't leak into state sets (effects) that shouldn't have one.
1457 stateSet = mRealRoot->getOrCreateStateSet();
1458 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1460 mDeferredRealRoot->addChild( mRealRoot.get() );
1463 void FGRenderer::panelChanged()
1469 osg::Node* n = FGPanelNode::createNode(globals->get_current_panel());
1470 if (panelSwitch->getNumChildren()) {
1471 panelSwitch->setChild(0, n);
1473 panelSwitch->addChild(n);
1477 // Update all Visuals (redraws anything graphics related)
1479 FGRenderer::update( ) {
1480 if (!(_scenery_loaded->getBoolValue() ||
1481 _scenery_override->getBoolValue()))
1483 _splash_alpha->setDoubleValue(1.0);
1486 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1488 if (_splash_alpha->getDoubleValue()>0.0)
1490 // Fade out the splash screen
1491 const double fade_time = 0.5;
1492 const double fade_steps_per_sec = 10;
1493 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1494 (SGTimeStamp::now() - _splash_time).toSecs());
1495 _splash_time = SGTimeStamp::now();
1496 double sAlpha = _splash_alpha->getDoubleValue();
1497 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1498 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1499 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1502 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1503 if (!_classicalRenderer ) {
1504 _ambientFactor->set( toOsg(l->scene_ambient()) );
1505 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1506 _sunSpecular->set( toOsg(l->scene_specular()) );
1507 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1510 // update fog params
1511 double actual_visibility;
1512 if (_cloud_status->getBoolValue()) {
1513 actual_visibility = _sky->get_visibility();
1515 actual_visibility = _visibility_m->getDoubleValue();
1518 // idle_state is now 1000 meaning we've finished all our
1519 // initializations and are running the main loop, so this will
1520 // now work without seg faulting the system.
1522 FGViewer *current__view = globals->get_current_view();
1523 // Force update of center dependent values ...
1524 current__view->set_dirty();
1526 osg::Camera *camera = viewer->getCamera();
1528 bool skyblend = _skyblend->getBoolValue();
1531 if ( _textures->getBoolValue() ) {
1532 SGVec4f clearColor(l->adj_fog_color());
1533 camera->setClearColor(toOsg(clearColor));
1536 SGVec4f clearColor(l->sky_color());
1537 camera->setClearColor(toOsg(clearColor));
1540 // update fog params if visibility has changed
1541 double visibility_meters = _visibility_m->getDoubleValue();
1542 _sky->set_visibility(visibility_meters);
1544 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1545 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1547 // update the sky dome
1550 // The sun and moon distances are scaled down versions
1551 // of the actual distance to get both the moon and the sun
1552 // within the range of the far clip plane.
1553 // Moon distance: 384,467 kilometers
1554 // Sun distance: 150,000,000 kilometers
1556 double sun_horiz_eff, moon_horiz_eff;
1557 if (_horizon_effect->getBoolValue()) {
1559 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1563 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1567 sun_horiz_eff = moon_horiz_eff = 1.0;
1571 sstate.pos = current__view->getViewPosition();
1572 sstate.pos_geod = current__view->getPosition();
1573 sstate.ori = current__view->getViewOrientation();
1574 sstate.spin = l->get_sun_rotation();
1575 sstate.gst = globals->get_time_params()->getGst();
1576 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1577 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1578 sstate.sun_angle = l->get_sun_angle();
1581 scolor.sky_color = SGVec3f(l->sky_color().data());
1582 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1583 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1584 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1585 scolor.sun_angle = l->get_sun_angle();
1586 scolor.moon_angle = l->get_moon_angle();
1588 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1589 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1590 _sky->repaint( scolor, *globals->get_ephem() );
1593 // shadows->setupShadows(
1594 // current__view->getLongitude_deg(),
1595 // current__view->getLatitude_deg(),
1596 // globals->get_time_params()->getGst(),
1597 // globals->get_ephem()->getSunRightAscension(),
1598 // globals->get_ephem()->getSunDeclination(),
1599 // l->get_sun_angle());
1603 // sgEnviro.setLight(l->adj_fog_color());
1604 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1605 // current__view->get_world_up(),
1606 // current__view->getLongitude_deg(),
1607 // current__view->getLatitude_deg(),
1608 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1612 // sgEnviro.drawLightning();
1614 // double current_view_origin_airspeed_horiz_kt =
1615 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1616 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1617 // * SGD_DEGREES_TO_RADIANS);
1620 // if( is_internal )
1621 // shadows->endOfFrame();
1623 // need to call the update visitor once
1624 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1625 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1626 current__view->getViewOrientation());
1627 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1628 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1629 l->scene_diffuse(), l->scene_specular(),
1631 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1632 mUpdateVisitor->setVisibility(actual_visibility);
1633 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1634 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1635 cullMask |= simgear::GroundLightManager::instance()
1636 ->getLightNodeMask(mUpdateVisitor.get());
1637 if (_panel_hotspots->getBoolValue())
1638 cullMask |= simgear::PICK_BIT;
1639 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1640 if ( !_classicalRenderer ) {
1641 _fogColor->set( toOsg( l->adj_fog_color() ) );
1642 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1647 FGRenderer::resize( int width, int height )
1649 int curWidth = _xsize->getIntValue(),
1650 curHeight = _ysize->getIntValue();
1651 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1652 if ((curHeight != height) || (curWidth != width)) {
1653 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1654 _xsize->setIntValue(width);
1655 _ysize->setIntValue(height);
1660 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1661 const osgGA::GUIEventAdapter* ea)
1663 // wipe out the return ...
1665 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1666 Intersections intersections;
1668 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1670 for (Intersections::iterator hit = intersections.begin(),
1671 e = intersections.end();
1674 const osg::NodePath& np = hit->nodePath;
1675 osg::NodePath::const_reverse_iterator npi;
1676 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1677 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1680 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1681 SGPickCallback* pickCallback = ud->getPickCallback(i);
1684 SGSceneryPick sceneryPick;
1685 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1686 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1687 sceneryPick.callback = pickCallback;
1688 pickList.push_back(sceneryPick);
1692 return !pickList.empty();
1696 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1702 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1704 eventHandler = eventHandler_;
1708 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1710 mRealRoot->addChild(camera);
1714 FGRenderer::removeCamera(osg::Camera* camera)
1716 mRealRoot->removeChild(camera);
1720 FGRenderer::setPlanes( double zNear, double zFar )
1722 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1726 fgDumpSceneGraphToFile(const char* filename)
1728 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1732 fgDumpTerrainBranchToFile(const char* filename)
1734 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1740 fgDumpNodeToFile(osg::Node* node, const char* filename)
1742 return osgDB::writeNodeFile(*node, filename);
1745 namespace flightgear
1747 using namespace osg;
1749 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1752 VisibleSceneInfoVistor()
1753 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1755 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1756 | CullSettings::VIEW_FRUSTUM_CULLING);
1757 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1760 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1764 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1766 typedef std::map<const std::string,int> InfoMap;
1768 void getNodeInfo(Node* node)
1770 const char* typeName = typeid(*node).name();
1771 classInfo[typeName]++;
1772 const std::string& nodeName = node->getName();
1773 if (!nodeName.empty())
1774 nodeInfo[nodeName]++;
1779 using namespace std;
1780 typedef vector<InfoMap::iterator> FreqVector;
1781 cout << "class info:\n";
1783 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1786 classes.push_back(itr);
1787 sort(classes.begin(), classes.end(), freqComp);
1788 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1791 cout << (*itr)->first << " " << (*itr)->second << "\n";
1793 cout << "\nnode info:\n";
1795 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1798 nodes.push_back(itr);
1800 sort (nodes.begin(), nodes.end(), freqComp);
1801 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1804 cout << (*itr)->first << " " << (*itr)->second << "\n";
1809 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1811 ref_ptr<RefMatrix> projection
1812 = createOrReuseMatrix(camera->getProjectionMatrix());
1813 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1815 viewport = camera->getViewport();
1817 pushViewport(viewport);
1818 pushProjectionMatrix(projection.get());
1819 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1820 root->accept(*this);
1821 popModelViewMatrix();
1822 popProjectionMatrix();
1828 void apply(Node& node)
1837 void apply(Group& node)
1847 void apply(Transform& node)
1852 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1853 node.computeLocalToWorldMatrix(*matrix,this);
1854 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1857 popModelViewMatrix();
1861 void apply(Camera& camera)
1863 // Save current cull settings
1864 CullSettings saved_cull_settings(*this);
1866 // set cull settings from this Camera
1867 setCullSettings(camera);
1868 // inherit the settings from above
1869 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1871 // set the cull mask.
1872 unsigned int savedTraversalMask = getTraversalMask();
1873 bool mustSetCullMask = (camera.getInheritanceMask()
1874 & osg::CullSettings::CULL_MASK) == 0;
1875 if (mustSetCullMask)
1876 setTraversalMask(camera.getCullMask());
1878 osg::RefMatrix* projection = 0;
1879 osg::RefMatrix* modelview = 0;
1881 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1882 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1883 projection = createOrReuseMatrix(*getProjectionMatrix()
1884 *camera.getProjectionMatrix());
1885 modelview = createOrReuseMatrix(*getModelViewMatrix()
1886 * camera.getViewMatrix());
1888 else { // pre multiply
1889 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1890 * (*getProjectionMatrix()));
1891 modelview = createOrReuseMatrix(camera.getViewMatrix()
1892 * (*getModelViewMatrix()));
1895 // an absolute reference frame
1896 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1897 modelview = createOrReuseMatrix(camera.getViewMatrix());
1899 if (camera.getViewport())
1900 pushViewport(camera.getViewport());
1902 pushProjectionMatrix(projection);
1903 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1907 // restore the previous model view matrix.
1908 popModelViewMatrix();
1910 // restore the previous model view matrix.
1911 popProjectionMatrix();
1913 if (camera.getViewport()) popViewport();
1915 // restore the previous traversal mask settings
1916 if (mustSetCullMask)
1917 setTraversalMask(savedTraversalMask);
1919 // restore the previous cull settings
1920 setCullSettings(saved_cull_settings);
1925 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1927 return lhs->second > rhs->second;
1933 bool printVisibleSceneInfo(FGRenderer* renderer)
1935 osgViewer::Viewer* viewer = renderer->getViewer();
1936 VisibleSceneInfoVistor vsv;
1938 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1939 const View::Slave& slave = viewer->getSlave(0);
1940 vp = slave._camera->getViewport();
1942 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1947 // end of renderer.cxx