1 // renderer.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
6 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
30 #include <simgear/compiler.h>
38 #include <boost/foreach.hpp>
40 #include <osg/ref_ptr>
41 #include <osg/AlphaFunc>
42 #include <osg/BlendFunc>
44 #include <osg/CullFace>
45 #include <osg/CullStack>
51 #include <osg/LightModel>
52 #include <osg/LightSource>
53 #include <osg/Material>
55 #include <osg/NodeCallback>
57 #include <osg/PolygonMode>
58 #include <osg/PolygonOffset>
59 #include <osg/Program>
60 #include <osg/Version>
63 #include <osgUtil/LineSegmentIntersector>
65 #include <osg/io_utils>
66 #include <osgDB/WriteFile>
67 #include <osgViewer/Renderer>
69 #include <simgear/scene/material/matlib.hxx>
70 #include <simgear/scene/material/EffectCullVisitor.hxx>
71 #include <simgear/scene/material/Effect.hxx>
72 #include <simgear/scene/material/EffectGeode.hxx>
73 #include <simgear/scene/material/EffectBuilder.hxx>
74 #include <simgear/scene/model/animation.hxx>
75 #include <simgear/scene/model/placement.hxx>
76 #include <simgear/scene/sky/sky.hxx>
77 #include <simgear/scene/util/DeletionManager.hxx>
78 #include <simgear/scene/util/SGUpdateVisitor.hxx>
79 #include <simgear/scene/util/RenderConstants.hxx>
80 #include <simgear/scene/util/SGSceneUserData.hxx>
81 #include <simgear/scene/tgdb/GroundLightManager.hxx>
82 #include <simgear/scene/tgdb/pt_lights.hxx>
83 #include <simgear/scene/tgdb/userdata.hxx>
84 #include <simgear/structure/OSGUtils.hxx>
85 #include <simgear/props/props.hxx>
86 #include <simgear/timing/sg_time.hxx>
87 #include <simgear/ephemeris/ephemeris.hxx>
88 #include <simgear/math/sg_random.h>
90 #include <simgear/screen/jpgfactory.hxx>
93 #include <Time/light.hxx>
94 #include <Time/light.hxx>
95 #include <Cockpit/panel.hxx>
97 #include <Model/panelnode.hxx>
98 #include <Model/modelmgr.hxx>
99 #include <Model/acmodel.hxx>
100 #include <Scenery/scenery.hxx>
101 #include <Scenery/redout.hxx>
102 #include <GUI/new_gui.hxx>
103 #include <Instrumentation/HUD/HUD.hxx>
104 #include <Environment/precipitation_mgr.hxx>
105 #include <Environment/environment_mgr.hxx>
107 //#include <Main/main.hxx>
108 #include "viewer.hxx"
109 #include "viewmgr.hxx"
110 #include "splash.hxx"
111 #include "renderer.hxx"
112 #include "CameraGroup.hxx"
113 #include "FGEventHandler.hxx"
116 using namespace simgear;
117 using namespace flightgear;
119 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
121 FGHintUpdateCallback(const char* configNode) :
122 mConfigNode(fgGetNode(configNode, true))
124 virtual void operator()(osg::StateAttribute* stateAttribute,
127 assert(dynamic_cast<osg::Hint*>(stateAttribute));
128 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
130 const char* value = mConfigNode->getStringValue();
132 hint->setMode(GL_DONT_CARE);
133 else if (0 == strcmp(value, "nicest"))
134 hint->setMode(GL_NICEST);
135 else if (0 == strcmp(value, "fastest"))
136 hint->setMode(GL_FASTEST);
138 hint->setMode(GL_DONT_CARE);
141 SGPropertyNode_ptr mConfigNode;
145 class SGPuDrawable : public osg::Drawable {
149 // Dynamic stuff, do not store geometry
150 setUseDisplayList(false);
151 setDataVariance(Object::DYNAMIC);
153 osg::StateSet* stateSet = getOrCreateStateSet();
154 stateSet->setRenderBinDetails(1001, "RenderBin");
155 // speed optimization?
156 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
157 // We can do translucent menus, so why not. :-)
158 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
159 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
160 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
162 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
164 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
165 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
167 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
168 { drawImplementation(*renderInfo.getState()); }
169 void drawImplementation(osg::State& state) const
171 state.setActiveTextureUnit(0);
172 state.setClientActiveTextureUnit(0);
174 state.disableAllVertexArrays();
176 glPushAttrib(GL_ALL_ATTRIB_BITS);
177 glPushClientAttrib(~0u);
185 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
186 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
191 class SGHUDDrawable : public osg::Drawable {
195 // Dynamic stuff, do not store geometry
196 setUseDisplayList(false);
197 setDataVariance(Object::DYNAMIC);
199 osg::StateSet* stateSet = getOrCreateStateSet();
200 stateSet->setRenderBinDetails(1000, "RenderBin");
202 // speed optimization?
203 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
204 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
205 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
206 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
207 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
209 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
211 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
212 { drawImplementation(*renderInfo.getState()); }
213 void drawImplementation(osg::State& state) const
215 state.setActiveTextureUnit(0);
216 state.setClientActiveTextureUnit(0);
217 state.disableAllVertexArrays();
219 glPushAttrib(GL_ALL_ATTRIB_BITS);
220 glPushClientAttrib(~0u);
222 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
229 virtual osg::Object* cloneType() const { return new SGHUDDrawable; }
230 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDDrawable; }
235 class FGLightSourceUpdateCallback : public osg::NodeCallback {
239 * @param isSun true if the light is the actual sun i.e., for
240 * illuminating the moon.
242 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
243 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
245 : NodeCallback(nc, op), _isSun(nc._isSun)
247 META_Object(flightgear,FGLightSourceUpdateCallback);
249 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
251 assert(dynamic_cast<osg::LightSource*>(node));
252 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
253 osg::Light* light = lightSource->getLight();
255 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
257 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
258 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
259 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
261 light->setAmbient(toOsg(l->scene_ambient()));
262 light->setDiffuse(toOsg(l->scene_diffuse()));
263 light->setSpecular(toOsg(l->scene_specular()));
265 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
266 light->setPosition(position);
274 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
276 FGWireFrameModeUpdateCallback() :
277 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
279 virtual void operator()(osg::StateAttribute* stateAttribute,
282 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
283 osg::PolygonMode* polygonMode;
284 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
286 if (mWireframe->getBoolValue())
287 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
288 osg::PolygonMode::LINE);
290 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
291 osg::PolygonMode::FILL);
294 SGPropertyNode_ptr mWireframe;
297 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
299 FGLightModelUpdateCallback() :
300 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
302 virtual void operator()(osg::StateAttribute* stateAttribute,
305 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
306 osg::LightModel* lightModel;
307 lightModel = static_cast<osg::LightModel*>(stateAttribute);
310 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
311 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
313 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
315 lightModel->setTwoSided(true);
316 lightModel->setLocalViewer(false);
318 if (mHighlights->getBoolValue()) {
319 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
321 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
325 SGPropertyNode_ptr mHighlights;
328 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
330 FGFogEnableUpdateCallback() :
331 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
333 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
335 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
336 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
338 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
342 SGPropertyNode_ptr mFogEnabled;
345 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
347 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
349 assert(dynamic_cast<SGUpdateVisitor*>(nv));
350 assert(dynamic_cast<osg::Fog*>(sa));
351 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
352 osg::Fog* fog = static_cast<osg::Fog*>(sa);
353 fog->setMode(osg::Fog::EXP2);
354 fog->setColor(toOsg(updateVisitor->getFogColor()));
355 fog->setDensity(updateVisitor->getFogExp2Density());
359 // update callback for the switch node guarding that splash
360 class FGScenerySwitchCallback : public osg::NodeCallback {
362 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
364 assert(dynamic_cast<osg::Switch*>(node));
365 osg::Switch* sw = static_cast<osg::Switch*>(node);
367 bool enabled = scenery_enabled;
368 sw->setValue(0, enabled);
374 static bool scenery_enabled;
377 bool FGScenerySwitchCallback::scenery_enabled = false;
379 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
380 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
382 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
383 static osg::ref_ptr<osg::Group> mDeferredRealRoot = new osg::Group;
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
387 #ifdef FG_JPEG_SERVER
388 static void updateRenderer()
390 globals->get_renderer()->update();
394 FGRenderer::FGRenderer() :
396 _ambientFactor( new osg::Uniform( "fg_SunAmbientColor", osg::Vec4f() ) ),
397 _sunDiffuse( new osg::Uniform( "fg_SunDiffuseColor", osg::Vec4f() ) ),
398 _sunSpecular( new osg::Uniform( "fg_SunSpecularColor", osg::Vec4f() ) ),
399 _sunDirection( new osg::Uniform( "fg_SunDirection", osg::Vec3f() ) ),
400 _planes( new osg::Uniform( "fg_Planes", osg::Vec3f() ) ),
401 _fogColor( new osg::Uniform( "fg_FogColor", osg::Vec4f(1.0, 1.0, 1.0, 1.0) ) ),
402 _fogDensity( new osg::Uniform( "fg_FogDensity", 0.0001f ) ),
403 _shadowNumber( new osg::Uniform( "fg_ShadowNumber", (int)4 ) ),
404 _shadowDistances( new osg::Uniform( "fg_ShadowDistances", osg::Vec4f(5.0, 50.0, 500.0, 5000.0 ) ) ),
405 _depthInColor( new osg::Uniform( "fg_DepthInColor", false ) )
407 #ifdef FG_JPEG_SERVER
408 jpgRenderFrame = updateRenderer;
410 eventHandler = new FGEventHandler;
413 _cascadeFar[0] = 5.f;
414 _cascadeFar[1] = 50.f;
415 _cascadeFar[2] = 500.f;
416 _cascadeFar[3] = 5000.f;
419 FGRenderer::~FGRenderer()
421 #ifdef FG_JPEG_SERVER
422 jpgRenderFrame = NULL;
427 // Initialize various GL/view parameters
428 // XXX This should be called "preinit" or something, as it initializes
429 // critical parts of the scene graph in addition to the splash screen.
431 FGRenderer::splashinit( void ) {
432 osgViewer::Viewer* viewer = getViewer();
433 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
434 ref_ptr<Node> splashNode = fgCreateSplashNode();
435 if (_classicalRenderer) {
436 mRealRoot->addChild(splashNode.get());
438 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
439 ii != CameraGroup::getDefault()->camerasEnd();
442 CameraInfo* info = ii->get();
443 Camera* camera = info->getCamera(DISPLAY_CAMERA);
444 if (camera == 0) continue;
446 camera->addChild(splashNode.get());
449 mFrameStamp = viewer->getFrameStamp();
450 // Scene doesn't seem to pass the frame stamp to the update
451 // visitor automatically.
452 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
453 viewer->setUpdateVisitor(mUpdateVisitor.get());
454 fgSetDouble("/sim/startup/splash-alpha", 1.0);
457 class ShadowMapSizeListener : public SGPropertyChangeListener {
459 virtual void valueChanged(SGPropertyNode* node) {
460 globals->get_renderer()->updateShadowMapSize(node->getIntValue());
464 class ShadowEnabledListener : public SGPropertyChangeListener {
466 virtual void valueChanged(SGPropertyNode* node) {
467 globals->get_renderer()->enableShadows(node->getBoolValue());
471 class ShadowNumListener : public SGPropertyChangeListener {
473 virtual void valueChanged(SGPropertyNode* node) {
474 globals->get_renderer()->updateCascadeNumber(node->getIntValue());
478 class ShadowRangeListener : public SGPropertyChangeListener {
480 virtual void valueChanged(SGPropertyNode* node) {
481 globals->get_renderer()->updateCascadeFar(node->getIndex(), node->getFloatValue());
486 FGRenderer::init( void )
488 sgUserDataInit( globals->get_props() );
490 _classicalRenderer = !fgGetBool("/sim/rendering/rembrandt/enabled", false);
491 _shadowMapSize = fgGetInt( "/sim/rendering/shadows/map-size", 4096 );
492 fgAddChangeListener( new ShadowMapSizeListener, "/sim/rendering/shadows/map-size" );
493 fgAddChangeListener( new ShadowEnabledListener, "/sim/rendering/shadows/enabled" );
494 ShadowRangeListener* srl = new ShadowRangeListener;
495 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[0]");
496 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[1]");
497 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[2]");
498 fgAddChangeListener(srl, "/sim/rendering/shadows/cascade-far-m[3]");
499 fgAddChangeListener(new ShadowNumListener, "/sim/rendering/shadows/num-cascades");
500 _numCascades = fgGetInt("/sim/rendering/shadows/num-cascades", 4);
501 _cascadeFar[0] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[0]", 5.0f);
502 _cascadeFar[1] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[1]", 50.0f);
503 _cascadeFar[2] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[2]", 500.0f);
504 _cascadeFar[3] = fgGetFloat("/sim/rendering/shadows/cascade-far-m[3]", 5000.0f);
505 updateCascadeNumber(_numCascades);
506 updateCascadeFar(0, _cascadeFar[0]);
507 updateCascadeFar(1, _cascadeFar[1]);
508 updateCascadeFar(2, _cascadeFar[2]);
509 updateCascadeFar(3, _cascadeFar[3]);
510 _useColorForDepth = fgGetBool( "/sim/rendering/rembrandt/use-color-for-depth", false );
511 _depthInColor->set( _useColorForDepth );
513 _renderer = fgGetString("/sim/rendering/rembrandt/renderer", "default-pipeline");
514 if (!_classicalRenderer)
515 _pipeline = makeRenderingPipeline(_renderer, 0);
516 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
517 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
518 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
519 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
521 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
523 _xsize = fgGetNode("/sim/startup/xsize", true);
524 _ysize = fgGetNode("/sim/startup/ysize", true);
525 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
527 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
528 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
529 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
530 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
531 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
532 _textures = fgGetNode("/sim/rendering/textures", true);
534 _altitude_ft = fgGetNode("/position/altitude-ft", true);
536 _cloud_status = fgGetNode("/environment/clouds/status", true);
537 _visibility_m = fgGetNode("/environment/visibility-m", true);
539 bool use_point_sprites = _point_sprites->getBoolValue();
540 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
541 bool distance_attenuation = _distance_attenuation->getBoolValue();
543 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
544 distance_attenuation );
546 if (const char* tc = fgGetString("/sim/rendering/texture-compression", NULL)) {
547 if (strcmp(tc, "false") == 0 || strcmp(tc, "off") == 0 ||
548 strcmp(tc, "0") == 0 || strcmp(tc, "no") == 0 ||
549 strcmp(tc, "none") == 0) {
550 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::DoNotUseCompression);
551 } else if (strcmp(tc, "arb") == 0) {
552 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseARBCompression);
553 } else if (strcmp(tc, "dxt1") == 0) {
554 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT1Compression);
555 } else if (strcmp(tc, "dxt3") == 0) {
556 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT3Compression);
557 } else if (strcmp(tc, "dxt5") == 0) {
558 SGSceneFeatures::instance()->setTextureCompression(SGSceneFeatures::UseDXT5Compression);
560 SG_LOG(SG_VIEW, SG_WARN, "Unknown texture compression setting!");
564 // create sky, but can't build until setupView, since we depend
565 // on other subsystems to be inited, eg Ephemeris
568 SGPath texture_path(globals->get_fg_root());
569 texture_path.append("Textures");
570 texture_path.append("Sky");
571 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
572 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
573 _sky->add_cloud_layer(layer);
576 _sky->texture_path( texture_path.str() );
578 if (!_classicalRenderer) {
579 eventHandler->setChangeStatsCameraRenderOrder( true );
580 _sky->set_minimum_sky_visibility( 0.0 ); // A black sky appears for below that
584 void installCullVisitor(Camera* camera)
586 osgViewer::Renderer* renderer
587 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
588 for (int i = 0; i < 2; ++i) {
589 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
590 #if SG_OSG_VERSION_LESS_THAN(3,0,0)
591 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
593 osg::ref_ptr<osgUtil::CullVisitor::Identifier> identifier;
594 identifier = sceneView->getCullVisitor()->getIdentifier();
595 sceneView->setCullVisitor(new simgear::EffectCullVisitor);
596 sceneView->getCullVisitor()->setIdentifier(identifier.get());
598 identifier = sceneView->getCullVisitorLeft()->getIdentifier();
599 sceneView->setCullVisitorLeft(sceneView->getCullVisitor()->clone());
600 sceneView->getCullVisitorLeft()->setIdentifier(identifier.get());
602 identifier = sceneView->getCullVisitorRight()->getIdentifier();
603 sceneView->setCullVisitorRight(sceneView->getCullVisitor()->clone());
604 sceneView->getCullVisitorRight()->setIdentifier(identifier.get());
610 FGRenderer::buildRenderingPipeline(CameraGroup* cgroup, unsigned flags, Camera* camera,
612 const Matrix& projection,
613 osg::GraphicsContext* gc,
614 bool useMasterSceneData)
616 CameraInfo* info = 0;
617 if (!_classicalRenderer && (flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
618 info = buildDeferredPipeline( cgroup, flags, camera, view, projection, gc );
623 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0)
624 _classicalRenderer = true;
625 return buildClassicalPipeline( cgroup, flags, camera, view, projection, useMasterSceneData );
630 FGRenderer::buildClassicalPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
631 const osg::Matrix& view,
632 const osg::Matrix& projection,
633 bool useMasterSceneData)
635 CameraInfo* info = new CameraInfo(flags);
636 // The camera group will always update the camera
637 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
639 Camera* farCamera = 0;
640 if ((flags & (CameraGroup::GUI | CameraGroup::ORTHO)) == 0) {
641 farCamera = new Camera;
642 farCamera->setAllowEventFocus(camera->getAllowEventFocus());
643 farCamera->setGraphicsContext(camera->getGraphicsContext());
644 farCamera->setCullingMode(camera->getCullingMode());
645 farCamera->setInheritanceMask(camera->getInheritanceMask());
646 farCamera->setReferenceFrame(Transform::ABSOLUTE_RF);
647 // Each camera's viewport is written when the window is
648 // resized; if the the viewport isn't copied here, it gets updated
649 // twice and ends up with the wrong value.
650 farCamera->setViewport(simgear::clone(camera->getViewport()));
651 farCamera->setDrawBuffer(camera->getDrawBuffer());
652 farCamera->setReadBuffer(camera->getReadBuffer());
653 farCamera->setRenderTargetImplementation(
654 camera->getRenderTargetImplementation());
655 const Camera::BufferAttachmentMap& bufferMap
656 = camera->getBufferAttachmentMap();
657 if (bufferMap.count(Camera::COLOR_BUFFER) != 0) {
659 Camera::COLOR_BUFFER,
660 bufferMap.find(Camera::COLOR_BUFFER)->second._texture.get());
662 cgroup->getViewer()->addSlave(farCamera, projection, view, useMasterSceneData);
663 installCullVisitor(farCamera);
664 int farSlaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
665 info->addCamera( FAR_CAMERA, farCamera, farSlaveIndex );
666 farCamera->setRenderOrder(Camera::POST_RENDER, farSlaveIndex);
667 camera->setCullMask(camera->getCullMask() & ~simgear::BACKGROUND_BIT);
668 camera->setClearMask(GL_DEPTH_BUFFER_BIT);
670 cgroup->getViewer()->addSlave(camera, projection, view, useMasterSceneData);
671 installCullVisitor(camera);
672 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
673 info->addCamera( MAIN_CAMERA, camera, slaveIndex );
674 camera->setRenderOrder(Camera::POST_RENDER, slaveIndex);
675 cgroup->addCamera(info);
679 class FGDeferredRenderingCameraCullCallback : public osg::NodeCallback {
681 FGDeferredRenderingCameraCullCallback( const std::string& k, CameraInfo* i, bool nd = false ) : kind( k ), info( i ), needsDuDv(nd) {}
682 virtual void operator()( osg::Node *n, osg::NodeVisitor *nv) {
683 simgear::EffectCullVisitor* cv = dynamic_cast<simgear::EffectCullVisitor*>(nv);
684 osg::Camera* camera = static_cast<osg::Camera*>(n);
686 cv->clearBufferList();
687 for (RenderBufferMap::iterator ii = info->buffers.begin(); ii != info->buffers.end(); ++ii) {
688 cv->addBuffer(ii->first, ii->second.texture);
691 if ( !info->getRenderStageInfo(kind).fullscreen )
692 info->setMatrices( camera );
695 osg::Matrix projInverse;
696 info->projInverse->get( projInverse );
698 osg::Vec4 p0 = osg::Vec4( -1.0, -1.0, 0.0, 1.0 ) * projInverse;
699 info->du->set( osg::Vec4( 1.0, -1.0, 0.0, 1.0 ) * projInverse - p0 );
700 info->dv->set( osg::Vec4( -1.0, 1.0, 0.0, 1.0 ) * projInverse - p0 );
703 cv->traverse( *camera );
705 if ( kind == GEOMETRY_CAMERA ) {
706 // Remove transparent bins. They will be renderer in the additional light stage (side effect)
707 osgUtil::RenderStage* renderStage = cv->getRenderStage();
708 osgUtil::RenderBin::RenderBinList& rbl = renderStage->getRenderBinList();
709 for (osgUtil::RenderBin::RenderBinList::iterator rbi = rbl.begin(); rbi != rbl.end(); ) {
710 if (rbi->second->getSortMode() == osgUtil::RenderBin::SORT_BACK_TO_FRONT) {
716 } else if ( kind == LIGHTING_CAMERA ) {
717 osg::ref_ptr<osg::Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
718 if (mainShadowCamera.valid()) {
719 osg::Switch* grp = mainShadowCamera->getChild(0)->asSwitch();
720 for (int i = 0; i < 4; ++i ) {
721 if (!grp->getValue(i))
724 osg::Camera* cascadeCam = static_cast<osg::Camera*>( grp->getChild(i) );
725 osg::Matrixf shadowMatrix = camera->getInverseViewMatrix() *
726 cascadeCam->getViewMatrix() *
727 cascadeCam->getProjectionMatrix() *
728 osg::Matrix::translate(1.0, 1.0, 1.0) *
729 osg::Matrix::scale(0.5f, 0.5f, 0.5f);
731 info->shadowMatrix[i]->set( shadowMatrix );
743 osg::Texture2D* buildDeferredBuffer(GLint internalFormat, GLenum sourceFormat, GLenum sourceType, GLenum wrapMode, bool shadowComparison = false)
745 osg::Texture2D* tex = new osg::Texture2D;
746 tex->setResizeNonPowerOfTwoHint( false );
747 tex->setInternalFormat( internalFormat );
748 tex->setShadowComparison(shadowComparison);
749 if (shadowComparison) {
750 tex->setShadowTextureMode(osg::Texture2D::LUMINANCE);
751 tex->setBorderColor(osg::Vec4(1.0f,1.0f,1.0f,1.0f));
753 tex->setSourceFormat(sourceFormat);
754 tex->setSourceType(sourceType);
755 tex->setFilter( osg::Texture2D::MIN_FILTER, osg::Texture2D::LINEAR );
756 tex->setFilter( osg::Texture2D::MAG_FILTER, osg::Texture2D::LINEAR );
757 tex->setWrap( osg::Texture::WRAP_S, (osg::Texture::WrapMode)wrapMode );
758 tex->setWrap( osg::Texture::WRAP_T, (osg::Texture::WrapMode)wrapMode );
762 void attachBufferToCamera( CameraInfo* info, osg::Camera* camera, osg::Camera::BufferComponent c, const std::string& ck, const std::string& bk )
764 camera->attach( c, info->getBuffer(bk) );
765 info->getRenderStageInfo(ck).buffers.insert( std::make_pair( c, bk ) );
768 void buildAttachments(CameraInfo* info, osg::Camera* camera, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments) {
769 BOOST_FOREACH(ref_ptr<FGRenderingPipeline::Attachment> attachment, attachments) {
770 if (attachment->valid())
771 attachBufferToCamera( info, camera, attachment->component, name, attachment->buffer );
775 osg::Camera* FGRenderer::buildDeferredGeometryCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
777 osg::Camera* camera = new osg::Camera;
778 info->addCamera(name, camera );
780 camera->setCullMask( ~simgear::MODELLIGHT_BIT );
781 camera->setName( "GeometryC" );
782 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
783 camera->setGraphicsContext( gc );
784 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( name, info ) );
785 camera->setClearMask( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
786 camera->setClearColor( osg::Vec4( 0., 0., 0., 0. ) );
787 camera->setClearDepth( 1.0 );
788 camera->setColorMask(true, true, true, true);
789 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
790 camera->setRenderOrder(osg::Camera::NESTED_RENDER, 0);
791 camera->setViewport( new osg::Viewport );
792 buildAttachments(info, camera, name, attachments);
793 camera->setDrawBuffer(GL_FRONT);
794 camera->setReadBuffer(GL_FRONT);
796 osg::StateSet* ss = camera->getOrCreateStateSet();
797 ss->addUniform( _depthInColor );
799 camera->addChild( mDeferredRealRoot.get() );
804 static void setShadowCascadeStateSet( osg::Camera* cam ) {
805 osg::StateSet* ss = cam->getOrCreateStateSet();
806 ss->setAttribute( new osg::PolygonOffset( 1.1f, 5.0f ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
807 ss->setMode( GL_POLYGON_OFFSET_FILL, osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
808 ss->setRenderBinDetails( 0, "RenderBin", osg::StateSet::OVERRIDE_RENDERBIN_DETAILS );
809 ss->setAttributeAndModes( new osg::AlphaFunc( osg::AlphaFunc::GREATER, 0.05 ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
810 ss->setAttributeAndModes( new osg::ColorMask( false, false, false, false ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
811 ss->setAttributeAndModes( new osg::CullFace( osg::CullFace::FRONT ), osg::StateAttribute::ON | osg::StateAttribute::OVERRIDE );
812 osg::Program* program = new osg::Program;
813 ss->setAttribute( program, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
814 ss->setMode( GL_LIGHTING, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
815 ss->setMode( GL_BLEND, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
816 //ss->setTextureMode( 0, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
817 ss->setTextureMode( 0, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
818 ss->setTextureMode( 1, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
819 ss->setTextureMode( 1, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
820 ss->setTextureMode( 2, GL_TEXTURE_2D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
821 ss->setTextureMode( 2, GL_TEXTURE_3D, osg::StateAttribute::OVERRIDE | osg::StateAttribute::OFF );
824 static osg::Camera* createShadowCascadeCamera( int no, int cascadeSize ) {
825 osg::Camera* cascadeCam = new osg::Camera;
826 setShadowCascadeStateSet( cascadeCam );
828 std::ostringstream oss;
829 oss << "CascadeCamera" << (no + 1);
830 cascadeCam->setName( oss.str() );
831 cascadeCam->setClearMask(0);
832 cascadeCam->setCullMask( simgear::CASTSHADOW_BIT );
833 cascadeCam->setCullingMode( cascadeCam->getCullingMode() | osg::CullSettings::SMALL_FEATURE_CULLING );
834 cascadeCam->setAllowEventFocus(false);
835 cascadeCam->setReferenceFrame(osg::Transform::ABSOLUTE_RF_INHERIT_VIEWPOINT);
836 cascadeCam->setRenderOrder(osg::Camera::NESTED_RENDER);
837 cascadeCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
838 cascadeCam->setViewport( int( no / 2 ) * cascadeSize, (no & 1) * cascadeSize, cascadeSize, cascadeSize );
842 osg::Camera* FGRenderer::buildDeferredShadowCamera( CameraInfo* info, osg::GraphicsContext* gc, const std::string& name, const std::vector<ref_ptr<FGRenderingPipeline::Attachment> > &attachments )
844 osg::Camera* mainShadowCamera = new osg::Camera;
845 info->addCamera(name, mainShadowCamera, 0.0f );
847 mainShadowCamera->setName( "ShadowC" );
848 mainShadowCamera->setClearMask( GL_DEPTH_BUFFER_BIT );
849 mainShadowCamera->setClearDepth( 1.0 );
850 mainShadowCamera->setAllowEventFocus(false);
851 mainShadowCamera->setGraphicsContext(gc);
852 mainShadowCamera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
853 buildAttachments(info, mainShadowCamera, name, attachments);
854 mainShadowCamera->setComputeNearFarMode(osg::Camera::DO_NOT_COMPUTE_NEAR_FAR);
855 mainShadowCamera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
856 mainShadowCamera->setProjectionMatrix(osg::Matrix::identity());
857 mainShadowCamera->setCullingMode( osg::CullSettings::NO_CULLING );
858 mainShadowCamera->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
859 mainShadowCamera->setDrawBuffer(GL_FRONT);
860 mainShadowCamera->setReadBuffer(GL_FRONT);
861 mainShadowCamera->setRenderOrder(Camera::NESTED_RENDER, 1);
863 osg::Switch* shadowSwitch = new osg::Switch;
864 mainShadowCamera->addChild( shadowSwitch );
866 for (int i = 0; i < 4; ++i ) {
867 osg::Camera* cascadeCam = createShadowCascadeCamera( i, _shadowMapSize/2 );
868 cascadeCam->addChild( mDeferredRealRoot.get() );
869 shadowSwitch->addChild( cascadeCam );
871 if (fgGetBool("/sim/rendering/shadows/enabled", true))
872 shadowSwitch->setAllChildrenOn();
874 shadowSwitch->setAllChildrenOff();
876 return mainShadowCamera;
879 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)
881 osg::Camera* cascade = static_cast<osg::Camera*>( grp->getChild(idx) );
882 osg::Matrixd &viewMatrix = cascade->getViewMatrix();
883 osg::Matrixd &projectionMatrix = cascade->getProjectionMatrix();
885 osg::BoundingSphere bs;
886 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f1);
887 bs.expandBy(osg::Vec3(right,top,-zNear) * f2);
888 bs.expandBy(osg::Vec3(left,bottom,-zNear) * f2);
889 bs.expandBy(osg::Vec3(right,top,-zNear) * f1);
891 osg::Vec4 aim = osg::Vec4(bs.center(), 1.0) * camera->getInverseViewMatrix();
893 projectionMatrix.makeOrtho( -bs.radius(), bs.radius(), -bs.radius(), bs.radius(), 1., 15000.0 );
894 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
895 viewMatrix.makeLookAt( position + (getSunDirection() * 10000.0), position, position );
898 osg::Vec3 FGRenderer::getSunDirection() const
901 _sunDirection->get( val );
905 void FGRenderer::updateShadowCamera(const CameraInfo* info, const osg::Vec3d& position)
907 ref_ptr<Camera> mainShadowCamera = info->getCamera( SHADOW_CAMERA );
908 if (mainShadowCamera.valid()) {
909 ref_ptr<Switch> shadowSwitch = mainShadowCamera->getChild( 0 )->asSwitch();
910 osg::Vec3d up = position,
911 dir = getSunDirection();
914 // cos(100 deg) == -0.17
915 if (up * dir < -0.17 || !fgGetBool("/sim/rendering/shadows/enabled", true)) {
916 shadowSwitch->setAllChildrenOff();
918 double left,right,bottom,top,zNear,zFar;
919 ref_ptr<Camera> camera = info->getCamera(GEOMETRY_CAMERA);
920 camera->getProjectionMatrix().getFrustum(left,right,bottom,top,zNear,zFar);
922 shadowSwitch->setAllChildrenOn();
923 if (_numCascades == 1) {
924 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(0) );
925 cascadeCam->setViewport( 0, 0, _shadowMapSize, _shadowMapSize );
927 for (int no = 0; no < 4; ++no) {
928 osg::Camera* cascadeCam = static_cast<osg::Camera*>( shadowSwitch->getChild(no) );
929 cascadeCam->setViewport( int( no / 2 ) * (_shadowMapSize/2), (no & 1) * (_shadowMapSize/2), (_shadowMapSize/2), (_shadowMapSize/2) );
932 updateShadowCascade(info, camera, shadowSwitch, 0, left, right, bottom, top, zNear, 1.0, _cascadeFar[0]/zNear);
933 if (_numCascades > 1) {
934 shadowSwitch->setValue(1, true);
935 updateShadowCascade(info, camera, shadowSwitch, 1, left, right, bottom, top, zNear, _cascadeFar[0]/zNear, _cascadeFar[1]/zNear);
937 shadowSwitch->setValue(1, false);
939 if (_numCascades > 2) {
940 shadowSwitch->setValue(2, true);
941 updateShadowCascade(info, camera, shadowSwitch, 2, left, right, bottom, top, zNear, _cascadeFar[1]/zNear, _cascadeFar[2]/zNear);
943 shadowSwitch->setValue(2, false);
945 if (_numCascades > 3) {
946 shadowSwitch->setValue(3, true);
947 updateShadowCascade(info, camera, shadowSwitch, 3, left, right, bottom, top, zNear, _cascadeFar[2]/zNear, _cascadeFar[3]/zNear);
949 shadowSwitch->setValue(3, false);
952 osg::Matrixd &viewMatrix = mainShadowCamera->getViewMatrix();
954 osg::Vec4 aim = osg::Vec4( 0.0, 0.0, 0.0, 1.0 ) * camera->getInverseViewMatrix();
956 osg::Vec3 position( aim.x(), aim.y(), aim.z() );
957 viewMatrix.makeLookAt( position, position + (getSunDirection() * 10000.0), position );
963 void FGRenderer::updateShadowMapSize(int mapSize)
965 if ( ((~( mapSize-1 )) & mapSize) != mapSize ) {
966 SG_LOG( SG_VIEW, SG_ALERT, "Map size is not a power of two" );
969 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
970 ii != CameraGroup::getDefault()->camerasEnd();
973 CameraInfo* info = ii->get();
974 Camera* camera = info->getCamera(SHADOW_CAMERA);
975 if (camera == 0) continue;
977 Texture2D* tex = info->getBuffer("shadow");
978 if (tex == 0) continue;
980 tex->setTextureSize( mapSize, mapSize );
981 tex->dirtyTextureObject();
983 Viewport* vp = camera->getViewport();
984 vp->width() = mapSize;
985 vp->height() = mapSize;
987 osgViewer::Renderer* renderer
988 = static_cast<osgViewer::Renderer*>(camera->getRenderer());
989 for (int i = 0; i < 2; ++i) {
990 osgUtil::SceneView* sceneView = renderer->getSceneView(i);
991 sceneView->getRenderStage()->setFrameBufferObject(0);
992 sceneView->getRenderStage()->setCameraRequiresSetUp(true);
993 if (sceneView->getRenderStageLeft()) {
994 sceneView->getRenderStageLeft()->setFrameBufferObject(0);
995 sceneView->getRenderStageLeft()->setCameraRequiresSetUp(true);
997 if (sceneView->getRenderStageRight()) {
998 sceneView->getRenderStageRight()->setFrameBufferObject(0);
999 sceneView->getRenderStageRight()->setCameraRequiresSetUp(true);
1003 int cascadeSize = mapSize / 2;
1004 Group* grp = camera->getChild(0)->asGroup();
1005 for (int i = 0; i < 4; ++i ) {
1006 Camera* cascadeCam = static_cast<Camera*>( grp->getChild(i) );
1007 cascadeCam->setViewport( int( i / 2 ) * cascadeSize, (i & 1) * cascadeSize, cascadeSize, cascadeSize );
1010 _shadowMapSize = mapSize;
1014 void FGRenderer::enableShadows(bool enabled)
1016 for ( CameraGroup::CameraIterator ii = CameraGroup::getDefault()->camerasBegin();
1017 ii != CameraGroup::getDefault()->camerasEnd();
1020 CameraInfo* info = ii->get();
1021 Camera* camera = info->getCamera(SHADOW_CAMERA);
1022 if (camera == 0) continue;
1024 osg::Switch* shadowSwitch = camera->getChild(0)->asSwitch();
1026 shadowSwitch->setAllChildrenOn();
1028 shadowSwitch->setAllChildrenOff();
1032 void FGRenderer::updateCascadeFar(int index, float far_m)
1034 if (index < 0 || index > 3)
1036 _cascadeFar[index] = far_m;
1037 _shadowDistances->set( osg::Vec4f(_cascadeFar[0], _cascadeFar[1], _cascadeFar[2], _cascadeFar[3]) );
1040 void FGRenderer::updateCascadeNumber(size_t num)
1042 if (num < 1 || num > 4)
1045 _shadowNumber->set( (int)_numCascades );
1048 class DebugPassListener : public SGPropertyChangeListener {
1050 DebugPassListener(osg::Switch* sw, int i) : _switch(sw), _index(i) {}
1051 virtual void valueChanged(SGPropertyNode* node) {
1052 _switch->setValue(_index, node->getBoolValue());
1056 osg::ref_ptr<osg::Switch> _switch;
1061 FGRenderer::buildDeferredLightingCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1063 osg::Camera* camera = new osg::Camera;
1064 info->addCamera(stage->name, camera );
1066 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1067 camera->setAllowEventFocus(false);
1068 camera->setGraphicsContext(gc);
1069 camera->setViewport(new Viewport);
1070 camera->setName(stage->name+"C");
1071 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1072 camera->setRenderOrder(osg::Camera::NESTED_RENDER, stage->orderNum);
1073 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1074 camera->setViewport( new osg::Viewport );
1075 buildAttachments(info, camera, stage->name, stage->attachments);
1076 camera->setDrawBuffer(GL_FRONT);
1077 camera->setReadBuffer(GL_FRONT);
1078 camera->setClearColor( osg::Vec4( 0.5, 0.5, 0.5, 1. ) );
1079 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1080 osg::StateSet* ss = camera->getOrCreateStateSet();
1081 ss->setAttribute( new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false) );
1082 ss->addUniform( _depthInColor );
1084 osg::Switch* lightingGroup = new osg::Switch;
1086 BOOST_FOREACH( osg::ref_ptr<FGRenderingPipeline::Pass> pass, stage->passes ) {
1087 ref_ptr<Node> node = buildPass(info, pass);
1089 lightingGroup->addChild(node);
1090 if (!pass->debugProperty.empty()) {
1091 lightingGroup->setValue(lightingGroup->getNumChildren()-1, fgGetBool(pass->debugProperty));
1092 fgAddChangeListener(new DebugPassListener(lightingGroup, lightingGroup->getNumChildren()-1), pass->debugProperty);
1097 camera->addChild( lightingGroup );
1103 FGRenderer::buildDeferredPipeline(CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1104 const osg::Matrix& view,
1105 const osg::Matrix& projection,
1106 osg::GraphicsContext* gc)
1108 return buildCameraFromRenderingPipeline(_pipeline, cgroup, flags, camera, view, projection, gc);
1112 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, const FGRenderingPipeline::Pass* pass )
1114 osg::Camera* camera = new osg::Camera;
1116 camera->setClearMask( 0 );
1117 camera->setAllowEventFocus(false);
1118 camera->setName(pass->name+"C");
1119 camera->setReferenceFrame(osg::Transform::ABSOLUTE_RF);
1120 camera->setRenderOrder(osg::Camera::NESTED_RENDER, pass->orderNum);
1121 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1122 camera->setViewMatrix(osg::Matrix::identity());
1123 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1125 osg::StateSet* ss = camera->getOrCreateStateSet();
1126 ss->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1127 ss->addUniform( info->projInverse );
1128 ss->addUniform( info->viewInverse );
1129 ss->addUniform( info->view );
1130 ss->addUniform( info->bufferSize );
1131 ss->addUniform( info->worldPosCart );
1132 ss->addUniform( info->worldPosGeod );
1133 ss->addUniform( info->shadowMatrix[0] );
1134 ss->addUniform( info->shadowMatrix[1] );
1135 ss->addUniform( info->shadowMatrix[2] );
1136 ss->addUniform( info->shadowMatrix[3] );
1137 ss->addUniform( _ambientFactor );
1138 ss->addUniform( _sunDiffuse );
1139 ss->addUniform( _sunSpecular );
1140 ss->addUniform( _sunDirection );
1141 ss->addUniform( _planes );
1142 ss->addUniform( _shadowNumber );
1143 ss->addUniform( _shadowDistances );
1144 ss->addUniform( _fogColor );
1145 ss->addUniform( _fogDensity );
1147 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1148 g->setUseDisplayList(false);
1149 simgear::EffectGeode* eg = new simgear::EffectGeode;
1150 simgear::Effect* effect = simgear::makeEffect(pass->effect, true);
1152 eg->setEffect( effect );
1155 eg->setName(pass->name+"Quad");
1156 eg->setCullingActive(false);
1158 camera->addChild(eg);
1164 FGRenderer::buildDeferredFullscreenCamera( flightgear::CameraInfo* info, osg::GraphicsContext* gc, const FGRenderingPipeline::Stage* stage )
1166 osg::Camera* camera = buildDeferredFullscreenCamera(info, static_cast<const FGRenderingPipeline::Pass*>(stage));
1167 info->addCamera(stage->name, camera, stage->scaleFactor, true);
1169 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback(stage->name, info, stage->needsDuDv) );
1170 camera->setGraphicsContext(gc);
1171 camera->setViewport(new Viewport);
1172 camera->setRenderTargetImplementation( osg::Camera::FRAME_BUFFER_OBJECT );
1173 buildAttachments(info, camera, stage->name, stage->attachments);
1174 camera->setDrawBuffer(GL_FRONT);
1175 camera->setReadBuffer(GL_FRONT);
1176 camera->setClearColor( osg::Vec4( 1., 1., 1., 1. ) );
1177 camera->setClearMask( GL_COLOR_BUFFER_BIT );
1178 camera->setViewMatrix(osg::Matrix::identity());
1179 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1181 osg::StateSet* ss = camera->getOrCreateStateSet();
1182 if (stage->needsDuDv) {
1183 ss->addUniform( info->du );
1184 ss->addUniform( info->dv );
1191 FGRenderer::buildDeferredDisplayCamera( osg::Camera* camera, flightgear::CameraInfo* info, const FGRenderingPipeline::Stage* stage, osg::GraphicsContext* gc )
1193 camera->setName( "DisplayC" );
1194 camera->setCullCallback( new FGDeferredRenderingCameraCullCallback( stage->name, info ) );
1195 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
1196 camera->setAllowEventFocus(false);
1197 osg::Geometry* g = osg::createTexturedQuadGeometry( osg::Vec3(-1.,-1.,0.), osg::Vec3(2.,0.,0.), osg::Vec3(0.,2.,0.) );
1198 g->setUseDisplayList(false); //DEBUG
1199 simgear::EffectGeode* eg = new simgear::EffectGeode;
1200 simgear::Effect* effect = simgear::makeEffect(stage->effect, true);
1202 SG_LOG(SG_VIEW, SG_ALERT, stage->effect + " not found");
1205 eg->setEffect(effect);
1206 eg->setCullingActive(false);
1208 camera->setViewMatrix(osg::Matrix::identity());
1209 camera->setProjectionMatrixAsOrtho2D(-1,1,-1,1);
1210 camera->addChild(eg);
1212 osg::StateSet* ss = camera->getOrCreateStateSet();
1213 ss->addUniform( _depthInColor );
1214 ss->addUniform( info->projInverse );
1215 ss->addUniform( info->viewInverse );
1216 ss->addUniform( info->view );
1217 ss->addUniform( info->bufferSize );
1218 ss->addUniform( info->worldPosCart );
1219 ss->addUniform( info->worldPosGeod );
1220 ss->addUniform( info->shadowMatrix[0] );
1221 ss->addUniform( info->shadowMatrix[1] );
1222 ss->addUniform( info->shadowMatrix[2] );
1223 ss->addUniform( info->shadowMatrix[3] );
1224 ss->addUniform( _ambientFactor );
1225 ss->addUniform( _sunDiffuse );
1226 ss->addUniform( _sunSpecular );
1227 ss->addUniform( _sunDirection );
1228 ss->addUniform( _planes );
1229 ss->addUniform( _shadowNumber );
1230 ss->addUniform( _shadowDistances );
1231 ss->addUniform( _fogColor );
1232 ss->addUniform( _fogDensity );
1236 FGRenderer::buildStage(CameraInfo* info,
1237 FGRenderingPipeline::Stage* stage,
1238 CameraGroup* cgroup,
1239 osg::Camera* mainCamera,
1240 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1242 if (!stage->valid())
1245 ref_ptr<Camera> camera;
1246 bool needOffsets = false;
1247 if (stage->type == "geometry") {
1248 camera = buildDeferredGeometryCamera(info, gc, stage->name, stage->attachments);
1250 } else if (stage->type == "lighting") {
1251 camera = buildDeferredLightingCamera(info, gc, stage);
1253 } else if (stage->type == "shadow")
1254 camera = buildDeferredShadowCamera(info, gc, stage->name, stage->attachments);
1255 else if (stage->type == "fullscreen")
1256 camera = buildDeferredFullscreenCamera(info, gc, stage);
1257 else if (stage->type == "display") {
1258 camera = mainCamera;
1259 buildDeferredDisplayCamera(camera, info, stage, gc);
1261 throw sg_exception("Stage type is not supported");
1264 cgroup->getViewer()->addSlave(camera, projection, view, false);
1266 cgroup->getViewer()->addSlave(camera, false);
1267 installCullVisitor(camera);
1268 int slaveIndex = cgroup->getViewer()->getNumSlaves() - 1;
1269 if (stage->type == "display")
1270 info->addCamera( stage->type, camera, slaveIndex, true );
1271 info->getRenderStageInfo(stage->name).slaveIndex = slaveIndex;
1275 FGRenderer::buildLightingSkyCloudsPass(FGRenderingPipeline::Pass* pass)
1277 Group* group = new Group;
1278 StateSet* ss = group->getOrCreateStateSet();
1279 ss->setAttributeAndModes( new osg::ColorMask( true, true, true, false ), osg::StateAttribute::ON );
1280 group->addChild( _sky->getPreRoot() );
1281 group->addChild( _sky->getCloudRoot() );
1286 FGRenderer::buildLightingLightsPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1288 osg::Camera* lightCam = new osg::Camera;
1289 StateSet* ss = lightCam->getOrCreateStateSet();
1290 ss->addUniform( _planes );
1291 ss->addUniform( info->bufferSize );
1292 ss->addUniform( _fogColor );
1293 ss->addUniform( _fogDensity );
1294 lightCam->setName( "LightCamera" );
1295 lightCam->setClearMask(0);
1296 lightCam->setAllowEventFocus(false);
1297 lightCam->setReferenceFrame(osg::Transform::RELATIVE_RF);
1298 lightCam->setRenderOrder(osg::Camera::NESTED_RENDER,pass->orderNum);
1299 lightCam->setViewMatrix(osg::Matrix::identity());
1300 lightCam->setProjectionMatrix(osg::Matrix::identity());
1301 lightCam->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1302 lightCam->setCullMask( simgear::MODELLIGHT_BIT | simgear::PANEL2D_BIT | simgear::PERMANENTLIGHT_BIT);
1303 lightCam->setInheritanceMask( osg::CullSettings::ALL_VARIABLES & ~osg::CullSettings::CULL_MASK );
1304 lightCam->addChild( mDeferredRealRoot.get() );
1310 FGRenderer::buildPass(CameraInfo* info, FGRenderingPipeline::Pass* pass)
1316 if (pass->type == "sky-clouds")
1317 node = buildLightingSkyCloudsPass(pass);
1318 else if (pass->type == "fullscreen")
1319 node = buildDeferredFullscreenCamera(info, pass);
1320 else if (pass->type == "lights")
1321 node = buildLightingLightsPass(info, pass);
1323 throw sg_exception("Pass type is not supported");
1325 return node.release();
1329 FGRenderer::buildBuffers(FGRenderingPipeline* rpipe, CameraInfo* info)
1331 for (size_t i = 0; i < rpipe->buffers.size(); ++i) {
1332 osg::ref_ptr<FGRenderingPipeline::Buffer> buffer = rpipe->buffers[i];
1333 if (buffer->valid()) {
1334 bool fullscreen = buffer->width == -1 && buffer->height == -1;
1335 info->addBuffer(buffer->name, buildDeferredBuffer( buffer->internalFormat,
1336 buffer->sourceFormat,
1339 buffer->shadowComparison),
1340 fullscreen ? buffer->scaleFactor : 0.0f);
1342 info->getBuffer(buffer->name)->setTextureSize(buffer->width, buffer->height);
1348 CameraInfo* FGRenderer::buildCameraFromRenderingPipeline(FGRenderingPipeline* rpipe, CameraGroup* cgroup, unsigned flags, osg::Camera* camera,
1349 const osg::Matrix& view, const osg::Matrix& projection, osg::GraphicsContext* gc)
1351 CameraInfo* info = new CameraInfo(flags);
1352 buildBuffers(rpipe, info);
1354 for (size_t i = 0; i < rpipe->stages.size(); ++i) {
1355 osg::ref_ptr<FGRenderingPipeline::Stage> stage = rpipe->stages[i];
1356 buildStage(info, stage, cgroup, camera, view, projection, gc);
1359 cgroup->addCamera(info);
1365 FGRenderer::setupView( void )
1367 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1368 osg::initNotifyLevel();
1370 // The number of polygon-offset "units" to place between layers. In
1371 // principle, one is supposed to be enough. In practice, I find that
1372 // my hardware/driver requires many more.
1373 osg::PolygonOffset::setUnitsMultiplier(1);
1374 osg::PolygonOffset::setFactorMultiplier(1);
1376 // Go full screen if requested ...
1377 if ( fgGetBool("/sim/startup/fullscreen") )
1381 // The sun and moon diameters are scaled down numbers of the
1382 // actual diameters. This was needed to fit both the sun and the
1383 // moon within the distance to the far clip plane.
1384 // Moon diameter: 3,476 kilometers
1385 // Sun diameter: 1,390,000 kilometers
1386 _sky->build( 80000.0, 80000.0,
1388 *globals->get_ephem(),
1389 fgGetNode("/environment", true));
1392 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1394 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
1396 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
1398 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
1399 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
1401 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
1402 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
1403 stateSet->setAttribute(new osg::BlendFunc);
1404 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
1406 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
1408 // this will be set below
1409 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
1411 osg::Material* material = new osg::Material;
1412 stateSet->setAttribute(material);
1414 stateSet->setTextureAttribute(0, new osg::TexEnv);
1415 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
1417 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
1418 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
1419 stateSet->setAttribute(hint);
1420 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
1421 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
1422 stateSet->setAttribute(hint);
1423 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
1424 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
1425 stateSet->setAttribute(hint);
1426 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
1427 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
1428 stateSet->setAttribute(hint);
1429 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
1430 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
1431 stateSet->setAttribute(hint);
1433 osg::Group* sceneGroup = new osg::Group;
1434 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
1435 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
1437 //sceneGroup->addChild(thesky->getCloudRoot());
1439 stateSet = sceneGroup->getOrCreateStateSet();
1440 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1442 // need to update the light on every frame
1443 // OSG LightSource objects are rather confusing. OSG only supports
1444 // the 10 lights specified by OpenGL itself; if more than one
1445 // LightSource in the scene graph have the same light number, it's
1446 // indeterminate which values will be used to render geometry that
1447 // has that light number enabled. Also, adding children to a
1448 // LightSource is just a shortcut for setting up a state set that
1449 // has the corresponding OpenGL light enabled: a LightSource will
1450 // affect geometry anywhere in the scene graph that has its light
1451 // number enabled in a state set.
1452 LightSource* lightSource = new LightSource;
1453 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
1454 // relative because of CameraView being just a clever transform node
1455 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1456 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
1457 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
1458 mRealRoot->addChild(lightSource);
1459 // we need a white diffuse light for the phase of the moon
1460 osg::LightSource* sunLight = new osg::LightSource;
1461 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
1462 sunLight->getLight()->setLightNum(1);
1463 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
1464 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
1465 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
1467 // Hang a StateSet above the sky subgraph in order to turn off
1469 Group* skyGroup = new Group;
1470 StateSet* skySS = skyGroup->getOrCreateStateSet();
1471 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
1472 skyGroup->addChild(_sky->getPreRoot());
1473 sunLight->addChild(skyGroup);
1474 mRoot->addChild(sceneGroup);
1475 if ( _classicalRenderer )
1476 mRoot->addChild(sunLight);
1478 // Clouds are added to the scene graph later
1479 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
1480 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
1481 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
1482 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
1484 // enable disable specular highlights.
1485 // is the place where we might plug in an other fragment shader ...
1486 osg::LightModel* lightModel = new osg::LightModel;
1487 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
1488 stateSet->setAttribute(lightModel);
1490 // switch to enable wireframe
1491 osg::PolygonMode* polygonMode = new osg::PolygonMode;
1492 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
1493 stateSet->setAttributeAndModes(polygonMode);
1495 // scene fog handling
1496 osg::Fog* fog = new osg::Fog;
1497 fog->setUpdateCallback(new FGFogUpdateCallback);
1498 stateSet->setAttributeAndModes(fog);
1499 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
1502 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
1505 osg::Geode* geode = new osg::Geode;
1506 geode->addDrawable(new SGPuDrawable);
1507 geode->addDrawable(new SGHUDDrawable);
1508 guiCamera->addChild(geode);
1511 guiCamera->addChild(FGPanelNode::create2DPanelNode());
1514 osg::Switch* sw = new osg::Switch;
1515 sw->setUpdateCallback(new FGScenerySwitchCallback);
1516 sw->addChild(mRoot.get());
1517 mRealRoot->addChild(sw);
1518 // The clouds are attached directly to the scene graph root
1519 // because, in theory, they don't want the same default state set
1520 // as the rest of the scene. This may not be true in practice.
1521 if ( _classicalRenderer ) {
1522 mRealRoot->addChild(_sky->getCloudRoot());
1523 mRealRoot->addChild(FGCreateRedoutNode());
1525 // Attach empty program to the scene root so that shader programs
1526 // don't leak into state sets (effects) that shouldn't have one.
1527 stateSet = mRealRoot->getOrCreateStateSet();
1528 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
1530 mDeferredRealRoot->addChild( mRealRoot.get() );
1532 DeletionManager::install(mRealRoot.get());
1535 // Update all Visuals (redraws anything graphics related)
1537 FGRenderer::update( ) {
1538 if (!(_scenery_loaded->getBoolValue() ||
1539 _scenery_override->getBoolValue()))
1541 _splash_alpha->setDoubleValue(1.0);
1544 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1546 if (_splash_alpha->getDoubleValue()>0.0)
1548 // Fade out the splash screen
1549 const double fade_time = 0.5;
1550 const double fade_steps_per_sec = 10;
1551 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
1552 (SGTimeStamp::now() - _splash_time).toSecs());
1553 _splash_time = SGTimeStamp::now();
1554 double sAlpha = _splash_alpha->getDoubleValue();
1555 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
1556 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
1557 _splash_alpha->setDoubleValue((sAlpha < 0) ? 0.0 : sAlpha);
1560 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
1561 if (!_classicalRenderer ) {
1562 _ambientFactor->set( toOsg(l->scene_ambient()) );
1563 _sunDiffuse->set( toOsg(l->scene_diffuse()) );
1564 _sunSpecular->set( toOsg(l->scene_specular()) );
1565 _sunDirection->set( osg::Vec3f(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]) );
1568 // update fog params
1569 double actual_visibility;
1570 if (_cloud_status->getBoolValue()) {
1571 actual_visibility = _sky->get_visibility();
1573 actual_visibility = _visibility_m->getDoubleValue();
1576 // idle_state is now 1000 meaning we've finished all our
1577 // initializations and are running the main loop, so this will
1578 // now work without seg faulting the system.
1580 FGViewer *current__view = globals->get_current_view();
1581 // Force update of center dependent values ...
1582 current__view->set_dirty();
1584 osg::Camera *camera = viewer->getCamera();
1586 bool skyblend = _skyblend->getBoolValue();
1589 if ( _textures->getBoolValue() ) {
1590 SGVec4f clearColor(l->adj_fog_color());
1591 camera->setClearColor(toOsg(clearColor));
1594 SGVec4f clearColor(l->sky_color());
1595 camera->setClearColor(toOsg(clearColor));
1598 // update fog params if visibility has changed
1599 double visibility_meters = _visibility_m->getDoubleValue();
1600 _sky->set_visibility(visibility_meters);
1602 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
1603 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
1605 // update the sky dome
1608 // The sun and moon distances are scaled down versions
1609 // of the actual distance to get both the moon and the sun
1610 // within the range of the far clip plane.
1611 // Moon distance: 384,467 kilometers
1612 // Sun distance: 150,000,000 kilometers
1614 double sun_horiz_eff, moon_horiz_eff;
1615 if (_horizon_effect->getBoolValue()) {
1617 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
1621 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
1625 sun_horiz_eff = moon_horiz_eff = 1.0;
1629 sstate.pos = current__view->getViewPosition();
1630 sstate.pos_geod = current__view->getPosition();
1631 sstate.ori = current__view->getViewOrientation();
1632 sstate.spin = l->get_sun_rotation();
1633 sstate.gst = globals->get_time_params()->getGst();
1634 sstate.sun_dist = 50000.0 * sun_horiz_eff;
1635 sstate.moon_dist = 40000.0 * moon_horiz_eff;
1636 sstate.sun_angle = l->get_sun_angle();
1639 scolor.sky_color = SGVec3f(l->sky_color().data());
1640 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
1641 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
1642 scolor.cloud_color = SGVec3f(l->cloud_color().data());
1643 scolor.sun_angle = l->get_sun_angle();
1644 scolor.moon_angle = l->get_moon_angle();
1646 double delta_time_sec = _sim_delta_sec->getDoubleValue();
1647 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
1648 _sky->repaint( scolor, *globals->get_ephem() );
1651 // shadows->setupShadows(
1652 // current__view->getLongitude_deg(),
1653 // current__view->getLatitude_deg(),
1654 // globals->get_time_params()->getGst(),
1655 // globals->get_ephem()->getSunRightAscension(),
1656 // globals->get_ephem()->getSunDeclination(),
1657 // l->get_sun_angle());
1661 // sgEnviro.setLight(l->adj_fog_color());
1662 // sgEnviro.startOfFrame(current__view->get_view_pos(),
1663 // current__view->get_world_up(),
1664 // current__view->getLongitude_deg(),
1665 // current__view->getLatitude_deg(),
1666 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
1670 // sgEnviro.drawLightning();
1672 // double current_view_origin_airspeed_horiz_kt =
1673 // fgGetDouble("/velocities/airspeed-kt", 0.0)
1674 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
1675 // * SGD_DEGREES_TO_RADIANS);
1678 // if( is_internal )
1679 // shadows->endOfFrame();
1681 // need to call the update visitor once
1682 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
1683 mUpdateVisitor->setViewData(current__view->getViewPosition(),
1684 current__view->getViewOrientation());
1685 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
1686 mUpdateVisitor->setLight(direction, l->scene_ambient(),
1687 l->scene_diffuse(), l->scene_specular(),
1689 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
1690 mUpdateVisitor->setVisibility(actual_visibility);
1691 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
1692 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
1693 cullMask |= simgear::GroundLightManager::instance()
1694 ->getLightNodeMask(mUpdateVisitor.get());
1695 if (_panel_hotspots->getBoolValue())
1696 cullMask |= simgear::PICK_BIT;
1697 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
1698 if ( !_classicalRenderer ) {
1699 _fogColor->set( toOsg( l->adj_fog_color() ) );
1700 _fogDensity->set( float( mUpdateVisitor->getFogExp2Density() ) );
1705 FGRenderer::resize( int width, int height )
1707 int curWidth = _xsize->getIntValue(),
1708 curHeight = _ysize->getIntValue();
1709 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
1710 if ((curHeight != height) || (curWidth != width)) {
1711 // must guard setting these, or PLIB-PUI fails with too many live interfaces
1712 _xsize->setIntValue(width);
1713 _ysize->setIntValue(height);
1718 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
1719 const osgGA::GUIEventAdapter* ea)
1721 // wipe out the return ...
1723 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1724 Intersections intersections;
1726 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
1728 for (Intersections::iterator hit = intersections.begin(),
1729 e = intersections.end();
1732 const osg::NodePath& np = hit->nodePath;
1733 osg::NodePath::const_reverse_iterator npi;
1734 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1735 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1738 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1739 SGPickCallback* pickCallback = ud->getPickCallback(i);
1742 SGSceneryPick sceneryPick;
1743 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
1744 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
1745 sceneryPick.callback = pickCallback;
1746 pickList.push_back(sceneryPick);
1750 return !pickList.empty();
1754 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
1760 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
1762 eventHandler = eventHandler_;
1766 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1768 mRealRoot->addChild(camera);
1772 FGRenderer::removeCamera(osg::Camera* camera)
1774 mRealRoot->removeChild(camera);
1778 FGRenderer::setPlanes( double zNear, double zFar )
1780 _planes->set( osg::Vec3f( - zFar, - zFar * zNear, zFar - zNear ) );
1784 fgDumpSceneGraphToFile(const char* filename)
1786 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1790 fgDumpTerrainBranchToFile(const char* filename)
1792 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1798 fgDumpNodeToFile(osg::Node* node, const char* filename)
1800 return osgDB::writeNodeFile(*node, filename);
1803 namespace flightgear
1805 using namespace osg;
1807 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
1810 VisibleSceneInfoVistor()
1811 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
1813 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
1814 | CullSettings::VIEW_FRUSTUM_CULLING);
1815 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
1818 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
1822 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
1824 typedef std::map<const std::string,int> InfoMap;
1826 void getNodeInfo(Node* node)
1828 const char* typeName = typeid(*node).name();
1829 classInfo[typeName]++;
1830 const std::string& nodeName = node->getName();
1831 if (!nodeName.empty())
1832 nodeInfo[nodeName]++;
1837 using namespace std;
1838 typedef vector<InfoMap::iterator> FreqVector;
1839 cout << "class info:\n";
1841 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
1844 classes.push_back(itr);
1845 sort(classes.begin(), classes.end(), freqComp);
1846 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
1849 cout << (*itr)->first << " " << (*itr)->second << "\n";
1851 cout << "\nnode info:\n";
1853 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
1856 nodes.push_back(itr);
1858 sort (nodes.begin(), nodes.end(), freqComp);
1859 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
1862 cout << (*itr)->first << " " << (*itr)->second << "\n";
1867 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
1869 ref_ptr<RefMatrix> projection
1870 = createOrReuseMatrix(camera->getProjectionMatrix());
1871 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
1873 viewport = camera->getViewport();
1875 pushViewport(viewport);
1876 pushProjectionMatrix(projection.get());
1877 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
1878 root->accept(*this);
1879 popModelViewMatrix();
1880 popProjectionMatrix();
1886 void apply(Node& node)
1895 void apply(Group& node)
1905 void apply(Transform& node)
1910 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
1911 node.computeLocalToWorldMatrix(*matrix,this);
1912 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1915 popModelViewMatrix();
1919 void apply(Camera& camera)
1921 // Save current cull settings
1922 CullSettings saved_cull_settings(*this);
1924 // set cull settings from this Camera
1925 setCullSettings(camera);
1926 // inherit the settings from above
1927 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1929 // set the cull mask.
1930 unsigned int savedTraversalMask = getTraversalMask();
1931 bool mustSetCullMask = (camera.getInheritanceMask()
1932 & osg::CullSettings::CULL_MASK) == 0;
1933 if (mustSetCullMask)
1934 setTraversalMask(camera.getCullMask());
1936 osg::RefMatrix* projection = 0;
1937 osg::RefMatrix* modelview = 0;
1939 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1940 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1941 projection = createOrReuseMatrix(*getProjectionMatrix()
1942 *camera.getProjectionMatrix());
1943 modelview = createOrReuseMatrix(*getModelViewMatrix()
1944 * camera.getViewMatrix());
1946 else { // pre multiply
1947 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1948 * (*getProjectionMatrix()));
1949 modelview = createOrReuseMatrix(camera.getViewMatrix()
1950 * (*getModelViewMatrix()));
1953 // an absolute reference frame
1954 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1955 modelview = createOrReuseMatrix(camera.getViewMatrix());
1957 if (camera.getViewport())
1958 pushViewport(camera.getViewport());
1960 pushProjectionMatrix(projection);
1961 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1965 // restore the previous model view matrix.
1966 popModelViewMatrix();
1968 // restore the previous model view matrix.
1969 popProjectionMatrix();
1971 if (camera.getViewport()) popViewport();
1973 // restore the previous traversal mask settings
1974 if (mustSetCullMask)
1975 setTraversalMask(savedTraversalMask);
1977 // restore the previous cull settings
1978 setCullSettings(saved_cull_settings);
1983 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1985 return lhs->second > rhs->second;
1991 bool printVisibleSceneInfo(FGRenderer* renderer)
1993 osgViewer::Viewer* viewer = renderer->getViewer();
1994 VisibleSceneInfoVistor vsv;
1996 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1997 const View::Slave& slave = viewer->getSlave(0);
1998 vp = slave._camera->getViewport();
2000 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
2005 // end of renderer.cxx