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>
66 #include <simgear/math/SGMath.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/sky/sky.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/util/SGSceneUserData.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
82 #include <simgear/screen/jpgfactory.hxx>
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Model/panelnode.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/redout.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Instrumentation/HUD/HUD.hxx>
95 #include <Environment/precipitation_mgr.hxx>
96 #include <Environment/environment_mgr.hxx>
99 #include "renderer.hxx"
101 #include "CameraGroup.hxx"
102 #include "FGEventHandler.hxx"
103 #include <Main/viewer.hxx>
104 #include <Main/viewmgr.hxx>
107 using namespace simgear;
108 using namespace flightgear;
110 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
112 FGHintUpdateCallback(const char* configNode) :
113 mConfigNode(fgGetNode(configNode, true))
115 virtual void operator()(osg::StateAttribute* stateAttribute,
118 assert(dynamic_cast<osg::Hint*>(stateAttribute));
119 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
121 const char* value = mConfigNode->getStringValue();
123 hint->setMode(GL_DONT_CARE);
124 else if (0 == strcmp(value, "nicest"))
125 hint->setMode(GL_NICEST);
126 else if (0 == strcmp(value, "fastest"))
127 hint->setMode(GL_FASTEST);
129 hint->setMode(GL_DONT_CARE);
132 SGPropertyNode_ptr mConfigNode;
136 class SGPuDrawable : public osg::Drawable {
140 // Dynamic stuff, do not store geometry
141 setUseDisplayList(false);
142 setDataVariance(Object::DYNAMIC);
144 osg::StateSet* stateSet = getOrCreateStateSet();
145 stateSet->setRenderBinDetails(1001, "RenderBin");
146 // speed optimization?
147 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
148 // We can do translucent menus, so why not. :-)
149 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
150 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
151 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
153 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
155 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
156 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
158 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
159 { drawImplementation(*renderInfo.getState()); }
160 void drawImplementation(osg::State& state) const
162 state.setActiveTextureUnit(0);
163 state.setClientActiveTextureUnit(0);
165 state.disableAllVertexArrays();
167 glPushAttrib(GL_ALL_ATTRIB_BITS);
168 glPushClientAttrib(~0u);
176 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
177 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
182 class SGHUDAndPanelDrawable : public osg::Drawable {
184 SGHUDAndPanelDrawable()
186 // Dynamic stuff, do not store geometry
187 setUseDisplayList(false);
188 setDataVariance(Object::DYNAMIC);
190 osg::StateSet* stateSet = getOrCreateStateSet();
191 stateSet->setRenderBinDetails(1000, "RenderBin");
193 // speed optimization?
194 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
195 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
196 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
197 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
198 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
200 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
202 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
203 { drawImplementation(*renderInfo.getState()); }
204 void drawImplementation(osg::State& state) const
206 state.setActiveTextureUnit(0);
207 state.setClientActiveTextureUnit(0);
208 state.disableAllVertexArrays();
210 glPushAttrib(GL_ALL_ATTRIB_BITS);
211 glPushClientAttrib(~0u);
213 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
216 // update the panel subsystem
217 if ( globals->get_current_panel() != NULL )
218 globals->get_current_panel()->update(state);
219 // We don't need a state here - can be safely removed when we can pick
228 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
238 * @param isSun true if the light is the actual sun i.e., for
239 * illuminating the moon.
241 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
244 : NodeCallback(nc, op), _isSun(nc._isSun)
246 META_Object(flightgear,FGLightSourceUpdateCallback);
248 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
250 assert(dynamic_cast<osg::LightSource*>(node));
251 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252 osg::Light* light = lightSource->getLight();
254 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
256 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
260 light->setAmbient(toOsg(l->scene_ambient()));
261 light->setDiffuse(toOsg(l->scene_diffuse()));
262 light->setSpecular(toOsg(l->scene_specular()));
264 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265 light->setPosition(position);
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
275 FGWireFrameModeUpdateCallback() :
276 mWireframe(fgGetNode("/sim/rendering/wireframe", true))
278 virtual void operator()(osg::StateAttribute* stateAttribute,
281 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282 osg::PolygonMode* polygonMode;
283 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
285 if (mWireframe->getBoolValue())
286 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287 osg::PolygonMode::LINE);
289 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290 osg::PolygonMode::FILL);
293 SGPropertyNode_ptr mWireframe;
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
298 FGLightModelUpdateCallback() :
299 mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
301 virtual void operator()(osg::StateAttribute* stateAttribute,
304 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305 osg::LightModel* lightModel;
306 lightModel = static_cast<osg::LightModel*>(stateAttribute);
309 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
312 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
314 lightModel->setTwoSided(true);
315 lightModel->setLocalViewer(false);
317 if (mHighlights->getBoolValue()) {
318 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
320 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
324 SGPropertyNode_ptr mHighlights;
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
329 FGFogEnableUpdateCallback() :
330 mFogEnabled(fgGetNode("/sim/rendering/fog", true))
332 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
334 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
337 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
341 SGPropertyNode_ptr mFogEnabled;
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
346 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
348 assert(dynamic_cast<SGUpdateVisitor*>(nv));
349 assert(dynamic_cast<osg::Fog*>(sa));
350 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351 osg::Fog* fog = static_cast<osg::Fog*>(sa);
352 fog->setMode(osg::Fog::EXP2);
353 fog->setColor(toOsg(updateVisitor->getFogColor()));
354 fog->setDensity(updateVisitor->getFogExp2Density());
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
361 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
363 assert(dynamic_cast<osg::Switch*>(node));
364 osg::Switch* sw = static_cast<osg::Switch*>(node);
366 bool enabled = scenery_enabled;
367 sw->setValue(0, enabled);
373 static bool scenery_enabled;
376 bool FGScenerySwitchCallback::scenery_enabled = false;
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
385 #ifdef FG_JPEG_SERVER
386 static void updateRenderer()
388 globals->get_renderer()->update();
392 FGRenderer::FGRenderer() :
395 #ifdef FG_JPEG_SERVER
396 jpgRenderFrame = updateRenderer;
398 eventHandler = new FGEventHandler;
401 FGRenderer::~FGRenderer()
403 #ifdef FG_JPEG_SERVER
404 jpgRenderFrame = NULL;
409 // Initialize various GL/view parameters
410 // XXX This should be called "preinit" or something, as it initializes
411 // critical parts of the scene graph in addition to the splash screen.
413 FGRenderer::splashinit( void ) {
414 osgViewer::Viewer* viewer = getViewer();
415 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
416 mRealRoot->addChild(fgCreateSplashNode());
417 mFrameStamp = viewer->getFrameStamp();
418 // Scene doesn't seem to pass the frame stamp to the update
419 // visitor automatically.
420 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
421 viewer->setUpdateVisitor(mUpdateVisitor.get());
422 fgSetDouble("/sim/startup/splash-alpha", 1.0);
426 FGRenderer::init( void )
428 _scenery_loaded = fgGetNode("/sim/sceneryloaded", true);
429 _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
430 _panel_hotspots = fgGetNode("/sim/panel-hotspots", true);
431 _virtual_cockpit = fgGetNode("/sim/virtual-cockpit", true);
433 _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
435 _xsize = fgGetNode("/sim/startup/xsize", true);
436 _ysize = fgGetNode("/sim/startup/ysize", true);
437 _splash_alpha = fgGetNode("/sim/startup/splash-alpha", true);
439 _skyblend = fgGetNode("/sim/rendering/skyblend", true);
440 _point_sprites = fgGetNode("/sim/rendering/point-sprites", true);
441 _enhanced_lighting = fgGetNode("/sim/rendering/enhanced-lighting", true);
442 _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
443 _horizon_effect = fgGetNode("/sim/rendering/horizon-effect", true);
444 _textures = fgGetNode("/sim/rendering/textures", true);
446 _altitude_ft = fgGetNode("/position/altitude-ft", true);
448 _cloud_status = fgGetNode("/environment/clouds/status", true);
449 _visibility_m = fgGetNode("/environment/visibility-m", true);
451 bool use_point_sprites = _point_sprites->getBoolValue();
452 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
453 bool distance_attenuation = _distance_attenuation->getBoolValue();
455 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
456 distance_attenuation );
458 // create sky, but can't build until setupView, since we depend
459 // on other subsystems to be inited, eg Ephemeris
462 SGPath texture_path(globals->get_fg_root());
463 texture_path.append("Textures");
464 texture_path.append("Sky");
465 for (int i = 0; i < FGEnvironmentMgr::MAX_CLOUD_LAYERS; i++) {
466 SGCloudLayer * layer = new SGCloudLayer(texture_path.str());
467 _sky->add_cloud_layer(layer);
470 _sky->texture_path( texture_path.str() );
474 FGRenderer::setupView( void )
476 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
477 osg::initNotifyLevel();
479 // The number of polygon-offset "units" to place between layers. In
480 // principle, one is supposed to be enough. In practice, I find that
481 // my hardware/driver requires many more.
482 osg::PolygonOffset::setUnitsMultiplier(1);
483 osg::PolygonOffset::setFactorMultiplier(1);
485 // Go full screen if requested ...
486 if ( fgGetBool("/sim/startup/fullscreen") )
490 // The sun and moon diameters are scaled down numbers of the
491 // actual diameters. This was needed to fit both the sun and the
492 // moon within the distance to the far clip plane.
493 // Moon diameter: 3,476 kilometers
494 // Sun diameter: 1,390,000 kilometers
495 _sky->build( 80000.0, 80000.0,
497 *globals->get_ephem(),
498 fgGetNode("/environment", true));
501 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
503 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
505 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
507 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
508 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
510 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
511 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
512 stateSet->setAttribute(new osg::BlendFunc);
513 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
515 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
517 // this will be set below
518 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
520 osg::Material* material = new osg::Material;
521 stateSet->setAttribute(material);
523 stateSet->setTextureAttribute(0, new osg::TexEnv);
524 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
526 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
527 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
528 stateSet->setAttribute(hint);
529 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
530 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
531 stateSet->setAttribute(hint);
532 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
533 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
534 stateSet->setAttribute(hint);
535 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
536 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
537 stateSet->setAttribute(hint);
538 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
539 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
540 stateSet->setAttribute(hint);
542 osg::Group* sceneGroup = new osg::Group;
543 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
544 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
546 //sceneGroup->addChild(thesky->getCloudRoot());
548 stateSet = sceneGroup->getOrCreateStateSet();
549 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
551 // need to update the light on every frame
552 // OSG LightSource objects are rather confusing. OSG only supports
553 // the 10 lights specified by OpenGL itself; if more than one
554 // LightSource in the scene graph have the same light number, it's
555 // indeterminate which values will be used to render geometry that
556 // has that light number enabled. Also, adding children to a
557 // LightSource is just a shortcut for setting up a state set that
558 // has the corresponding OpenGL light enabled: a LightSource will
559 // affect geometry anywhere in the scene graph that has its light
560 // number enabled in a state set.
561 LightSource* lightSource = new LightSource;
562 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
563 // relative because of CameraView being just a clever transform node
564 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
565 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
566 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
567 mRealRoot->addChild(lightSource);
568 // we need a white diffuse light for the phase of the moon
569 osg::LightSource* sunLight = new osg::LightSource;
570 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
571 sunLight->getLight()->setLightNum(1);
572 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
573 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
574 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
576 // Hang a StateSet above the sky subgraph in order to turn off
578 Group* skyGroup = new Group;
579 StateSet* skySS = skyGroup->getOrCreateStateSet();
580 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
581 skyGroup->addChild(_sky->getPreRoot());
582 sunLight->addChild(skyGroup);
583 mRoot->addChild(sceneGroup);
584 mRoot->addChild(sunLight);
586 // Clouds are added to the scene graph later
587 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
588 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
589 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
590 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
592 // enable disable specular highlights.
593 // is the place where we might plug in an other fragment shader ...
594 osg::LightModel* lightModel = new osg::LightModel;
595 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
596 stateSet->setAttribute(lightModel);
598 // switch to enable wireframe
599 osg::PolygonMode* polygonMode = new osg::PolygonMode;
600 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
601 stateSet->setAttributeAndModes(polygonMode);
603 // scene fog handling
604 osg::Fog* fog = new osg::Fog;
605 fog->setUpdateCallback(new FGFogUpdateCallback);
606 stateSet->setAttributeAndModes(fog);
607 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
610 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
612 osg::Geode* geode = new osg::Geode;
613 geode->addDrawable(new SGPuDrawable);
614 geode->addDrawable(new SGHUDAndPanelDrawable);
615 guiCamera->addChild(geode);
617 osg::Switch* sw = new osg::Switch;
618 sw->setUpdateCallback(new FGScenerySwitchCallback);
619 sw->addChild(mRoot.get());
620 mRealRoot->addChild(sw);
621 // The clouds are attached directly to the scene graph root
622 // because, in theory, they don't want the same default state set
623 // as the rest of the scene. This may not be true in practice.
624 mRealRoot->addChild(_sky->getCloudRoot());
625 mRealRoot->addChild(FGCreateRedoutNode());
626 // Attach empty program to the scene root so that shader programs
627 // don't leak into state sets (effects) that shouldn't have one.
628 stateSet = mRealRoot->getOrCreateStateSet();
629 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
632 // Update all Visuals (redraws anything graphics related)
634 FGRenderer::update( ) {
635 if (!(_scenery_loaded->getBoolValue() ||
636 _scenery_override->getBoolValue()))
638 _splash_alpha->setDoubleValue(1.0);
641 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
643 if (_splash_alpha->getDoubleValue()>0.0)
645 // Fade out the splash screen
646 const double fade_time = 0.8;
647 const double fade_steps_per_sec = 20;
648 double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
649 (SGTimeStamp::now() - _splash_time).toSecs());
650 _splash_time = SGTimeStamp::now();
651 double sAlpha = _splash_alpha->getDoubleValue();
652 sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
653 FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
654 _splash_alpha->setDoubleValue(sAlpha);
658 // OSGFIXME: features no longer available or no longer run-time configurable
660 bool use_point_sprites = _point_sprites->getBoolValue();
661 bool enhanced_lighting = _enhanced_lighting->getBoolValue();
662 bool distance_attenuation = _distance_attenuation->getBoolValue();
664 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
665 distance_attenuation );
669 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
672 double actual_visibility;
673 if (_cloud_status->getBoolValue()) {
674 actual_visibility = _sky->get_visibility();
676 actual_visibility = _visibility_m->getDoubleValue();
679 // idle_state is now 1000 meaning we've finished all our
680 // initializations and are running the main loop, so this will
681 // now work without seg faulting the system.
683 FGViewer *current__view = globals->get_current_view();
684 // Force update of center dependent values ...
685 current__view->set_dirty();
687 osg::Camera *camera = viewer->getCamera();
689 bool skyblend = _skyblend->getBoolValue();
692 if ( _textures->getBoolValue() ) {
693 SGVec4f clearColor(l->adj_fog_color());
694 camera->setClearColor(toOsg(clearColor));
697 SGVec4f clearColor(l->sky_color());
698 camera->setClearColor(toOsg(clearColor));
701 // update fog params if visibility has changed
702 double visibility_meters = _visibility_m->getDoubleValue();
703 _sky->set_visibility(visibility_meters);
705 double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
706 _sky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
708 // update the sky dome
711 // The sun and moon distances are scaled down versions
712 // of the actual distance to get both the moon and the sun
713 // within the range of the far clip plane.
714 // Moon distance: 384,467 kilometers
715 // Sun distance: 150,000,000 kilometers
717 double sun_horiz_eff, moon_horiz_eff;
718 if (_horizon_effect->getBoolValue()) {
720 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
724 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
728 sun_horiz_eff = moon_horiz_eff = 1.0;
732 sstate.pos = current__view->getViewPosition();
733 sstate.pos_geod = current__view->getPosition();
734 sstate.ori = current__view->getViewOrientation();
735 sstate.spin = l->get_sun_rotation();
736 sstate.gst = globals->get_time_params()->getGst();
737 sstate.sun_dist = 50000.0 * sun_horiz_eff;
738 sstate.moon_dist = 40000.0 * moon_horiz_eff;
739 sstate.sun_angle = l->get_sun_angle();
742 scolor.sky_color = SGVec3f(l->sky_color().data());
743 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
744 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
745 scolor.cloud_color = SGVec3f(l->cloud_color().data());
746 scolor.sun_angle = l->get_sun_angle();
747 scolor.moon_angle = l->get_moon_angle();
749 double delta_time_sec = _sim_delta_sec->getDoubleValue();
750 _sky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
751 _sky->repaint( scolor, *globals->get_ephem() );
754 // shadows->setupShadows(
755 // current__view->getLongitude_deg(),
756 // current__view->getLatitude_deg(),
757 // globals->get_time_params()->getGst(),
758 // globals->get_ephem()->getSunRightAscension(),
759 // globals->get_ephem()->getSunDeclination(),
760 // l->get_sun_angle());
764 // sgEnviro.setLight(l->adj_fog_color());
765 // sgEnviro.startOfFrame(current__view->get_view_pos(),
766 // current__view->get_world_up(),
767 // current__view->getLongitude_deg(),
768 // current__view->getLatitude_deg(),
769 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
773 // sgEnviro.drawLightning();
775 // double current_view_origin_airspeed_horiz_kt =
776 // fgGetDouble("/velocities/airspeed-kt", 0.0)
777 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
778 // * SGD_DEGREES_TO_RADIANS);
782 // shadows->endOfFrame();
784 // need to call the update visitor once
785 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
786 mUpdateVisitor->setViewData(current__view->getViewPosition(),
787 current__view->getViewOrientation());
788 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
789 mUpdateVisitor->setLight(direction, l->scene_ambient(),
790 l->scene_diffuse(), l->scene_specular(),
792 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
793 mUpdateVisitor->setVisibility(actual_visibility);
794 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
795 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
796 cullMask |= simgear::GroundLightManager::instance()
797 ->getLightNodeMask(mUpdateVisitor.get());
798 if (_panel_hotspots->getBoolValue())
799 cullMask |= simgear::PICK_BIT;
800 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
804 FGRenderer::resize( int width, int height )
806 int curWidth = _xsize->getIntValue(),
807 curHeight = _ysize->getIntValue();
808 SG_LOG(SG_VIEW, SG_DEBUG, "FGRenderer::resize: new size " << width << " x " << height);
809 if ((curHeight != height) || (curWidth != width)) {
810 // must guard setting these, or PLIB-PUI fails with too many live interfaces
811 _xsize->setIntValue(width);
812 _ysize->setIntValue(height);
817 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
818 const osgGA::GUIEventAdapter* ea)
820 // wipe out the return ...
822 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
823 Intersections intersections;
825 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
827 for (Intersections::iterator hit = intersections.begin(),
828 e = intersections.end();
831 const osg::NodePath& np = hit->nodePath;
832 osg::NodePath::const_reverse_iterator npi;
833 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
834 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
837 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
838 SGPickCallback* pickCallback = ud->getPickCallback(i);
841 SGSceneryPick sceneryPick;
842 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
843 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
844 sceneryPick.callback = pickCallback;
845 pickList.push_back(sceneryPick);
849 return !pickList.empty();
853 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
859 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
861 eventHandler = eventHandler_;
865 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
867 mRealRoot->addChild(camera);
871 fgDumpSceneGraphToFile(const char* filename)
873 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
877 fgDumpTerrainBranchToFile(const char* filename)
879 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
885 fgDumpNodeToFile(osg::Node* node, const char* filename)
887 return osgDB::writeNodeFile(*node, filename);
894 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
897 VisibleSceneInfoVistor()
898 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
900 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
901 | CullSettings::VIEW_FRUSTUM_CULLING);
902 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
905 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
909 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
911 typedef std::map<const std::string,int> InfoMap;
913 void getNodeInfo(Node* node)
915 const char* typeName = typeid(*node).name();
916 classInfo[typeName]++;
917 const std::string& nodeName = node->getName();
918 if (!nodeName.empty())
919 nodeInfo[nodeName]++;
925 typedef vector<InfoMap::iterator> FreqVector;
926 cout << "class info:\n";
928 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
931 classes.push_back(itr);
932 sort(classes.begin(), classes.end(), freqComp);
933 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
936 cout << (*itr)->first << " " << (*itr)->second << "\n";
938 cout << "\nnode info:\n";
940 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
943 nodes.push_back(itr);
945 sort (nodes.begin(), nodes.end(), freqComp);
946 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
949 cout << (*itr)->first << " " << (*itr)->second << "\n";
954 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
956 ref_ptr<RefMatrix> projection
957 = createOrReuseMatrix(camera->getProjectionMatrix());
958 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
960 viewport = camera->getViewport();
962 pushViewport(viewport);
963 pushProjectionMatrix(projection.get());
964 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
966 popModelViewMatrix();
967 popProjectionMatrix();
973 void apply(Node& node)
982 void apply(Group& node)
992 void apply(Transform& node)
997 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
998 node.computeLocalToWorldMatrix(*matrix,this);
999 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
1002 popModelViewMatrix();
1006 void apply(Camera& camera)
1008 // Save current cull settings
1009 CullSettings saved_cull_settings(*this);
1011 // set cull settings from this Camera
1012 setCullSettings(camera);
1013 // inherit the settings from above
1014 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1016 // set the cull mask.
1017 unsigned int savedTraversalMask = getTraversalMask();
1018 bool mustSetCullMask = (camera.getInheritanceMask()
1019 & osg::CullSettings::CULL_MASK) == 0;
1020 if (mustSetCullMask)
1021 setTraversalMask(camera.getCullMask());
1023 osg::RefMatrix* projection = 0;
1024 osg::RefMatrix* modelview = 0;
1026 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1027 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1028 projection = createOrReuseMatrix(*getProjectionMatrix()
1029 *camera.getProjectionMatrix());
1030 modelview = createOrReuseMatrix(*getModelViewMatrix()
1031 * camera.getViewMatrix());
1033 else { // pre multiply
1034 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1035 * (*getProjectionMatrix()));
1036 modelview = createOrReuseMatrix(camera.getViewMatrix()
1037 * (*getModelViewMatrix()));
1040 // an absolute reference frame
1041 projection = createOrReuseMatrix(camera.getProjectionMatrix());
1042 modelview = createOrReuseMatrix(camera.getViewMatrix());
1044 if (camera.getViewport())
1045 pushViewport(camera.getViewport());
1047 pushProjectionMatrix(projection);
1048 pushModelViewMatrix(modelview, camera.getReferenceFrame());
1052 // restore the previous model view matrix.
1053 popModelViewMatrix();
1055 // restore the previous model view matrix.
1056 popProjectionMatrix();
1058 if (camera.getViewport()) popViewport();
1060 // restore the previous traversal mask settings
1061 if (mustSetCullMask)
1062 setTraversalMask(savedTraversalMask);
1064 // restore the previous cull settings
1065 setCullSettings(saved_cull_settings);
1070 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1072 return lhs->second > rhs->second;
1078 bool printVisibleSceneInfo(FGRenderer* renderer)
1080 osgViewer::Viewer* viewer = renderer->getViewer();
1081 VisibleSceneInfoVistor vsv;
1083 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1084 const View::Slave& slave = viewer->getSlave(0);
1085 vp = slave._camera->getViewport();
1087 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1091 // end of renderer.cxx