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.
26 #include <simgear/compiler.h>
32 #include <osg/ref_ptr>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
36 #include <osg/CullFace>
42 #include <osg/LightModel>
43 #include <osg/LightSource>
44 #include <osg/NodeCallback>
46 #include <osg/PolygonMode>
47 #include <osg/PolygonOffset>
48 #include <osg/ShadeModel>
49 #include <osg/Version>
52 #include <osgUtil/SceneView>
53 #include <osgUtil/UpdateVisitor>
54 #include <osgUtil/IntersectVisitor>
55 #include <osgUtil/LineSegmentIntersector>
57 #include <osg/io_utils>
58 #include <osgDB/WriteFile>
59 #include <osgDB/ReadFile>
62 #include <simgear/math/SGMath.hxx>
63 #include <simgear/screen/extensions.hxx>
64 #include <simgear/scene/material/matlib.hxx>
65 #include <simgear/scene/model/animation.hxx>
66 #include <simgear/scene/model/placement.hxx>
67 #include <simgear/scene/util/SGUpdateVisitor.hxx>
68 #include <simgear/scene/util/RenderConstants.hxx>
69 #include <simgear/scene/tgdb/GroundLightManager.hxx>
70 #include <simgear/scene/tgdb/pt_lights.hxx>
71 #include <simgear/props/props.hxx>
72 #include <simgear/timing/sg_time.hxx>
73 #include <simgear/ephemeris/ephemeris.hxx>
74 #include <simgear/math/sg_random.h>
76 #include <simgear/screen/jpgfactory.hxx>
79 #include <simgear/environment/visual_enviro.hxx>
81 #include <Time/light.hxx>
82 #include <Time/light.hxx>
83 #include <Aircraft/aircraft.hxx>
84 #include <Cockpit/panel.hxx>
85 #include <Cockpit/cockpit.hxx>
86 #include <Cockpit/hud.hxx>
87 #include <Model/panelnode.hxx>
88 #include <Model/modelmgr.hxx>
89 #include <Model/acmodel.hxx>
90 #include <Scenery/scenery.hxx>
91 #include <Scenery/redout.hxx>
92 #include <Scenery/tilemgr.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Instrumentation/instrument_mgr.hxx>
95 #include <Instrumentation/HUD/HUD.hxx>
96 #include <Environment/precipitation_mgr.hxx>
98 #include <Include/general.hxx>
100 #include "renderer.hxx"
102 #include "ViewPartitionNode.hxx"
104 // XXX Make this go away when OSG 2.2 is released.
105 #if (FG_OSG_VERSION >= 21004)
106 #define UPDATE_VISITOR_IN_VIEWER 1
109 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
111 FGHintUpdateCallback(const char* configNode) :
112 mConfigNode(fgGetNode(configNode, true))
114 virtual void operator()(osg::StateAttribute* stateAttribute,
117 assert(dynamic_cast<osg::Hint*>(stateAttribute));
118 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
120 const char* value = mConfigNode->getStringValue();
122 hint->setMode(GL_DONT_CARE);
123 else if (0 == strcmp(value, "nicest"))
124 hint->setMode(GL_NICEST);
125 else if (0 == strcmp(value, "fastest"))
126 hint->setMode(GL_FASTEST);
128 hint->setMode(GL_DONT_CARE);
131 SGSharedPtr<SGPropertyNode> mConfigNode;
135 class SGPuDrawable : public osg::Drawable {
139 // Dynamic stuff, do not store geometry
140 setUseDisplayList(false);
142 osg::StateSet* stateSet = getOrCreateStateSet();
143 stateSet->setRenderBinDetails(1001, "RenderBin");
144 // speed optimization?
145 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
146 // We can do translucent menus, so why not. :-)
147 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
148 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
149 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
151 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
153 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
154 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
156 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
157 { drawImplementation(*renderInfo.getState()); }
158 void drawImplementation(osg::State& state) const
160 if (!fgOSIsMainContext(state.getGraphicsContext()))
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);
189 osg::StateSet* stateSet = getOrCreateStateSet();
190 stateSet->setRenderBinDetails(1000, "RenderBin");
192 // speed optimization?
193 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
194 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
195 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
196 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
197 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
199 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
201 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
202 { drawImplementation(*renderInfo.getState()); }
203 void drawImplementation(osg::State& state) const
205 if (!fgOSIsMainContext(state.getGraphicsContext()))
207 state.setActiveTextureUnit(0);
208 state.setClientActiveTextureUnit(0);
209 state.disableAllVertexArrays();
211 glPushAttrib(GL_ALL_ATTRIB_BITS);
212 glPushClientAttrib(~0u);
214 fgCockpitUpdate(&state);
216 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
217 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
220 // update the panel subsystem
221 if ( globals->get_current_panel() != NULL )
222 globals->get_current_panel()->update(state);
223 // We don't need a state here - can be safely removed when we can pick
232 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
233 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
238 class FGLightSourceUpdateCallback : public osg::NodeCallback {
240 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
242 assert(dynamic_cast<osg::LightSource*>(node));
243 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
244 osg::Light* light = lightSource->getLight();
246 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
247 light->setAmbient(l->scene_ambient().osg());
248 light->setDiffuse(l->scene_diffuse().osg());
249 light->setSpecular(l->scene_specular().osg());
250 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
251 light->setPosition(position.osg());
252 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
253 light->setDirection(direction.osg());
254 light->setSpotExponent(0);
255 light->setSpotCutoff(180);
256 light->setConstantAttenuation(1);
257 light->setLinearAttenuation(0);
258 light->setQuadraticAttenuation(0);
264 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
266 FGWireFrameModeUpdateCallback() :
267 mWireframe(fgGetNode("/sim/rendering/wireframe"))
269 virtual void operator()(osg::StateAttribute* stateAttribute,
272 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
273 osg::PolygonMode* polygonMode;
274 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
276 if (mWireframe->getBoolValue())
277 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
278 osg::PolygonMode::LINE);
280 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
281 osg::PolygonMode::FILL);
284 SGSharedPtr<SGPropertyNode> mWireframe;
287 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
289 FGLightModelUpdateCallback() :
290 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
292 virtual void operator()(osg::StateAttribute* stateAttribute,
295 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
296 osg::LightModel* lightModel;
297 lightModel = static_cast<osg::LightModel*>(stateAttribute);
300 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
301 lightModel->setAmbientIntensity(l->scene_ambient().osg());
303 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
305 lightModel->setTwoSided(true);
306 lightModel->setLocalViewer(false);
308 if (mHighlights->getBoolValue()) {
309 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
311 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
315 SGSharedPtr<SGPropertyNode> mHighlights;
318 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
320 FGFogEnableUpdateCallback() :
321 mFogEnabled(fgGetNode("/sim/rendering/fog"))
323 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
325 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
326 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
328 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
332 SGSharedPtr<SGPropertyNode> mFogEnabled;
335 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
337 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
339 assert(dynamic_cast<SGUpdateVisitor*>(nv));
340 assert(dynamic_cast<osg::Fog*>(sa));
341 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
342 osg::Fog* fog = static_cast<osg::Fog*>(sa);
343 fog->setMode(osg::Fog::EXP2);
344 fog->setColor(updateVisitor->getFogColor().osg());
345 fog->setDensity(updateVisitor->getFogExp2Density());
349 // update callback for the switch node guarding that splash
350 class FGScenerySwitchCallback : public osg::NodeCallback {
352 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
354 assert(dynamic_cast<osg::Switch*>(node));
355 osg::Switch* sw = static_cast<osg::Switch*>(node);
357 double t = globals->get_sim_time_sec();
358 bool enabled = 0 < t;
359 sw->setValue(0, enabled);
369 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
370 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
372 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
374 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
376 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
378 FGRenderer::FGRenderer()
380 #ifdef FG_JPEG_SERVER
381 jpgRenderFrame = FGRenderer::update;
383 manipulator = new FGManipulator;
386 FGRenderer::~FGRenderer()
388 #ifdef FG_JPEG_SERVER
389 jpgRenderFrame = NULL;
393 // Initialize various GL/view parameters
394 // XXX This should be called "preinit" or something, as it initializes
395 // critical parts of the scene graph in addition to the splash screen.
397 FGRenderer::splashinit( void ) {
398 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
399 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
400 mRealRoot->addChild(fgCreateSplashNode());
401 mFrameStamp = viewer->getFrameStamp();
402 // Scene doesn't seem to pass the frame stamp to the update
403 // visitor automatically.
404 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
405 #ifdef UPDATE_VISITOR_IN_VIEWER
406 viewer->setUpdateVisitor(mUpdateVisitor.get());
408 osgViewer::Scene* scene = viewer->getScene();
409 scene->setUpdateVisitor(mUpdateVisitor.get());
415 // Create a slave camera that will be used to render a fixed GUI-like
418 makeSlaveCamera(osg::Camera::RenderOrder renderOrder, int orderNum)
421 Camera* camera = new osg::Camera;
422 GraphicsContext *gc = fgOSGetMainContext();
424 camera->setRenderOrder(renderOrder, orderNum);
425 camera->setClearMask(0);
426 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
427 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
428 | CullSettings::CULLING_MODE));
429 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
430 camera->setCullingMode(osg::CullSettings::NO_CULLING);
431 camera->setGraphicsContext(gc);
432 // Establish an initial viewport. This may be altered,
433 // particularly when drawing a 2d panel.
434 const GraphicsContext::Traits *traits = gc->getTraits();
435 camera->setViewport(new Viewport(0, 0, traits->width, traits->height));
436 camera->setProjectionResizePolicy(Camera::FIXED);
437 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
438 camera->setAllowEventFocus(false);
439 globals->get_renderer()->getViewer()->addSlave(camera, false);
446 FGRenderer::init( void )
448 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
449 osg::initNotifyLevel();
451 // The number of polygon-offset "units" to place between layers. In
452 // principle, one is supposed to be enough. In practice, I find that
453 // my hardware/driver requires many more.
454 osg::PolygonOffset::setUnitsMultiplier(1);
455 osg::PolygonOffset::setFactorMultiplier(1);
457 // Go full screen if requested ...
458 if ( fgGetBool("/sim/startup/fullscreen") )
462 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
464 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
466 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
468 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
469 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
471 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
472 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
473 stateSet->setAttribute(new osg::BlendFunc);
474 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
476 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
478 // this will be set below
479 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
481 osg::Material* material = new osg::Material;
482 stateSet->setAttribute(material);
484 stateSet->setTextureAttribute(0, new osg::TexEnv);
485 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
487 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
488 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
489 stateSet->setAttribute(hint);
490 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
491 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
492 stateSet->setAttribute(hint);
493 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
494 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
495 stateSet->setAttribute(hint);
496 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
497 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
498 stateSet->setAttribute(hint);
499 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
500 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
501 stateSet->setAttribute(hint);
503 osg::Group* sceneGroup = new osg::Group;
504 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
505 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
507 //sceneGroup->addChild(thesky->getCloudRoot());
509 stateSet = sceneGroup->getOrCreateStateSet();
510 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
511 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
513 // need to update the light on every frame
514 osg::LightSource* lightSource = new osg::LightSource;
515 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
516 // relative because of CameraView being just a clever transform node
517 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
518 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
520 lightSource->addChild(sceneGroup);
521 lightSource->addChild(thesky->getPreRoot());
522 mRoot->addChild(lightSource);
524 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
525 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
526 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
527 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
528 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
530 // enable disable specular highlights.
531 // is the place where we might plug in an other fragment shader ...
532 osg::LightModel* lightModel = new osg::LightModel;
533 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
534 stateSet->setAttribute(lightModel);
536 // switch to enable wireframe
537 osg::PolygonMode* polygonMode = new osg::PolygonMode;
538 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
539 stateSet->setAttributeAndModes(polygonMode);
541 // scene fog handling
542 osg::Fog* fog = new osg::Fog;
543 fog->setUpdateCallback(new FGFogUpdateCallback);
544 stateSet->setAttributeAndModes(fog);
545 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
548 osg::Camera* guiCamera = makeSlaveCamera(osg::Camera::POST_RENDER, 100);
549 guiCamera->setName("GUI");
550 osg::Geode* geode = new osg::Geode;
551 geode->addDrawable(new SGPuDrawable);
552 geode->addDrawable(new SGHUDAndPanelDrawable);
553 guiCamera->addChild(geode);
555 osg::Switch* sw = new osg::Switch;
556 sw->setUpdateCallback(new FGScenerySwitchCallback);
557 sw->addChild(mRoot.get());
558 viewPartition->addChild(sw);
559 viewPartition->addChild(thesky->getCloudRoot());
561 mRealRoot->addChild(viewPartition.get());
562 mRealRoot->addChild(FGCreateRedoutNode());
566 // Update all Visuals (redraws anything graphics related)
568 FGRenderer::update( bool refresh_camera_settings ) {
569 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
570 || fgGetBool("sim/sceneryloaded-override");
571 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
572 if ( idle_state < 1000 || !scenery_loaded ) {
573 fgSetDouble("/sim/startup/splash-alpha", 1.0);
575 // Keep resetting sim time while the sim is initializing
576 // the splash screen is now in the scenegraph
577 globals->set_sim_time_sec( 0.0 );
581 // Fade out the splash screen over the first three seconds.
582 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
583 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
585 bool skyblend = fgGetBool("/sim/rendering/skyblend");
586 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
587 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
588 bool distance_attenuation
589 = fgGetBool("/sim/rendering/distance-attenuation");
591 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
592 distance_attenuation );
594 static const SGPropertyNode *groundlevel_nearplane
595 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
597 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
600 double actual_visibility;
601 if (fgGetBool("/environment/clouds/status")) {
602 actual_visibility = thesky->get_visibility();
604 actual_visibility = fgGetDouble("/environment/visibility-m");
607 // idle_state is now 1000 meaning we've finished all our
608 // initializations and are running the main loop, so this will
609 // now work without seg faulting the system.
611 FGViewer *current__view = globals->get_current_view();
612 // Force update of center dependent values ...
613 current__view->set_dirty();
615 if ( refresh_camera_settings ) {
617 resize( fgGetInt("/sim/startup/xsize"),
618 fgGetInt("/sim/startup/ysize") );
620 SGVec3d position = current__view->getViewPosition();
621 SGQuatd attitude = current__view->getViewOrientation();
622 SGVec3d osgPosition = attitude.transform(-position);
624 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
625 manipulator->setPosition(position.osg());
626 manipulator->setAttitude(attitude.osg());
628 osg::Camera *camera = viewer->getCamera();
632 if ( fgGetBool("/sim/rendering/textures") ) {
633 SGVec4f clearColor(l->adj_fog_color());
634 camera->setClearColor(clearColor.osg());
637 SGVec4f clearColor(l->sky_color());
638 camera->setClearColor(clearColor.osg());
641 // update fog params if visibility has changed
642 double visibility_meters = fgGetDouble("/environment/visibility-m");
643 thesky->set_visibility(visibility_meters);
645 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
646 ( global_multi_loop * fgGetInt("/sim/speed-up") )
647 / (double)fgGetInt("/sim/model-hz") );
649 // update the sky dome
652 // The sun and moon distances are scaled down versions
653 // of the actual distance to get both the moon and the sun
654 // within the range of the far clip plane.
655 // Moon distance: 384,467 kilometers
656 // Sun distance: 150,000,000 kilometers
658 double sun_horiz_eff, moon_horiz_eff;
659 if (fgGetBool("/sim/rendering/horizon-effect")) {
660 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
661 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
663 sun_horiz_eff = moon_horiz_eff = 1.0;
666 static SGSkyState sstate;
668 sstate.view_pos = toVec3f(current__view->get_view_pos());
669 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
670 sstate.view_up = current__view->get_world_up();
671 sstate.lon = current__view->getLongitude_deg()
672 * SGD_DEGREES_TO_RADIANS;
673 sstate.lat = current__view->getLatitude_deg()
674 * SGD_DEGREES_TO_RADIANS;
675 sstate.alt = current__view->getAltitudeASL_ft()
677 sstate.spin = l->get_sun_rotation();
678 sstate.gst = globals->get_time_params()->getGst();
679 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
680 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
681 sstate.sun_dist = 50000.0 * sun_horiz_eff;
682 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
683 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
684 sstate.moon_dist = 40000.0 * moon_horiz_eff;
685 sstate.sun_angle = l->get_sun_angle();
689 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
690 << l->sky_color()[0] << " "
691 << l->sky_color()[1] << " "
692 << l->sky_color()[2] << " "
693 << l->sky_color()[3] );
694 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
695 << l->fog_color()[0] << " "
696 << l->fog_color()[1] << " "
697 << l->fog_color()[2] << " "
698 << l->fog_color()[3] );
699 SG_LOG( SG_GENERAL, SG_BULK,
700 " sun_angle = " << l->sun_angle
701 << " moon_angle = " << l->moon_angle );
704 static SGSkyColor scolor;
706 scolor.sky_color = SGVec3f(l->sky_color().data());
707 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
708 scolor.cloud_color = SGVec3f(l->cloud_color().data());
709 scolor.sun_angle = l->get_sun_angle();
710 scolor.moon_angle = l->get_moon_angle();
711 scolor.nplanets = globals->get_ephem()->getNumPlanets();
712 scolor.nstars = globals->get_ephem()->getNumStars();
713 scolor.planet_data = globals->get_ephem()->getPlanets();
714 scolor.star_data = globals->get_ephem()->getStars();
716 thesky->reposition( sstate, delta_time_sec );
717 thesky->repaint( scolor );
720 SG_LOG( SG_GENERAL, SG_BULK,
721 "thesky->reposition( view_pos = " << view_pos[0] << " "
722 << view_pos[1] << " " << view_pos[2] );
723 SG_LOG( SG_GENERAL, SG_BULK,
724 " zero_elev = " << zero_elev[0] << " "
725 << zero_elev[1] << " " << zero_elev[2]
726 << " lon = " << cur_fdm_state->get_Longitude()
727 << " lat = " << cur_fdm_state->get_Latitude() );
728 SG_LOG( SG_GENERAL, SG_BULK,
729 " sun_rot = " << l->get_sun_rotation
730 << " gst = " << SGTime::cur_time_params->getGst() );
731 SG_LOG( SG_GENERAL, SG_BULK,
732 " sun ra = " << globals->get_ephem()->getSunRightAscension()
733 << " sun dec = " << globals->get_ephem()->getSunDeclination()
734 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
735 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
739 // shadows->setupShadows(
740 // current__view->getLongitude_deg(),
741 // current__view->getLatitude_deg(),
742 // globals->get_time_params()->getGst(),
743 // globals->get_ephem()->getSunRightAscension(),
744 // globals->get_ephem()->getSunDeclination(),
745 // l->get_sun_angle());
749 // sgEnviro.setLight(l->adj_fog_color());
751 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
752 - current__view->getSGLocation()->get_cur_elev_m();
754 float scene_nearplane, scene_farplane;
755 // XXX Given that the own airplane model is part of the scene
756 // graph, should this business be ripped out? The near plane is
757 // ignored by setCameraParameters.
759 scene_nearplane = 10.0f;
760 scene_farplane = 120000.0f;
762 scene_nearplane = groundlevel_nearplane->getDoubleValue();
763 scene_farplane = 120000.0f;
765 setCameraParameters(current__view->get_v_fov(),
766 current__view->get_aspect_ratio(),
767 scene_nearplane, scene_farplane);
769 // sgEnviro.startOfFrame(current__view->get_view_pos(),
770 // current__view->get_world_up(),
771 // current__view->getLongitude_deg(),
772 // current__view->getLatitude_deg(),
773 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
777 // sgEnviro.drawLightning();
779 // double current_view_origin_airspeed_horiz_kt =
780 // fgGetDouble("/velocities/airspeed-kt", 0.0)
781 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
782 // * SGD_DEGREES_TO_RADIANS);
786 // shadows->endOfFrame();
788 // need to call the update visitor once
789 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
790 mUpdateVisitor->setViewData(current__view->getViewPosition(),
791 current__view->getViewOrientation());
792 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
793 mUpdateVisitor->setLight(direction, l->scene_ambient(),
794 l->scene_diffuse(), l->scene_specular(),
796 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
797 mUpdateVisitor->setVisibility(actual_visibility);
798 viewPartition->setVisibility(actual_visibility);
799 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
800 bool hotspots = fgGetBool("/sim/panel-hotspots");
801 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
802 & ~simgear::BACKGROUND_BIT);
803 cullMask |= simgear::GroundLightManager::instance()
804 ->getLightNodeMask(mUpdateVisitor.get());
806 cullMask |= simgear::PICK_BIT;
807 camera->setCullMask(cullMask);
809 for (int i = 0; i < viewer->getNumSlaves(); ++i)
810 viewer->getSlave(i)._camera->setCullMask(cullMask);
815 // options.cxx needs to see this for toggle_panel()
816 // Handle new window size or exposure
818 FGRenderer::resize( int width, int height ) {
821 if ( (!fgGetBool("/sim/virtual-cockpit"))
822 && fgPanelVisible() && idle_state == 1000 ) {
823 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
824 globals->get_current_panel()->getYOffset()) / 768.0);
829 static int lastwidth = 0;
830 static int lastheight = 0;
831 if (width != lastwidth)
832 fgSetInt("/sim/startup/xsize", lastwidth = width);
833 if (height != lastheight)
834 fgSetInt("/sim/startup/ysize", lastheight = height);
836 guiInitMouse(width, height);
839 FGViewMgr *viewmgr = globals->get_viewmgr();
841 for ( int i = 0; i < viewmgr->size(); ++i ) {
842 viewmgr->get_view(i)->
843 set_aspect_ratio((float)view_h / (float)width);
848 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
849 float zNear, float zFar)
852 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
853 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
859 FGRenderer::pick( unsigned x, unsigned y,
860 std::vector<SGSceneryPick>& pickList,
861 const osgGA::GUIEventAdapter* ea )
863 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
864 // wipe out the return ...
868 // just compute intersections in the viewers method ...
869 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
870 Intersections intersections;
871 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
873 Intersections::iterator hit;
874 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
875 const osg::NodePath& np = hit->nodePath;
876 osg::NodePath::const_reverse_iterator npi;
877 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
878 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
881 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
882 SGPickCallback* pickCallback = ud->getPickCallback(i);
885 SGSceneryPick sceneryPick;
886 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
887 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
888 sceneryPick.callback = pickCallback;
889 pickList.push_back(sceneryPick);
893 return !pickList.empty();
894 } else { // we can get called early ...
900 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
902 mRealRoot->addChild(camera);
906 fgDumpSceneGraphToFile(const char* filename)
908 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
912 fgDumpTerrainBranchToFile(const char* filename)
914 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
920 fgDumpNodeToFile(osg::Node* node, const char* filename)
922 return osgDB::writeNodeFile(*node, filename);
924 // end of renderer.cxx