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>
28 #include <osg/ref_ptr>
29 #include <osg/AlphaFunc>
30 #include <osg/BlendFunc>
32 #include <osg/CullFace>
38 #include <osg/LightModel>
39 #include <osg/LightSource>
40 #include <osg/NodeCallback>
42 #include <osg/PolygonMode>
43 #include <osg/PolygonOffset>
44 #include <osg/ShadeModel>
45 #include <osg/Version>
48 #include <osgUtil/SceneView>
49 #include <osgUtil/UpdateVisitor>
50 #include <osgUtil/IntersectVisitor>
51 #include <osgUtil/LineSegmentIntersector>
53 #include <osg/io_utils>
54 #include <osgDB/WriteFile>
55 #include <osgDB/ReadFile>
58 #include <simgear/math/SGMath.hxx>
59 #include <simgear/screen/extensions.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/util/SGUpdateVisitor.hxx>
64 #include <simgear/scene/util/RenderConstants.hxx>
65 #include <simgear/scene/tgdb/GroundLightManager.hxx>
66 #include <simgear/scene/tgdb/pt_lights.hxx>
67 #include <simgear/props/props.hxx>
68 #include <simgear/timing/sg_time.hxx>
69 #include <simgear/ephemeris/ephemeris.hxx>
70 #include <simgear/math/sg_random.h>
72 #include <simgear/screen/jpgfactory.hxx>
75 #include <simgear/environment/visual_enviro.hxx>
77 #include <Time/light.hxx>
78 #include <Time/light.hxx>
79 #include <Aircraft/aircraft.hxx>
80 #include <Cockpit/panel.hxx>
81 #include <Cockpit/cockpit.hxx>
82 #include <Cockpit/hud.hxx>
83 #include <Model/panelnode.hxx>
84 #include <Model/modelmgr.hxx>
85 #include <Model/acmodel.hxx>
86 #include <Scenery/scenery.hxx>
87 #include <Scenery/redout.hxx>
88 #include <Scenery/tilemgr.hxx>
89 #include <GUI/new_gui.hxx>
90 #include <Instrumentation/instrument_mgr.hxx>
91 #include <Instrumentation/HUD/HUD.hxx>
92 #include <Environment/precipitation_mgr.hxx>
94 #include <Include/general.hxx>
96 #include "renderer.hxx"
98 #include "ViewPartitionNode.hxx"
100 // XXX Make this go away when OSG 2.2 is released.
101 #if (FG_OSG_VERSION >= 21004)
102 #define UPDATE_VISITOR_IN_VIEWER 1
105 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
107 FGHintUpdateCallback(const char* configNode) :
108 mConfigNode(fgGetNode(configNode, true))
110 virtual void operator()(osg::StateAttribute* stateAttribute,
113 assert(dynamic_cast<osg::Hint*>(stateAttribute));
114 osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
116 const char* value = mConfigNode->getStringValue();
118 hint->setMode(GL_DONT_CARE);
119 else if (0 == strcmp(value, "nicest"))
120 hint->setMode(GL_NICEST);
121 else if (0 == strcmp(value, "fastest"))
122 hint->setMode(GL_FASTEST);
124 hint->setMode(GL_DONT_CARE);
127 SGSharedPtr<SGPropertyNode> mConfigNode;
131 class SGPuDrawable : public osg::Drawable {
135 // Dynamic stuff, do not store geometry
136 setUseDisplayList(false);
138 osg::StateSet* stateSet = getOrCreateStateSet();
139 stateSet->setRenderBinDetails(1001, "RenderBin");
140 // speed optimization?
141 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
142 // We can do translucent menus, so why not. :-)
143 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
144 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
145 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
147 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
149 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
150 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
152 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
153 { drawImplementation(*renderInfo.getState()); }
154 void drawImplementation(osg::State& state) const
156 if (!fgOSIsMainContext(state.getGraphicsContext()))
158 state.setActiveTextureUnit(0);
159 state.setClientActiveTextureUnit(0);
161 state.disableAllVertexArrays();
163 glPushAttrib(GL_ALL_ATTRIB_BITS);
164 glPushClientAttrib(~0u);
172 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
173 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
178 class SGHUDAndPanelDrawable : public osg::Drawable {
180 SGHUDAndPanelDrawable()
182 // Dynamic stuff, do not store geometry
183 setUseDisplayList(false);
185 osg::StateSet* stateSet = getOrCreateStateSet();
186 stateSet->setRenderBinDetails(1000, "RenderBin");
188 // speed optimization?
189 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
190 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
191 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
192 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
193 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
195 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
197 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
198 { drawImplementation(*renderInfo.getState()); }
199 void drawImplementation(osg::State& state) const
201 if (!fgOSIsMainContext(state.getGraphicsContext()))
203 state.setActiveTextureUnit(0);
204 state.setClientActiveTextureUnit(0);
205 state.disableAllVertexArrays();
207 glPushAttrib(GL_ALL_ATTRIB_BITS);
208 glPushClientAttrib(~0u);
210 fgCockpitUpdate(&state);
212 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
213 HUD *hud = static_cast<HUD*>(instr->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 {
236 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
238 assert(dynamic_cast<osg::LightSource*>(node));
239 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
240 osg::Light* light = lightSource->getLight();
242 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
243 light->setAmbient(l->scene_ambient().osg());
244 light->setDiffuse(l->scene_diffuse().osg());
245 light->setSpecular(l->scene_specular().osg());
246 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
247 light->setPosition(position.osg());
248 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
249 light->setDirection(direction.osg());
250 light->setSpotExponent(0);
251 light->setSpotCutoff(180);
252 light->setConstantAttenuation(1);
253 light->setLinearAttenuation(0);
254 light->setQuadraticAttenuation(0);
260 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
262 FGWireFrameModeUpdateCallback() :
263 mWireframe(fgGetNode("/sim/rendering/wireframe"))
265 virtual void operator()(osg::StateAttribute* stateAttribute,
268 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
269 osg::PolygonMode* polygonMode;
270 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
272 if (mWireframe->getBoolValue())
273 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
274 osg::PolygonMode::LINE);
276 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
277 osg::PolygonMode::FILL);
280 SGSharedPtr<SGPropertyNode> mWireframe;
283 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
285 FGLightModelUpdateCallback() :
286 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
288 virtual void operator()(osg::StateAttribute* stateAttribute,
291 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
292 osg::LightModel* lightModel;
293 lightModel = static_cast<osg::LightModel*>(stateAttribute);
296 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
297 lightModel->setAmbientIntensity(l->scene_ambient().osg());
299 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
301 lightModel->setTwoSided(true);
302 lightModel->setLocalViewer(false);
304 if (mHighlights->getBoolValue()) {
305 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
307 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
311 SGSharedPtr<SGPropertyNode> mHighlights;
314 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
316 FGFogEnableUpdateCallback() :
317 mFogEnabled(fgGetNode("/sim/rendering/fog"))
319 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
321 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
322 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
324 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
328 SGSharedPtr<SGPropertyNode> mFogEnabled;
331 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
333 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
335 assert(dynamic_cast<SGUpdateVisitor*>(nv));
336 assert(dynamic_cast<osg::Fog*>(sa));
337 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
338 osg::Fog* fog = static_cast<osg::Fog*>(sa);
339 fog->setMode(osg::Fog::EXP2);
340 fog->setColor(updateVisitor->getFogColor().osg());
341 fog->setDensity(updateVisitor->getFogExp2Density());
345 // update callback for the switch node guarding that splash
346 class FGScenerySwitchCallback : public osg::NodeCallback {
348 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
350 assert(dynamic_cast<osg::Switch*>(node));
351 osg::Switch* sw = static_cast<osg::Switch*>(node);
353 double t = globals->get_sim_time_sec();
354 bool enabled = 0 < t;
355 sw->setValue(0, enabled);
365 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
366 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
368 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
370 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
372 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
374 FGRenderer::FGRenderer()
376 #ifdef FG_JPEG_SERVER
377 jpgRenderFrame = FGRenderer::update;
379 manipulator = new FGManipulator;
382 FGRenderer::~FGRenderer()
384 #ifdef FG_JPEG_SERVER
385 jpgRenderFrame = NULL;
389 // Initialize various GL/view parameters
390 // XXX This should be called "preinit" or something, as it initializes
391 // critical parts of the scene graph in addition to the splash screen.
393 FGRenderer::splashinit( void ) {
394 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
395 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
396 mRealRoot->addChild(fgCreateSplashNode());
397 mFrameStamp = viewer->getFrameStamp();
398 // Scene doesn't seem to pass the frame stamp to the update
399 // visitor automatically.
400 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
401 #ifdef UPDATE_VISITOR_IN_VIEWER
402 viewer->setUpdateVisitor(mUpdateVisitor.get());
404 osgViewer::Scene* scene = viewer->getScene();
405 scene->setUpdateVisitor(mUpdateVisitor.get());
411 // Create a slave camera that will be used to render a fixed GUI-like
414 makeSlaveCamera(osg::Camera::RenderOrder renderOrder, int orderNum)
417 Camera* camera = new osg::Camera;
418 GraphicsContext *gc = fgOSGetMainContext();
420 camera->setRenderOrder(renderOrder, orderNum);
421 camera->setClearMask(0);
422 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
423 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
424 | CullSettings::CULLING_MODE));
425 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
426 camera->setCullingMode(osg::CullSettings::NO_CULLING);
427 camera->setGraphicsContext(gc);
428 // Establish an initial viewport. This may be altered,
429 // particularly when drawing a 2d panel.
430 const GraphicsContext::Traits *traits = gc->getTraits();
431 camera->setViewport(new Viewport(0, 0, traits->width, traits->height));
432 camera->setProjectionResizePolicy(Camera::FIXED);
433 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
434 camera->setAllowEventFocus(false);
435 globals->get_renderer()->getViewer()->addSlave(camera, false);
442 FGRenderer::init( void )
444 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
445 osg::initNotifyLevel();
447 // The number of polygon-offset "units" to place between layers. In
448 // principle, one is supposed to be enough. In practice, I find that
449 // my hardware/driver requires many more.
450 osg::PolygonOffset::setUnitsMultiplier(1);
451 osg::PolygonOffset::setFactorMultiplier(1);
453 // Go full screen if requested ...
454 if ( fgGetBool("/sim/startup/fullscreen") )
458 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
460 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
462 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
464 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
465 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
467 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
468 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
469 stateSet->setAttribute(new osg::BlendFunc);
470 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
472 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
474 // this will be set below
475 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
477 osg::Material* material = new osg::Material;
478 stateSet->setAttribute(material);
480 stateSet->setTextureAttribute(0, new osg::TexEnv);
481 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
483 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
484 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
485 stateSet->setAttribute(hint);
486 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
487 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
488 stateSet->setAttribute(hint);
489 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
490 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
491 stateSet->setAttribute(hint);
492 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
493 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
494 stateSet->setAttribute(hint);
495 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
496 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
497 stateSet->setAttribute(hint);
499 osg::Group* sceneGroup = new osg::Group;
500 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
501 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
503 //sceneGroup->addChild(thesky->getCloudRoot());
505 stateSet = sceneGroup->getOrCreateStateSet();
506 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
507 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
509 // need to update the light on every frame
510 osg::LightSource* lightSource = new osg::LightSource;
511 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
512 // relative because of CameraView being just a clever transform node
513 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
514 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
516 lightSource->addChild(sceneGroup);
517 lightSource->addChild(thesky->getPreRoot());
518 mRoot->addChild(lightSource);
520 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
521 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
522 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
523 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
524 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
526 // enable disable specular highlights.
527 // is the place where we might plug in an other fragment shader ...
528 osg::LightModel* lightModel = new osg::LightModel;
529 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
530 stateSet->setAttribute(lightModel);
532 // switch to enable wireframe
533 osg::PolygonMode* polygonMode = new osg::PolygonMode;
534 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
535 stateSet->setAttributeAndModes(polygonMode);
537 // scene fog handling
538 osg::Fog* fog = new osg::Fog;
539 fog->setUpdateCallback(new FGFogUpdateCallback);
540 stateSet->setAttributeAndModes(fog);
541 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
544 osg::Camera* guiCamera = makeSlaveCamera(osg::Camera::POST_RENDER, 100);
545 guiCamera->setName("GUI");
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());
562 // Update all Visuals (redraws anything graphics related)
564 FGRenderer::update( bool refresh_camera_settings ) {
565 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
566 || fgGetBool("sim/sceneryloaded-override");
567 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
568 if ( idle_state < 1000 || !scenery_loaded ) {
569 fgSetDouble("/sim/startup/splash-alpha", 1.0);
571 // Keep resetting sim time while the sim is initializing
572 // the splash screen is now in the scenegraph
573 globals->set_sim_time_sec( 0.0 );
577 // Fade out the splash screen over the first three seconds.
578 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
579 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
581 bool skyblend = fgGetBool("/sim/rendering/skyblend");
582 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
583 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
584 bool distance_attenuation
585 = fgGetBool("/sim/rendering/distance-attenuation");
587 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
588 distance_attenuation );
590 static const SGPropertyNode *groundlevel_nearplane
591 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
593 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
596 double actual_visibility;
597 if (fgGetBool("/environment/clouds/status")) {
598 actual_visibility = thesky->get_visibility();
600 actual_visibility = fgGetDouble("/environment/visibility-m");
603 // idle_state is now 1000 meaning we've finished all our
604 // initializations and are running the main loop, so this will
605 // now work without seg faulting the system.
607 FGViewer *current__view = globals->get_current_view();
608 // Force update of center dependent values ...
609 current__view->set_dirty();
611 if ( refresh_camera_settings ) {
613 resize( fgGetInt("/sim/startup/xsize"),
614 fgGetInt("/sim/startup/ysize") );
616 SGVec3d position = current__view->getViewPosition();
617 SGQuatd attitude = current__view->getViewOrientation();
618 SGVec3d osgPosition = attitude.transform(-position);
620 FGManipulator *manipulator = globals->get_renderer()->getManipulator();
621 manipulator->setPosition(position.osg());
622 manipulator->setAttitude(attitude.osg());
624 osg::Camera *camera = viewer->getCamera();
628 if ( fgGetBool("/sim/rendering/textures") ) {
629 SGVec4f clearColor(l->adj_fog_color());
630 camera->setClearColor(clearColor.osg());
633 SGVec4f clearColor(l->sky_color());
634 camera->setClearColor(clearColor.osg());
637 // update fog params if visibility has changed
638 double visibility_meters = fgGetDouble("/environment/visibility-m");
639 thesky->set_visibility(visibility_meters);
641 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
642 ( global_multi_loop * fgGetInt("/sim/speed-up") )
643 / (double)fgGetInt("/sim/model-hz") );
645 // update the sky dome
648 // The sun and moon distances are scaled down versions
649 // of the actual distance to get both the moon and the sun
650 // within the range of the far clip plane.
651 // Moon distance: 384,467 kilometers
652 // Sun distance: 150,000,000 kilometers
654 double sun_horiz_eff, moon_horiz_eff;
655 if (fgGetBool("/sim/rendering/horizon-effect")) {
656 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
657 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
659 sun_horiz_eff = moon_horiz_eff = 1.0;
662 static SGSkyState sstate;
664 sstate.view_pos = toVec3f(current__view->get_view_pos());
665 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
666 sstate.view_up = current__view->get_world_up();
667 sstate.lon = current__view->getLongitude_deg()
668 * SGD_DEGREES_TO_RADIANS;
669 sstate.lat = current__view->getLatitude_deg()
670 * SGD_DEGREES_TO_RADIANS;
671 sstate.alt = current__view->getAltitudeASL_ft()
673 sstate.spin = l->get_sun_rotation();
674 sstate.gst = globals->get_time_params()->getGst();
675 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
676 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
677 sstate.sun_dist = 50000.0 * sun_horiz_eff;
678 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
679 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
680 sstate.moon_dist = 40000.0 * moon_horiz_eff;
681 sstate.sun_angle = l->get_sun_angle();
685 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
686 << l->sky_color()[0] << " "
687 << l->sky_color()[1] << " "
688 << l->sky_color()[2] << " "
689 << l->sky_color()[3] );
690 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
691 << l->fog_color()[0] << " "
692 << l->fog_color()[1] << " "
693 << l->fog_color()[2] << " "
694 << l->fog_color()[3] );
695 SG_LOG( SG_GENERAL, SG_BULK,
696 " sun_angle = " << l->sun_angle
697 << " moon_angle = " << l->moon_angle );
700 static SGSkyColor scolor;
702 scolor.sky_color = SGVec3f(l->sky_color().data());
703 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
704 scolor.cloud_color = SGVec3f(l->cloud_color().data());
705 scolor.sun_angle = l->get_sun_angle();
706 scolor.moon_angle = l->get_moon_angle();
707 scolor.nplanets = globals->get_ephem()->getNumPlanets();
708 scolor.nstars = globals->get_ephem()->getNumStars();
709 scolor.planet_data = globals->get_ephem()->getPlanets();
710 scolor.star_data = globals->get_ephem()->getStars();
712 thesky->reposition( sstate, delta_time_sec );
713 thesky->repaint( scolor );
716 SG_LOG( SG_GENERAL, SG_BULK,
717 "thesky->reposition( view_pos = " << view_pos[0] << " "
718 << view_pos[1] << " " << view_pos[2] );
719 SG_LOG( SG_GENERAL, SG_BULK,
720 " zero_elev = " << zero_elev[0] << " "
721 << zero_elev[1] << " " << zero_elev[2]
722 << " lon = " << cur_fdm_state->get_Longitude()
723 << " lat = " << cur_fdm_state->get_Latitude() );
724 SG_LOG( SG_GENERAL, SG_BULK,
725 " sun_rot = " << l->get_sun_rotation
726 << " gst = " << SGTime::cur_time_params->getGst() );
727 SG_LOG( SG_GENERAL, SG_BULK,
728 " sun ra = " << globals->get_ephem()->getSunRightAscension()
729 << " sun dec = " << globals->get_ephem()->getSunDeclination()
730 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
731 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
735 // shadows->setupShadows(
736 // current__view->getLongitude_deg(),
737 // current__view->getLatitude_deg(),
738 // globals->get_time_params()->getGst(),
739 // globals->get_ephem()->getSunRightAscension(),
740 // globals->get_ephem()->getSunDeclination(),
741 // l->get_sun_angle());
745 // sgEnviro.setLight(l->adj_fog_color());
747 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
748 - current__view->getSGLocation()->get_cur_elev_m();
750 float scene_nearplane, scene_farplane;
751 // XXX Given that the own airplane model is part of the scene
752 // graph, should this business be ripped out? The near plane is
753 // ignored by setCameraParameters.
755 scene_nearplane = 10.0f;
756 scene_farplane = 120000.0f;
758 scene_nearplane = groundlevel_nearplane->getDoubleValue();
759 scene_farplane = 120000.0f;
761 setCameraParameters(current__view->get_v_fov(),
762 current__view->get_aspect_ratio(),
763 scene_nearplane, scene_farplane);
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 viewPartition->setVisibility(actual_visibility);
795 simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
796 bool hotspots = fgGetBool("/sim/panel-hotspots");
797 osg::Node::NodeMask cullMask = (~simgear::LIGHTS_BITS & ~simgear::PICK_BIT
798 & ~simgear::BACKGROUND_BIT);
799 cullMask |= simgear::GroundLightManager::instance()
800 ->getLightNodeMask(mUpdateVisitor.get());
802 cullMask |= simgear::PICK_BIT;
803 camera->setCullMask(cullMask);
805 for (int i = 0; i < viewer->getNumSlaves(); ++i)
806 viewer->getSlave(i)._camera->setCullMask(cullMask);
811 // options.cxx needs to see this for toggle_panel()
812 // Handle new window size or exposure
814 FGRenderer::resize( int width, int height ) {
817 if ( (!fgGetBool("/sim/virtual-cockpit"))
818 && fgPanelVisible() && idle_state == 1000 ) {
819 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
820 globals->get_current_panel()->getYOffset()) / 768.0);
825 static int lastwidth = 0;
826 static int lastheight = 0;
827 if (width != lastwidth)
828 fgSetInt("/sim/startup/xsize", lastwidth = width);
829 if (height != lastheight)
830 fgSetInt("/sim/startup/ysize", lastheight = height);
833 FGViewMgr *viewmgr = globals->get_viewmgr();
835 for ( int i = 0; i < viewmgr->size(); ++i ) {
836 viewmgr->get_view(i)->
837 set_aspect_ratio((float)view_h / (float)width);
842 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
843 float zNear, float zFar)
846 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
847 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
853 FGRenderer::pick( unsigned x, unsigned y,
854 std::vector<SGSceneryPick>& pickList,
855 const osgGA::GUIEventAdapter* ea )
857 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
858 // wipe out the return ...
862 // just compute intersections in the viewers method ...
863 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
864 Intersections intersections;
865 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
867 Intersections::iterator hit;
868 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
869 const osg::NodePath& np = hit->nodePath;
870 osg::NodePath::const_reverse_iterator npi;
871 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
872 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
875 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
876 SGPickCallback* pickCallback = ud->getPickCallback(i);
879 SGSceneryPick sceneryPick;
880 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
881 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
882 sceneryPick.callback = pickCallback;
883 pickList.push_back(sceneryPick);
887 return !pickList.empty();
888 } else { // we can get called early ...
894 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
896 mRealRoot->addChild(camera);
900 fgDumpSceneGraphToFile(const char* filename)
902 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
906 fgDumpTerrainBranchToFile(const char* filename)
908 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
914 fgDumpNodeToFile(osg::Node* node, const char* filename)
916 return osgDB::writeNodeFile(*node, filename);
918 // end of renderer.cxx