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 <simgear/environment/visual_enviro.hxx>
87 #include <Time/light.hxx>
88 #include <Time/light.hxx>
89 #include <Cockpit/panel.hxx>
90 #include <Model/panelnode.hxx>
91 #include <Model/modelmgr.hxx>
92 #include <Model/acmodel.hxx>
93 #include <Scenery/scenery.hxx>
94 #include <Scenery/redout.hxx>
95 #include <Scenery/tilemgr.hxx>
96 #include <GUI/new_gui.hxx>
97 #include <Instrumentation/HUD/HUD.hxx>
98 #include <Environment/precipitation_mgr.hxx>
100 #include "splash.hxx"
101 #include "renderer.hxx"
103 #include "CameraGroup.hxx"
104 #include "FGEventHandler.hxx"
105 #include <Main/viewer.hxx>
106 #include <Main/viewmgr.hxx>
109 using namespace simgear;
110 using namespace flightgear;
112 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
114 FGHintUpdateCallback(const char* configNode) :
115 mConfigNode(fgGetNode(configNode, true))
117 virtual void operator()(osg::StateAttribute* stateAttribute,
120 assert(dynamic_cast<osg::Hint*>(stateAttribute));
121 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
123 const char* value = mConfigNode->getStringValue();
125 hint->setMode(GL_DONT_CARE);
126 else if (0 == strcmp(value, "nicest"))
127 hint->setMode(GL_NICEST);
128 else if (0 == strcmp(value, "fastest"))
129 hint->setMode(GL_FASTEST);
131 hint->setMode(GL_DONT_CARE);
134 SGSharedPtr<SGPropertyNode> mConfigNode;
138 class SGPuDrawable : public osg::Drawable {
142 // Dynamic stuff, do not store geometry
143 setUseDisplayList(false);
144 setDataVariance(Object::DYNAMIC);
146 osg::StateSet* stateSet = getOrCreateStateSet();
147 stateSet->setRenderBinDetails(1001, "RenderBin");
148 // speed optimization?
149 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
150 // We can do translucent menus, so why not. :-)
151 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
152 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
153 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
155 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
157 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
158 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
160 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
161 { drawImplementation(*renderInfo.getState()); }
162 void drawImplementation(osg::State& state) const
164 state.setActiveTextureUnit(0);
165 state.setClientActiveTextureUnit(0);
167 state.disableAllVertexArrays();
169 glPushAttrib(GL_ALL_ATTRIB_BITS);
170 glPushClientAttrib(~0u);
178 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
179 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
184 class SGHUDAndPanelDrawable : public osg::Drawable {
186 SGHUDAndPanelDrawable()
188 // Dynamic stuff, do not store geometry
189 setUseDisplayList(false);
190 setDataVariance(Object::DYNAMIC);
192 osg::StateSet* stateSet = getOrCreateStateSet();
193 stateSet->setRenderBinDetails(1000, "RenderBin");
195 // speed optimization?
196 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
197 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
198 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
199 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
200 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
202 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
204 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
205 { drawImplementation(*renderInfo.getState()); }
206 void drawImplementation(osg::State& state) const
208 state.setActiveTextureUnit(0);
209 state.setClientActiveTextureUnit(0);
210 state.disableAllVertexArrays();
212 glPushAttrib(GL_ALL_ATTRIB_BITS);
213 glPushClientAttrib(~0u);
215 HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
218 // update the panel subsystem
219 if ( globals->get_current_panel() != NULL )
220 globals->get_current_panel()->update(state);
221 // We don't need a state here - can be safely removed when we can pick
230 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
231 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
236 class FGLightSourceUpdateCallback : public osg::NodeCallback {
240 * @param isSun true if the light is the actual sun i.e., for
241 * illuminating the moon.
243 FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
244 FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
246 : NodeCallback(nc, op), _isSun(nc._isSun)
248 META_Object(flightgear,FGLightSourceUpdateCallback);
250 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
252 assert(dynamic_cast<osg::LightSource*>(node));
253 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
254 osg::Light* light = lightSource->getLight();
256 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
258 light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259 light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
260 light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
262 light->setAmbient(toOsg(l->scene_ambient()));
263 light->setDiffuse(toOsg(l->scene_diffuse()));
264 light->setSpecular(toOsg(l->scene_specular()));
266 osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
267 light->setPosition(position);
275 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
277 FGWireFrameModeUpdateCallback() :
278 mWireframe(fgGetNode("/sim/rendering/wireframe"))
280 virtual void operator()(osg::StateAttribute* stateAttribute,
283 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
284 osg::PolygonMode* polygonMode;
285 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
287 if (mWireframe->getBoolValue())
288 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
289 osg::PolygonMode::LINE);
291 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
292 osg::PolygonMode::FILL);
295 SGSharedPtr<SGPropertyNode> mWireframe;
298 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
300 FGLightModelUpdateCallback() :
301 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
303 virtual void operator()(osg::StateAttribute* stateAttribute,
306 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
307 osg::LightModel* lightModel;
308 lightModel = static_cast<osg::LightModel*>(stateAttribute);
311 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
312 lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
314 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
316 lightModel->setTwoSided(true);
317 lightModel->setLocalViewer(false);
319 if (mHighlights->getBoolValue()) {
320 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
322 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
326 SGSharedPtr<SGPropertyNode> mHighlights;
329 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
331 FGFogEnableUpdateCallback() :
332 mFogEnabled(fgGetNode("/sim/rendering/fog"))
334 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
336 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
337 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
339 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
343 SGSharedPtr<SGPropertyNode> mFogEnabled;
346 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
348 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
350 assert(dynamic_cast<SGUpdateVisitor*>(nv));
351 assert(dynamic_cast<osg::Fog*>(sa));
352 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
353 osg::Fog* fog = static_cast<osg::Fog*>(sa);
354 fog->setMode(osg::Fog::EXP2);
355 fog->setColor(toOsg(updateVisitor->getFogColor()));
356 fog->setDensity(updateVisitor->getFogExp2Density());
360 // update callback for the switch node guarding that splash
361 class FGScenerySwitchCallback : public osg::NodeCallback {
363 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
365 assert(dynamic_cast<osg::Switch*>(node));
366 osg::Switch* sw = static_cast<osg::Switch*>(node);
368 double t = globals->get_sim_time_sec();
369 bool enabled = 0 < t;
370 sw->setValue(0, enabled);
380 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
381 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
383 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
387 FGRenderer::FGRenderer()
389 #ifdef FG_JPEG_SERVER
390 jpgRenderFrame = FGRenderer::update;
392 eventHandler = new FGEventHandler;
395 FGRenderer::~FGRenderer()
397 #ifdef FG_JPEG_SERVER
398 jpgRenderFrame = NULL;
402 // Initialize various GL/view parameters
403 // XXX This should be called "preinit" or something, as it initializes
404 // critical parts of the scene graph in addition to the splash screen.
406 FGRenderer::splashinit( void ) {
407 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
408 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
409 mRealRoot->addChild(fgCreateSplashNode());
410 mFrameStamp = viewer->getFrameStamp();
411 // Scene doesn't seem to pass the frame stamp to the update
412 // visitor automatically.
413 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
414 viewer->setUpdateVisitor(mUpdateVisitor.get());
418 FGRenderer::init( void )
420 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
421 osg::initNotifyLevel();
423 // The number of polygon-offset "units" to place between layers. In
424 // principle, one is supposed to be enough. In practice, I find that
425 // my hardware/driver requires many more.
426 osg::PolygonOffset::setUnitsMultiplier(1);
427 osg::PolygonOffset::setFactorMultiplier(1);
429 // Go full screen if requested ...
430 if ( fgGetBool("/sim/startup/fullscreen") )
434 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
436 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
438 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
440 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
441 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
443 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
444 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
445 stateSet->setAttribute(new osg::BlendFunc);
446 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
448 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
450 // this will be set below
451 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
453 osg::Material* material = new osg::Material;
454 stateSet->setAttribute(material);
456 stateSet->setTextureAttribute(0, new osg::TexEnv);
457 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
459 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
460 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
461 stateSet->setAttribute(hint);
462 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
463 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
464 stateSet->setAttribute(hint);
465 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
466 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
467 stateSet->setAttribute(hint);
468 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
469 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
470 stateSet->setAttribute(hint);
471 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
472 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
473 stateSet->setAttribute(hint);
475 osg::Group* sceneGroup = new osg::Group;
476 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
477 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
479 //sceneGroup->addChild(thesky->getCloudRoot());
481 stateSet = sceneGroup->getOrCreateStateSet();
482 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
484 // need to update the light on every frame
485 // OSG LightSource objects are rather confusing. OSG only supports
486 // the 10 lights specified by OpenGL itself; if more than one
487 // LightSource in the scene graph have the same light number, it's
488 // indeterminate which values will be used to render geometry that
489 // has that light number enabled. Also, adding children to a
490 // LightSource is just a shortcut for setting up a state set that
491 // has the corresponding OpenGL light enabled: a LightSource will
492 // affect geometry anywhere in the scene graph that has its light
493 // number enabled in a state set.
494 LightSource* lightSource = new LightSource;
495 lightSource->getLight()->setDataVariance(Object::DYNAMIC);
496 // relative because of CameraView being just a clever transform node
497 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
498 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
499 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
500 mRealRoot->addChild(lightSource);
501 // we need a white diffuse light for the phase of the moon
502 osg::LightSource* sunLight = new osg::LightSource;
503 sunLight->getLight()->setDataVariance(Object::DYNAMIC);
504 sunLight->getLight()->setLightNum(1);
505 sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
506 sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
507 sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
508 // Hang a StateSet above the sky subgraph in order to turn off
510 Group* skyGroup = new Group;
511 StateSet* skySS = skyGroup->getOrCreateStateSet();
512 skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
513 skyGroup->addChild(thesky->getPreRoot());
514 sunLight->addChild(skyGroup);
515 mRoot->addChild(sceneGroup);
516 mRoot->addChild(sunLight);
517 // Clouds are added to the scene graph later
518 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
519 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
520 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
521 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
523 // enable disable specular highlights.
524 // is the place where we might plug in an other fragment shader ...
525 osg::LightModel* lightModel = new osg::LightModel;
526 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
527 stateSet->setAttribute(lightModel);
529 // switch to enable wireframe
530 osg::PolygonMode* polygonMode = new osg::PolygonMode;
531 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
532 stateSet->setAttributeAndModes(polygonMode);
534 // scene fog handling
535 osg::Fog* fog = new osg::Fog;
536 fog->setUpdateCallback(new FGFogUpdateCallback);
537 stateSet->setAttributeAndModes(fog);
538 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
541 osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
543 osg::Geode* geode = new osg::Geode;
544 geode->addDrawable(new SGPuDrawable);
545 geode->addDrawable(new SGHUDAndPanelDrawable);
546 guiCamera->addChild(geode);
548 osg::Switch* sw = new osg::Switch;
549 sw->setUpdateCallback(new FGScenerySwitchCallback);
550 sw->addChild(mRoot.get());
551 mRealRoot->addChild(sw);
552 // The clouds are attached directly to the scene graph root
553 // because, in theory, they don't want the same default state set
554 // as the rest of the scene. This may not be true in practice.
555 mRealRoot->addChild(thesky->getCloudRoot());
556 mRealRoot->addChild(FGCreateRedoutNode());
557 // Attach empty program to the scene root so that shader programs
558 // don't leak into state sets (effects) that shouldn't have one.
559 stateSet = mRealRoot->getOrCreateStateSet();
560 stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
564 // Update all Visuals (redraws anything graphics related)
566 FGRenderer::update( bool refresh_camera_settings ) {
567 bool scenery_loaded = fgGetBool("sim/sceneryloaded", false)
568 || fgGetBool("sim/sceneryloaded-override");
569 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
570 if (!scenery_loaded) {
571 fgSetDouble("/sim/startup/splash-alpha", 1.0);
575 // Fade out the splash screen over the first three seconds.
576 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
577 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
579 bool skyblend = fgGetBool("/sim/rendering/skyblend");
580 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
581 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
582 bool distance_attenuation
583 = fgGetBool("/sim/rendering/distance-attenuation");
585 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
586 distance_attenuation );
588 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
591 double actual_visibility;
592 if (fgGetBool("/environment/clouds/status")) {
593 actual_visibility = thesky->get_visibility();
595 actual_visibility = fgGetDouble("/environment/visibility-m");
598 // idle_state is now 1000 meaning we've finished all our
599 // initializations and are running the main loop, so this will
600 // now work without seg faulting the system.
602 FGViewer *current__view = globals->get_current_view();
603 // Force update of center dependent values ...
604 current__view->set_dirty();
606 if ( refresh_camera_settings ) {
608 resize( fgGetInt("/sim/startup/xsize"),
609 fgGetInt("/sim/startup/ysize") );
611 osg::Camera *camera = viewer->getCamera();
615 if ( fgGetBool("/sim/rendering/textures") ) {
616 SGVec4f clearColor(l->adj_fog_color());
617 camera->setClearColor(toOsg(clearColor));
620 SGVec4f clearColor(l->sky_color());
621 camera->setClearColor(toOsg(clearColor));
624 // update fog params if visibility has changed
625 double visibility_meters = fgGetDouble("/environment/visibility-m");
626 thesky->set_visibility(visibility_meters);
628 double altitude_m = fgGetDouble("/position/altitude-ft") * SG_FEET_TO_METER;
629 thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
631 // update the sky dome
634 // The sun and moon distances are scaled down versions
635 // of the actual distance to get both the moon and the sun
636 // within the range of the far clip plane.
637 // Moon distance: 384,467 kilometers
638 // Sun distance: 150,000,000 kilometers
640 double sun_horiz_eff, moon_horiz_eff;
641 if (fgGetBool("/sim/rendering/horizon-effect")) {
643 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
647 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
651 sun_horiz_eff = moon_horiz_eff = 1.0;
655 sstate.pos = current__view->getViewPosition();
656 sstate.pos_geod = current__view->getPosition();
657 sstate.ori = current__view->getViewOrientation();
658 sstate.spin = l->get_sun_rotation();
659 sstate.gst = globals->get_time_params()->getGst();
660 sstate.sun_dist = 50000.0 * sun_horiz_eff;
661 sstate.moon_dist = 40000.0 * moon_horiz_eff;
662 sstate.sun_angle = l->get_sun_angle();
665 scolor.sky_color = SGVec3f(l->sky_color().data());
666 scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
667 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
668 scolor.cloud_color = SGVec3f(l->cloud_color().data());
669 scolor.sun_angle = l->get_sun_angle();
670 scolor.moon_angle = l->get_moon_angle();
672 double delta_time_sec = fgGetDouble("/sim/time/delta-sec");
673 thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
674 thesky->repaint( scolor, *globals->get_ephem() );
677 // shadows->setupShadows(
678 // current__view->getLongitude_deg(),
679 // current__view->getLatitude_deg(),
680 // globals->get_time_params()->getGst(),
681 // globals->get_ephem()->getSunRightAscension(),
682 // globals->get_ephem()->getSunDeclination(),
683 // l->get_sun_angle());
687 // sgEnviro.setLight(l->adj_fog_color());
688 // sgEnviro.startOfFrame(current__view->get_view_pos(),
689 // current__view->get_world_up(),
690 // current__view->getLongitude_deg(),
691 // current__view->getLatitude_deg(),
692 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
696 // sgEnviro.drawLightning();
698 // double current_view_origin_airspeed_horiz_kt =
699 // fgGetDouble("/velocities/airspeed-kt", 0.0)
700 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
701 // * SGD_DEGREES_TO_RADIANS);
705 // shadows->endOfFrame();
707 // need to call the update visitor once
708 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
709 mUpdateVisitor->setViewData(current__view->getViewPosition(),
710 current__view->getViewOrientation());
711 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
712 mUpdateVisitor->setLight(direction, l->scene_ambient(),
713 l->scene_diffuse(), l->scene_specular(),
715 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
716 mUpdateVisitor->setVisibility(actual_visibility);
717 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
718 bool hotspots = fgGetBool("/sim/panel-hotspots");
719 osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
720 cullMask |= simgear::GroundLightManager::instance()
721 ->getLightNodeMask(mUpdateVisitor.get());
723 cullMask |= simgear::PICK_BIT;
724 CameraGroup::getDefault()->setCameraCullMasks(cullMask);
729 // options.cxx needs to see this for toggle_panel()
730 // Handle new window size or exposure
732 FGRenderer::resize( int width, int height ) {
735 if ( (!fgGetBool("/sim/virtual-cockpit"))
736 && fgPanelVisible() && idle_state == 1000 ) {
737 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
738 globals->get_current_panel()->getYOffset()) / 768.0);
743 static int lastwidth = 0;
744 static int lastheight = 0;
745 if (width != lastwidth)
746 fgSetInt("/sim/startup/xsize", lastwidth = width);
747 if (height != lastheight)
748 fgSetInt("/sim/startup/ysize", lastheight = height);
751 FGViewMgr *viewmgr = globals->get_viewmgr();
753 for ( int i = 0; i < viewmgr->size(); ++i ) {
754 viewmgr->get_view(i)->
755 set_aspect_ratio((float)view_h / (float)width);
761 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
762 const osgGA::GUIEventAdapter* ea)
764 // wipe out the return ...
766 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
767 Intersections intersections;
769 if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
771 for (Intersections::iterator hit = intersections.begin(),
772 e = intersections.end();
775 const osg::NodePath& np = hit->nodePath;
776 osg::NodePath::const_reverse_iterator npi;
777 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
778 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
781 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
782 SGPickCallback* pickCallback = ud->getPickCallback(i);
785 SGSceneryPick sceneryPick;
786 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
787 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
788 sceneryPick.callback = pickCallback;
789 pickList.push_back(sceneryPick);
793 return !pickList.empty();
797 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
803 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
805 eventHandler = eventHandler_;
809 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
811 mRealRoot->addChild(camera);
815 fgDumpSceneGraphToFile(const char* filename)
817 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
821 fgDumpTerrainBranchToFile(const char* filename)
823 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
829 fgDumpNodeToFile(osg::Node* node, const char* filename)
831 return osgDB::writeNodeFile(*node, filename);
838 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
841 VisibleSceneInfoVistor()
842 : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
844 setCullingMode(CullSettings::SMALL_FEATURE_CULLING
845 | CullSettings::VIEW_FRUSTUM_CULLING);
846 setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
849 VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
853 META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
855 typedef std::map<const std::string,int> InfoMap;
857 void getNodeInfo(Node* node)
859 const char* typeName = typeid(*node).name();
860 classInfo[typeName]++;
861 const std::string& nodeName = node->getName();
862 if (!nodeName.empty())
863 nodeInfo[nodeName]++;
869 typedef vector<InfoMap::iterator> FreqVector;
870 cout << "class info:\n";
872 for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
875 classes.push_back(itr);
876 sort(classes.begin(), classes.end(), freqComp);
877 for (FreqVector::iterator itr = classes.begin(), end = classes.end();
880 cout << (*itr)->first << " " << (*itr)->second << "\n";
882 cout << "\nnode info:\n";
884 for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
887 nodes.push_back(itr);
889 sort (nodes.begin(), nodes.end(), freqComp);
890 for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
893 cout << (*itr)->first << " " << (*itr)->second << "\n";
898 void doTraversal(Camera* camera, Node* root, Viewport* viewport)
900 ref_ptr<RefMatrix> projection
901 = createOrReuseMatrix(camera->getProjectionMatrix());
902 ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
904 viewport = camera->getViewport();
906 pushViewport(viewport);
907 pushProjectionMatrix(projection.get());
908 pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
910 popModelViewMatrix();
911 popProjectionMatrix();
917 void apply(Node& node)
926 void apply(Group& node)
936 void apply(Transform& node)
941 ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
942 node.computeLocalToWorldMatrix(*matrix,this);
943 pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
946 popModelViewMatrix();
950 void apply(Camera& camera)
952 // Save current cull settings
953 CullSettings saved_cull_settings(*this);
955 // set cull settings from this Camera
956 setCullSettings(camera);
957 // inherit the settings from above
958 inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
960 // set the cull mask.
961 unsigned int savedTraversalMask = getTraversalMask();
962 bool mustSetCullMask = (camera.getInheritanceMask()
963 & osg::CullSettings::CULL_MASK) == 0;
965 setTraversalMask(camera.getCullMask());
967 osg::RefMatrix* projection = 0;
968 osg::RefMatrix* modelview = 0;
970 if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
971 if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
972 projection = createOrReuseMatrix(*getProjectionMatrix()
973 *camera.getProjectionMatrix());
974 modelview = createOrReuseMatrix(*getModelViewMatrix()
975 * camera.getViewMatrix());
977 else { // pre multiply
978 projection = createOrReuseMatrix(camera.getProjectionMatrix()
979 * (*getProjectionMatrix()));
980 modelview = createOrReuseMatrix(camera.getViewMatrix()
981 * (*getModelViewMatrix()));
984 // an absolute reference frame
985 projection = createOrReuseMatrix(camera.getProjectionMatrix());
986 modelview = createOrReuseMatrix(camera.getViewMatrix());
988 if (camera.getViewport())
989 pushViewport(camera.getViewport());
991 pushProjectionMatrix(projection);
992 pushModelViewMatrix(modelview, camera.getReferenceFrame());
996 // restore the previous model view matrix.
997 popModelViewMatrix();
999 // restore the previous model view matrix.
1000 popProjectionMatrix();
1002 if (camera.getViewport()) popViewport();
1004 // restore the previous traversal mask settings
1005 if (mustSetCullMask)
1006 setTraversalMask(savedTraversalMask);
1008 // restore the previous cull settings
1009 setCullSettings(saved_cull_settings);
1014 static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1016 return lhs->second > rhs->second;
1022 bool printVisibleSceneInfo(FGRenderer* renderer)
1024 osgViewer::Viewer* viewer = renderer->getViewer();
1025 VisibleSceneInfoVistor vsv;
1027 if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1028 const View::Slave& slave = viewer->getSlave(0);
1029 vp = slave._camera->getViewport();
1031 vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1035 // end of renderer.cxx