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.disableAllVertexArrays();
164 glPushAttrib(GL_ALL_ATTRIB_BITS);
165 glPushClientAttrib(~0u);
173 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
174 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
179 class SGHUDAndPanelDrawable : public osg::Drawable {
181 SGHUDAndPanelDrawable()
183 // Dynamic stuff, do not store geometry
184 setUseDisplayList(false);
186 osg::StateSet* stateSet = getOrCreateStateSet();
187 stateSet->setRenderBinDetails(1000, "RenderBin");
189 // speed optimization?
190 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
191 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
192 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
193 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
194 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
196 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
198 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
199 { drawImplementation(*renderInfo.getState()); }
200 void drawImplementation(osg::State& state) const
202 if (!fgOSIsMainContext(state.getGraphicsContext()))
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
227 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
228 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
233 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
237 assert(dynamic_cast<osg::LightSource*>(node));
238 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
239 osg::Light* light = lightSource->getLight();
241 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
242 light->setAmbient(l->scene_ambient().osg());
243 light->setDiffuse(l->scene_diffuse().osg());
244 light->setSpecular(l->scene_specular().osg());
245 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
246 light->setPosition(position.osg());
247 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
248 light->setDirection(direction.osg());
249 light->setSpotExponent(0);
250 light->setSpotCutoff(180);
251 light->setConstantAttenuation(1);
252 light->setLinearAttenuation(0);
253 light->setQuadraticAttenuation(0);
259 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
261 FGWireFrameModeUpdateCallback() :
262 mWireframe(fgGetNode("/sim/rendering/wireframe"))
264 virtual void operator()(osg::StateAttribute* stateAttribute,
267 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
268 osg::PolygonMode* polygonMode;
269 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
271 if (mWireframe->getBoolValue())
272 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
273 osg::PolygonMode::LINE);
275 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
276 osg::PolygonMode::FILL);
279 SGSharedPtr<SGPropertyNode> mWireframe;
282 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
284 FGLightModelUpdateCallback() :
285 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
287 virtual void operator()(osg::StateAttribute* stateAttribute,
290 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
291 osg::LightModel* lightModel;
292 lightModel = static_cast<osg::LightModel*>(stateAttribute);
295 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
296 lightModel->setAmbientIntensity(l->scene_ambient().osg());
298 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
300 lightModel->setTwoSided(true);
301 lightModel->setLocalViewer(false);
303 if (mHighlights->getBoolValue()) {
304 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
306 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
310 SGSharedPtr<SGPropertyNode> mHighlights;
313 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
315 FGFogEnableUpdateCallback() :
316 mFogEnabled(fgGetNode("/sim/rendering/fog"))
318 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
320 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
321 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
323 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
327 SGSharedPtr<SGPropertyNode> mFogEnabled;
330 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
332 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
334 assert(dynamic_cast<SGUpdateVisitor*>(nv));
335 assert(dynamic_cast<osg::Fog*>(sa));
336 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
337 osg::Fog* fog = static_cast<osg::Fog*>(sa);
338 fog->setMode(osg::Fog::EXP2);
339 fog->setColor(updateVisitor->getFogColor().osg());
340 fog->setDensity(updateVisitor->getFogExp2Density());
344 // update callback for the switch node guarding that splash
345 class FGScenerySwitchCallback : public osg::NodeCallback {
347 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
349 assert(dynamic_cast<osg::Switch*>(node));
350 osg::Switch* sw = static_cast<osg::Switch*>(node);
352 double t = globals->get_sim_time_sec();
353 bool enabled = 0 < t;
354 sw->setValue(0, enabled);
364 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
365 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
367 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
369 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
371 static osg::ref_ptr<ViewPartitionNode> viewPartition = new ViewPartitionNode;
373 FGRenderer::FGRenderer()
375 #ifdef FG_JPEG_SERVER
376 jpgRenderFrame = FGRenderer::update;
378 manipulator = new FGManipulator;
381 FGRenderer::~FGRenderer()
383 #ifdef FG_JPEG_SERVER
384 jpgRenderFrame = NULL;
388 // Initialize various GL/view parameters
389 // XXX This should be called "preinit" or something, as it initializes
390 // critical parts of the scene graph in addition to the splash screen.
392 FGRenderer::splashinit( void ) {
393 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
394 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
395 mRealRoot->addChild(fgCreateSplashNode());
396 mFrameStamp = viewer->getFrameStamp();
397 // Scene doesn't seem to pass the frame stamp to the update
398 // visitor automatically.
399 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
400 #ifdef UPDATE_VISITOR_IN_VIEWER
401 viewer->setUpdateVisitor(mUpdateVisitor.get());
403 osgViewer::Scene* scene = viewer->getScene();
404 scene->setUpdateVisitor(mUpdateVisitor.get());
410 // Create a slave camera that will be used to render a fixed GUI-like
413 makeSlaveCamera(osg::Camera::RenderOrder renderOrder, int orderNum)
416 Camera* camera = new osg::Camera;
417 GraphicsContext *gc = fgOSGetMainContext();
419 camera->setRenderOrder(renderOrder, orderNum);
420 camera->setClearMask(0);
421 camera->setInheritanceMask(CullSettings::ALL_VARIABLES
422 & ~(CullSettings::COMPUTE_NEAR_FAR_MODE
423 | CullSettings::CULLING_MODE));
424 camera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
425 camera->setCullingMode(osg::CullSettings::NO_CULLING);
426 camera->setGraphicsContext(gc);
427 // Establish an initial viewport. This may be altered,
428 // particularly when drawing a 2d panel.
429 const GraphicsContext::Traits *traits = gc->getTraits();
430 camera->setViewport(new Viewport(0, 0, traits->width, traits->height));
431 camera->setProjectionResizePolicy(Camera::FIXED);
432 camera->setReferenceFrame(Transform::ABSOLUTE_RF);
433 camera->setAllowEventFocus(false);
434 globals->get_renderer()->getViewer()->addSlave(camera, false);
441 FGRenderer::init( void )
443 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
444 osg::initNotifyLevel();
446 // The number of polygon-offset "units" to place between layers. In
447 // principle, one is supposed to be enough. In practice, I find that
448 // my hardware/driver requires many more.
449 osg::PolygonOffset::setUnitsMultiplier(1);
450 osg::PolygonOffset::setFactorMultiplier(1);
452 // Go full screen if requested ...
453 if ( fgGetBool("/sim/startup/fullscreen") )
457 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
459 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
461 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
463 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
464 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
466 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
467 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
468 stateSet->setAttribute(new osg::BlendFunc);
469 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
471 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
473 // this will be set below
474 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
476 osg::Material* material = new osg::Material;
477 stateSet->setAttribute(material);
479 stateSet->setTextureAttribute(0, new osg::TexEnv);
480 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
482 osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
483 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
484 stateSet->setAttribute(hint);
485 hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
486 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
487 stateSet->setAttribute(hint);
488 hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
489 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
490 stateSet->setAttribute(hint);
491 hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
492 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
493 stateSet->setAttribute(hint);
494 hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
495 hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
496 stateSet->setAttribute(hint);
498 osg::Group* sceneGroup = new osg::Group;
499 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
500 sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
502 //sceneGroup->addChild(thesky->getCloudRoot());
504 stateSet = sceneGroup->getOrCreateStateSet();
505 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
506 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
508 // need to update the light on every frame
509 osg::LightSource* lightSource = new osg::LightSource;
510 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
511 // relative because of CameraView being just a clever transform node
512 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
513 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
515 lightSource->addChild(sceneGroup);
516 lightSource->addChild(thesky->getPreRoot());
517 mRoot->addChild(lightSource);
519 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
520 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
521 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
522 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
523 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
525 // enable disable specular highlights.
526 // is the place where we might plug in an other fragment shader ...
527 osg::LightModel* lightModel = new osg::LightModel;
528 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
529 stateSet->setAttribute(lightModel);
531 // switch to enable wireframe
532 osg::PolygonMode* polygonMode = new osg::PolygonMode;
533 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
534 stateSet->setAttributeAndModes(polygonMode);
536 // scene fog handling
537 osg::Fog* fog = new osg::Fog;
538 fog->setUpdateCallback(new FGFogUpdateCallback);
539 stateSet->setAttributeAndModes(fog);
540 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
543 osg::Camera* guiCamera = makeSlaveCamera(osg::Camera::POST_RENDER, 100);
544 guiCamera->setName("GUI");
545 osg::Geode* geode = new osg::Geode;
546 geode->addDrawable(new SGPuDrawable);
547 geode->addDrawable(new SGHUDAndPanelDrawable);
548 guiCamera->addChild(geode);
550 osg::Switch* sw = new osg::Switch;
551 sw->setUpdateCallback(new FGScenerySwitchCallback);
552 sw->addChild(mRoot.get());
553 viewPartition->addChild(sw);
554 viewPartition->addChild(thesky->getCloudRoot());
556 mRealRoot->addChild(viewPartition.get());
557 mRealRoot->addChild(FGCreateRedoutNode());
558 mRealRoot->addChild(guiCamera);
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);
832 guiInitMouse(width, height);
835 FGViewMgr *viewmgr = globals->get_viewmgr();
837 for ( int i = 0; i < viewmgr->size(); ++i ) {
838 viewmgr->get_view(i)->
839 set_aspect_ratio((float)view_h / (float)width);
844 void FGRenderer::setCameraParameters(float vfov, float aspectRatio,
845 float zNear, float zFar)
848 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
849 viewer->getCamera()->setProjectionMatrixAsPerspective(vfov,
855 FGRenderer::pick( unsigned x, unsigned y,
856 std::vector<SGSceneryPick>& pickList,
857 const osgGA::GUIEventAdapter* ea )
859 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
860 // wipe out the return ...
864 // just compute intersections in the viewers method ...
865 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
866 Intersections intersections;
867 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
869 Intersections::iterator hit;
870 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
871 const osg::NodePath& np = hit->nodePath;
872 osg::NodePath::const_reverse_iterator npi;
873 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
874 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
877 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
878 SGPickCallback* pickCallback = ud->getPickCallback(i);
881 SGSceneryPick sceneryPick;
882 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
883 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
884 sceneryPick.callback = pickCallback;
885 pickList.push_back(sceneryPick);
889 return !pickList.empty();
890 } else { // we can get called early ...
896 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
898 mRealRoot->addChild(camera);
902 fgDumpSceneGraphToFile(const char* filename)
904 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
908 fgDumpTerrainBranchToFile(const char* filename)
910 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
916 fgDumpNodeToFile(osg::Node* node, const char* filename)
918 return osgDB::writeNodeFile(*node, filename);
920 // end of renderer.cxx