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.
29 #include <simgear/compiler.h>
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
39 #include <osg/CullFace>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/ShadeModel>
52 #include <osg/Version>
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58 #include <osgUtil/LineSegmentIntersector>
60 #include <osg/io_utils>
61 #include <osgDB/WriteFile>
62 #include <osgDB/ReadFile>
65 #include <simgear/math/SGMath.hxx>
66 #include <simgear/screen/extensions.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/util/SGUpdateVisitor.hxx>
71 #include <simgear/scene/util/RenderConstants.hxx>
72 #include <simgear/scene/tgdb/GroundLightManager.hxx>
73 #include <simgear/scene/tgdb/pt_lights.hxx>
74 #include <simgear/props/props.hxx>
75 #include <simgear/timing/sg_time.hxx>
76 #include <simgear/ephemeris/ephemeris.hxx>
77 #include <simgear/math/sg_random.h>
79 #include <simgear/screen/jpgfactory.hxx>
82 #include <simgear/environment/visual_enviro.hxx>
84 #include <Time/light.hxx>
85 #include <Time/light.hxx>
86 #include <Aircraft/aircraft.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Cockpit/cockpit.hxx>
89 #include <Cockpit/hud.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/instrument_mgr.hxx>
98 #include <Instrumentation/HUD/HUD.hxx>
99 #include <Environment/precipitation_mgr.hxx>
101 #include <Include/general.hxx>
102 #include "splash.hxx"
103 #include "renderer.hxx"
105 #include "ViewPartitionNode.hxx"
107 // XXX Make this go away when OSG 2.2 is released.
108 #if (FG_OSG_VERSION >= 21004)
109 #define UPDATE_VISITOR_IN_VIEWER 1
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);
145 osg::StateSet* stateSet = getOrCreateStateSet();
146 stateSet->setRenderBinDetails(1001, "RenderBin");
147 // speed optimization?
148 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
149 // We can do translucent menus, so why not. :-)
150 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
151 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
152 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
154 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
156 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
157 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
159 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
160 { drawImplementation(*renderInfo.getState()); }
161 void drawImplementation(osg::State& state) const
163 if (!fgOSIsMainContext(state.getGraphicsContext()))
166 state.pushStateSet(getStateSet());
168 state.setActiveTextureUnit(0);
169 state.setClientActiveTextureUnit(0);
170 state.disableAllVertexArrays();
172 glPushAttrib(GL_ALL_ATTRIB_BITS);
173 glPushClientAttrib(~0u);
181 state.dirtyAllModes();
182 state.dirtyAllAttributes();
183 state.dirtyAllVertexArrays();
186 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
187 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
192 class SGHUDAndPanelDrawable : public osg::Drawable {
194 SGHUDAndPanelDrawable()
196 // Dynamic stuff, do not store geometry
197 setUseDisplayList(false);
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 // std::cout << state.getGraphicsContext() << std::endl;
216 if (!fgOSIsMainContext(state.getGraphicsContext()))
219 state.pushStateSet(getStateSet());
221 state.setActiveTextureUnit(0);
222 state.setClientActiveTextureUnit(0);
223 state.disableAllVertexArrays();
225 glPushAttrib(GL_ALL_ATTRIB_BITS);
226 glPushClientAttrib(~0u);
228 fgCockpitUpdate(&state);
230 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
231 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
234 // update the panel subsystem
235 if ( globals->get_current_panel() != NULL )
236 globals->get_current_panel()->update(state);
237 // We don't need a state here - can be safely removed when we can pick
245 state.dirtyAllModes();
246 state.dirtyAllAttributes();
247 state.dirtyAllVertexArrays();
250 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
251 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
256 class FGLightSourceUpdateCallback : public osg::NodeCallback {
258 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
260 assert(dynamic_cast<osg::LightSource*>(node));
261 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
262 osg::Light* light = lightSource->getLight();
264 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
265 light->setAmbient(l->scene_ambient().osg());
266 light->setDiffuse(l->scene_diffuse().osg());
267 light->setSpecular(l->scene_specular().osg());
268 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
269 light->setPosition(position.osg());
270 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
271 light->setDirection(direction.osg());
272 light->setSpotExponent(0);
273 light->setSpotCutoff(180);
274 light->setConstantAttenuation(1);
275 light->setLinearAttenuation(0);
276 light->setQuadraticAttenuation(0);
282 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
284 FGWireFrameModeUpdateCallback() :
285 mWireframe(fgGetNode("/sim/rendering/wireframe"))
287 virtual void operator()(osg::StateAttribute* stateAttribute,
290 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
291 osg::PolygonMode* polygonMode;
292 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
294 if (mWireframe->getBoolValue())
295 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
296 osg::PolygonMode::LINE);
298 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
299 osg::PolygonMode::FILL);
302 SGSharedPtr<SGPropertyNode> mWireframe;
305 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
307 FGLightModelUpdateCallback() :
308 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
310 virtual void operator()(osg::StateAttribute* stateAttribute,
313 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
314 osg::LightModel* lightModel;
315 lightModel = static_cast<osg::LightModel*>(stateAttribute);
318 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
319 lightModel->setAmbientIntensity(l->scene_ambient().osg());
321 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
323 lightModel->setTwoSided(true);
324 lightModel->setLocalViewer(false);
326 if (mHighlights->getBoolValue()) {
327 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
329 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
333 SGSharedPtr<SGPropertyNode> mHighlights;
336 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
338 FGFogEnableUpdateCallback() :
339 mFogEnabled(fgGetNode("/sim/rendering/fog"))
341 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
343 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
344 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
346 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
350 SGSharedPtr<SGPropertyNode> mFogEnabled;
353 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
355 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
357 assert(dynamic_cast<SGUpdateVisitor*>(nv));
358 assert(dynamic_cast<osg::Fog*>(sa));
359 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
360 osg::Fog* fog = static_cast<osg::Fog*>(sa);
361 fog->setMode(osg::Fog::EXP2);
362 fog->setColor(updateVisitor->getFogColor().osg());
363 fog->setDensity(updateVisitor->getFogExp2Density());
367 // update callback for the switch node guarding that splash
368 class FGScenerySwitchCallback : public osg::NodeCallback {
370 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
372 assert(dynamic_cast<osg::Switch*>(node));
373 osg::Switch* sw = static_cast<osg::Switch*>(node);
375 double t = globals->get_sim_time_sec();
376 bool enabled = 0 < t;
377 sw->setValue(0, enabled);
387 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
388 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
390 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
392 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
394 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
396 FGRenderer::FGRenderer()
398 #ifdef FG_JPEG_SERVER
399 jpgRenderFrame = FGRenderer::update;
401 manipulator = new FGManipulator;
404 FGRenderer::~FGRenderer()
406 #ifdef FG_JPEG_SERVER
407 jpgRenderFrame = NULL;
411 // Initialize various GL/view parameters
412 // XXX This should be called "preinit" or something, as it initializes
413 // critical parts of the scene graph in addition to the splash screen.
415 FGRenderer::splashinit( void ) {
416 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
417 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
418 mRealRoot->addChild(fgCreateSplashNode());
419 mFrameStamp = viewer->getFrameStamp();
420 // Scene doesn't seem to pass the frame stamp to the update
421 // visitor automatically.
422 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
423 #ifdef UPDATE_VISITOR_IN_VIEWER
424 viewer->setUpdateVisitor(mUpdateVisitor.get());
426 osgViewer::Scene* scene = viewer->getScene();
427 scene->setUpdateVisitor(mUpdateVisitor.get());
432 FGRenderer::init( void ) {
433 // The viewer can call this before the graphics context is current
434 // in the main thread; indeed, in a multithreaded setup it might
435 // never be current in the main thread.
437 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
438 osg::initNotifyLevel();
440 // The number of polygon-offset "units" to place between layers. In
441 // principle, one is supposed to be enough. In practice, I find that
442 // my hardware/driver requires many more.
443 osg::PolygonOffset::setUnitsMultiplier(1);
444 osg::PolygonOffset::setFactorMultiplier(1);
446 // Go full screen if requested ...
447 if ( fgGetBool("/sim/startup/fullscreen") )
451 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
453 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
455 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
457 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
458 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
460 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
461 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
462 stateSet->setAttribute(new osg::BlendFunc);
463 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
465 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
467 // this will be set below
468 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
470 osg::Material* material = new osg::Material;
471 stateSet->setAttribute(material);
473 stateSet->setTextureAttribute(0, new osg::TexEnv);
474 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
476 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
477 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
478 stateSet->setAttribute(hint);
479 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
480 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
481 stateSet->setAttribute(hint);
482 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
483 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
484 stateSet->setAttribute(hint);
485 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
486 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
487 stateSet->setAttribute(hint);
488 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
489 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
490 stateSet->setAttribute(hint);
492 osg::Group* sceneGroup = new osg::Group;
493 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
494 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
496 //sceneGroup->addChild(thesky->getCloudRoot());
498 stateSet = sceneGroup->getOrCreateStateSet();
499 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
500 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
502 // need to update the light on every frame
503 osg::LightSource* lightSource = new osg::LightSource;
504 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
505 // relative because of CameraView being just a clever transform node
506 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
507 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
509 lightSource->addChild(sceneGroup);
510 lightSource->addChild(thesky->getPreRoot());
511 mRoot->addChild(lightSource);
513 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
514 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
515 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
516 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
517 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
519 // enable disable specular highlights.
520 // is the place where we might plug in an other fragment shader ...
521 osg::LightModel* lightModel = new osg::LightModel;
522 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
523 stateSet->setAttribute(lightModel);
525 // switch to enable wireframe
526 osg::PolygonMode* polygonMode = new osg::PolygonMode;
527 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
528 stateSet->setAttributeAndModes(polygonMode);
530 // scene fog handling
531 osg::Fog* fog = new osg::Fog;
532 fog->setUpdateCallback(new FGFogUpdateCallback);
533 stateSet->setAttributeAndModes(fog);
534 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
537 osg::Camera* guiCamera = new osg::Camera;
538 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
539 guiCamera->setClearMask(0);
540 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
541 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
542 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
543 guiCamera->setInheritanceMask(inheritanceMask);
544 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
545 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
546 osg::Geode* geode = new osg::Geode;
547 geode->addDrawable(new SGPuDrawable);
548 geode->addDrawable(new SGHUDAndPanelDrawable);
549 guiCamera->addChild(geode);
551 osg::Switch* sw = new osg::Switch;
552 sw->setUpdateCallback(new FGScenerySwitchCallback);
553 sw->addChild(mRoot.get());
554 viewPartition->addChild(sw);
555 viewPartition->addChild(thesky->getCloudRoot());
557 mRealRoot->addChild(viewPartition.get());
558 mRealRoot->addChild(FGCreateRedoutNode());
559 mRealRoot->addChild(guiCamera);
563 // Update all Visuals (redraws anything graphics related)
565 FGRenderer::update( bool refresh_camera_settings ) {
566 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
567 || fgGetBool("sim/sceneryloaded-override");
568 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
569 if ( idle_state < 1000 || !scenery_loaded ) {
570 fgSetDouble("/sim/startup/splash-alpha", 1.0);
572 // Keep resetting sim time while the sim is initializing
573 // the splash screen is now in the scenegraph
574 globals->set_sim_time_sec( 0.0 );
578 // Fade out the splash screen over the first three seconds.
579 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
580 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
582 bool skyblend = fgGetBool("/sim/rendering/skyblend");
583 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
584 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
585 bool distance_attenuation
586 = fgGetBool("/sim/rendering/distance-attenuation");
588 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
589 distance_attenuation );
591 static const SGPropertyNode *groundlevel_nearplane
592 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
594 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
597 double actual_visibility;
598 if (fgGetBool("/environment/clouds/status")) {
599 actual_visibility = thesky->get_visibility();
601 actual_visibility = fgGetDouble("/environment/visibility-m");
604 // idle_state is now 1000 meaning we've finished all our
605 // initializations and are running the main loop, so this will
606 // now work without seg faulting the system.
608 FGViewer *current__view = globals->get_current_view();
609 // Force update of center dependent values ...
610 current__view->set_dirty();
612 if ( refresh_camera_settings ) {
614 resize( fgGetInt("/sim/startup/xsize"),
615 fgGetInt("/sim/startup/ysize") );
617 SGVec3d position = current__view->getViewPosition();
618 SGQuatd attitude = current__view->getViewOrientation();
619 SGVec3d osgPosition = attitude.transform(-position);
621 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
622 manipulator->setPosition(position.osg());
623 manipulator->setAttitude(attitude.osg());
625 osg::Camera *camera = viewer->getCamera();
629 if ( fgGetBool("/sim/rendering/textures") ) {
630 SGVec4f clearColor(l->adj_fog_color());
631 camera->setClearColor(clearColor.osg());
634 SGVec4f clearColor(l->sky_color());
635 camera->setClearColor(clearColor.osg());
638 // update fog params if visibility has changed
639 double visibility_meters = fgGetDouble("/environment/visibility-m");
640 thesky->set_visibility(visibility_meters);
642 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
643 ( global_multi_loop * fgGetInt("/sim/speed-up") )
644 / (double)fgGetInt("/sim/model-hz") );
646 // update the sky dome
649 // The sun and moon distances are scaled down versions
650 // of the actual distance to get both the moon and the sun
651 // within the range of the far clip plane.
652 // Moon distance: 384,467 kilometers
653 // Sun distance: 150,000,000 kilometers
655 double sun_horiz_eff, moon_horiz_eff;
656 if (fgGetBool("/sim/rendering/horizon-effect")) {
657 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
658 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
660 sun_horiz_eff = moon_horiz_eff = 1.0;
663 static SGSkyState sstate;
665 sstate.view_pos = toVec3f(current__view->get_view_pos());
666 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
667 sstate.view_up = current__view->get_world_up();
668 sstate.lon = current__view->getLongitude_deg()
669 * SGD_DEGREES_TO_RADIANS;
670 sstate.lat = current__view->getLatitude_deg()
671 * SGD_DEGREES_TO_RADIANS;
672 sstate.alt = current__view->getAltitudeASL_ft()
674 sstate.spin = l->get_sun_rotation();
675 sstate.gst = globals->get_time_params()->getGst();
676 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
677 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
678 sstate.sun_dist = 50000.0 * sun_horiz_eff;
679 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
680 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
681 sstate.moon_dist = 40000.0 * moon_horiz_eff;
682 sstate.sun_angle = l->get_sun_angle();
686 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
687 << l->sky_color()[0] << " "
688 << l->sky_color()[1] << " "
689 << l->sky_color()[2] << " "
690 << l->sky_color()[3] );
691 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
692 << l->fog_color()[0] << " "
693 << l->fog_color()[1] << " "
694 << l->fog_color()[2] << " "
695 << l->fog_color()[3] );
696 SG_LOG( SG_GENERAL, SG_BULK,
697 " sun_angle = " << l->sun_angle
698 << " moon_angle = " << l->moon_angle );
701 static SGSkyColor scolor;
703 scolor.sky_color = SGVec3f(l->sky_color().data());
704 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
705 scolor.cloud_color = SGVec3f(l->cloud_color().data());
706 scolor.sun_angle = l->get_sun_angle();
707 scolor.moon_angle = l->get_moon_angle();
708 scolor.nplanets = globals->get_ephem()->getNumPlanets();
709 scolor.nstars = globals->get_ephem()->getNumStars();
710 scolor.planet_data = globals->get_ephem()->getPlanets();
711 scolor.star_data = globals->get_ephem()->getStars();
713 thesky->reposition( sstate, delta_time_sec );
714 thesky->repaint( scolor );
717 SG_LOG( SG_GENERAL, SG_BULK,
718 "thesky->reposition( view_pos = " << view_pos[0] << " "
719 << view_pos[1] << " " << view_pos[2] );
720 SG_LOG( SG_GENERAL, SG_BULK,
721 " zero_elev = " << zero_elev[0] << " "
722 << zero_elev[1] << " " << zero_elev[2]
723 << " lon = " << cur_fdm_state->get_Longitude()
724 << " lat = " << cur_fdm_state->get_Latitude() );
725 SG_LOG( SG_GENERAL, SG_BULK,
726 " sun_rot = " << l->get_sun_rotation
727 << " gst = " << SGTime::cur_time_params->getGst() );
728 SG_LOG( SG_GENERAL, SG_BULK,
729 " sun ra = " << globals->get_ephem()->getSunRightAscension()
730 << " sun dec = " << globals->get_ephem()->getSunDeclination()
731 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
732 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
736 // shadows->setupShadows(
737 // current__view->getLongitude_deg(),
738 // current__view->getLatitude_deg(),
739 // globals->get_time_params()->getGst(),
740 // globals->get_ephem()->getSunRightAscension(),
741 // globals->get_ephem()->getSunDeclination(),
742 // l->get_sun_angle());
746 // sgEnviro.setLight(l->adj_fog_color());
748 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
749 - current__view->getSGLocation()->get_cur_elev_m();
751 float scene_nearplane, scene_farplane;
752 // XXX Given that the own airplane model is part of the scene
753 // graph, should this business be ripped out? The near plane is
754 // ignored by setCameraParameters.
756 scene_nearplane = 10.0f;
757 scene_farplane = 120000.0f;
759 scene_nearplane = groundlevel_nearplane->getDoubleValue();
760 scene_farplane = 120000.0f;
762 setCameraParameters(current__view->get_v_fov(),
763 current__view->get_aspect_ratio(),
764 scene_nearplane, scene_farplane);
766 // sgEnviro.startOfFrame(current__view->get_view_pos(),
767 // current__view->get_world_up(),
768 // current__view->getLongitude_deg(),
769 // current__view->getLatitude_deg(),
770 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
774 // sgEnviro.drawLightning();
776 // double current_view_origin_airspeed_horiz_kt =
777 // fgGetDouble("/velocities/airspeed-kt", 0.0)
778 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
779 // * SGD_DEGREES_TO_RADIANS);
783 // shadows->endOfFrame();
785 // need to call the update visitor once
786 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
787 mUpdateVisitor->setViewData(current__view->getViewPosition(),
788 current__view->getViewOrientation());
789 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
790 mUpdateVisitor->setLight(direction, l->scene_ambient(),
791 l->scene_diffuse(), l->scene_specular(),
793 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
794 mUpdateVisitor->setVisibility(actual_visibility);
795 viewPartition->setVisibility(actual_visibility);
796 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
797 bool hotspots = fgGetBool("/sim/panel-hotspots");
798 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
799 & ~simgear::BACKGROUND_BIT);
800 cullMask |= simgear::GroundLightManager::instance()
801 ->getLightNodeMask(mUpdateVisitor.get());
803 cullMask |= simgear::PICK_BIT;
804 camera->setCullMask(cullMask);
806 for (int i = 0; i < viewer->getNumSlaves(); ++i)
807 viewer->getSlave(i)._camera->setCullMask(cullMask);
812 // options.cxx needs to see this for toggle_panel()
813 // Handle new window size or exposure
815 FGRenderer::resize( int width, int height ) {
818 if ( (!fgGetBool("/sim/virtual-cockpit"))
819 && fgPanelVisible() && idle_state == 1000 ) {
820 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
821 globals->get_current_panel()->getYOffset()) / 768.0);
826 static int lastwidth = 0;
827 static int lastheight = 0;
828 if (width != lastwidth)
829 fgSetInt("/sim/startup/xsize", lastwidth = width);
830 if (height != lastheight)
831 fgSetInt("/sim/startup/ysize", lastheight = height);
833 guiInitMouse(width, height);
836 FGViewMgr *viewmgr = globals->get_viewmgr();
838 for ( int i = 0; i < viewmgr->size(); ++i ) {
839 viewmgr->get_view(i)->
840 set_aspect_ratio((float)view_h / (float)width);
845 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
846 float zNear, float zFar)
849 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
850 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
856 FGRenderer::pick( unsigned x, unsigned y,
857 std::vector<SGSceneryPick>& pickList,
858 const osgGA::GUIEventAdapter* ea )
860 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
861 // wipe out the return ...
865 // just compute intersections in the viewers method ...
866 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
867 Intersections intersections;
868 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
870 Intersections::iterator hit;
871 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
872 const osg::NodePath& np = hit->nodePath;
873 osg::NodePath::const_reverse_iterator npi;
874 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
875 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
878 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
879 SGPickCallback* pickCallback = ud->getPickCallback(i);
882 SGSceneryPick sceneryPick;
883 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
884 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
885 sceneryPick.callback = pickCallback;
886 pickList.push_back(sceneryPick);
890 return !pickList.empty();
891 } else { // we can get called early ...
897 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
899 mRealRoot->addChild(camera);
903 fgDumpSceneGraphToFile(const char* filename)
905 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
909 fgDumpTerrainBranchToFile(const char* filename)
911 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
917 fgDumpNodeToFile(osg::Node* node, const char* filename)
919 return osgDB::writeNodeFile(*node, filename);
921 // end of renderer.cxx