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>
38 #include <osg/CameraNode>
39 #include <osg/CameraView>
40 #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>
54 #include <osgUtil/SceneView>
55 #include <osgUtil/UpdateVisitor>
56 #include <osgUtil/IntersectVisitor>
58 #include <osg/io_utils>
59 #include <osgDB/WriteFile>
60 #include <osgDB/ReadFile>
63 #include <simgear/math/SGMath.hxx>
64 #include <simgear/screen/extensions.hxx>
65 #include <simgear/scene/material/matlib.hxx>
66 #include <simgear/scene/model/animation.hxx>
67 #include <simgear/scene/model/model.hxx>
68 #include <simgear/scene/model/modellib.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/util/SGUpdateVisitor.hxx>
71 #include <simgear/scene/tgdb/pt_lights.hxx>
72 #include <simgear/props/props.hxx>
73 #include <simgear/timing/sg_time.hxx>
74 #include <simgear/ephemeris/ephemeris.hxx>
75 #include <simgear/math/sg_random.h>
77 #include <simgear/screen/jpgfactory.hxx>
80 #include <simgear/environment/visual_enviro.hxx>
82 #include <Scenery/tileentry.hxx>
83 #include <Time/light.hxx>
84 #include <Time/light.hxx>
85 #include <Aircraft/aircraft.hxx>
86 #include <Cockpit/panel.hxx>
87 #include <Cockpit/cockpit.hxx>
88 #include <Cockpit/hud.hxx>
89 #include <Model/panelnode.hxx>
90 #include <Model/modelmgr.hxx>
91 #include <Model/acmodel.hxx>
92 #include <Scenery/scenery.hxx>
93 #include <Scenery/tilemgr.hxx>
94 #include <ATC/ATCdisplay.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Instrumentation/HUD/HUD.hxx>
100 #include "renderer.hxx"
103 class SGPuDrawable : public osg::Drawable {
107 // Dynamic stuff, do not store geometry
108 setUseDisplayList(false);
110 osg::StateSet* stateSet = getOrCreateStateSet();
111 stateSet->setRenderBinDetails(1001, "RenderBin");
112 // speed optimization?
113 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
114 // We can do translucent menus, so why not. :-)
115 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
116 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
117 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
119 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
121 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
122 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
124 virtual void drawImplementation(osg::State& state) const
126 state.pushStateSet(getStateSet());
128 state.setActiveTextureUnit(0);
129 state.setClientActiveTextureUnit(0);
131 if((fgGetBool("/sim/atc/enabled"))
132 || (fgGetBool("/sim/ai-traffic/enabled")))
133 globals->get_ATC_display()->update(delta_time_sec, state);
137 // Fade out the splash screen over the first three seconds.
138 double t = globals->get_sim_time_sec();
140 glPushAttrib(GL_ALL_ATTRIB_BITS);
141 glPushClientAttrib(~0u);
143 fgSplashUpdate((2.5 - t) / 2.5);
152 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
153 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
158 class SGHUDAndPanelDrawable : public osg::Drawable {
160 SGHUDAndPanelDrawable()
162 // Dynamic stuff, do not store geometry
163 setUseDisplayList(false);
165 osg::StateSet* stateSet = getOrCreateStateSet();
166 stateSet->setRenderBinDetails(1000, "RenderBin");
168 // speed optimization?
169 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
170 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
171 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
172 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
173 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
175 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
177 virtual void drawImplementation(osg::State& state) const
179 state.pushStateSet(getStateSet());
181 state.setActiveTextureUnit(0);
182 state.setClientActiveTextureUnit(0);
184 glPushAttrib(GL_ALL_ATTRIB_BITS);
185 glPushClientAttrib(~0u);
187 fgCockpitUpdate(&state);
189 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
190 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
193 // update the panel subsystem
194 if ( globals->get_current_panel() != NULL )
195 globals->get_current_panel()->update(state);
196 // We don't need a state here - can be safely removed when we can pick
206 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
207 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
212 class FGLightSourceUpdateCallback : public osg::NodeCallback {
214 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
216 assert(dynamic_cast<osg::LightSource*>(node));
217 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
218 osg::Light* light = lightSource->getLight();
220 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
221 light->setAmbient(l->scene_ambient().osg());
222 light->setDiffuse(l->scene_diffuse().osg());
223 light->setSpecular(l->scene_specular().osg());
224 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
225 light->setPosition(position.osg());
226 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
227 light->setDirection(direction.osg());
228 light->setSpotExponent(0);
229 light->setSpotCutoff(180);
230 light->setConstantAttenuation(1);
231 light->setLinearAttenuation(0);
232 light->setQuadraticAttenuation(0);
238 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
240 FGWireFrameModeUpdateCallback() :
241 mWireframe(fgGetNode("/sim/rendering/wireframe"))
243 virtual void operator()(osg::StateAttribute* stateAttribute,
246 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
247 osg::PolygonMode* polygonMode;
248 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
250 if (mWireframe->getBoolValue())
251 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
252 osg::PolygonMode::LINE);
254 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
255 osg::PolygonMode::FILL);
258 SGSharedPtr<SGPropertyNode> mWireframe;
261 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
263 FGLightModelUpdateCallback() :
264 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
266 virtual void operator()(osg::StateAttribute* stateAttribute,
269 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
270 osg::LightModel* lightModel;
271 lightModel = static_cast<osg::LightModel*>(stateAttribute);
274 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
275 lightModel->setAmbientIntensity(l->scene_ambient().osg());
277 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
279 lightModel->setTwoSided(true);
280 lightModel->setLocalViewer(false);
282 if (mHighlights->getBoolValue()) {
283 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
285 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
289 SGSharedPtr<SGPropertyNode> mHighlights;
292 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
294 FGFogEnableUpdateCallback() :
295 mFogEnabled(fgGetNode("/sim/rendering/fog"))
297 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
299 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
300 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
302 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
306 SGSharedPtr<SGPropertyNode> mFogEnabled;
309 // fog constants. I'm a little nervous about putting actual code out
310 // here but it seems to work (?)
311 static const double m_log01 = -log( 0.01 );
312 static const double sqrt_m_log01 = sqrt( m_log01 );
313 static GLfloat fog_exp_density;
314 static GLfloat fog_exp2_density;
315 static GLfloat rwy_exp2_punch_through;
316 static GLfloat taxi_exp2_punch_through;
317 static GLfloat ground_exp2_punch_through;
322 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
323 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
324 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
326 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
328 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
329 static osg::ref_ptr<osg::CameraNode> mBackGroundCamera = new osg::CameraNode;
330 osg::ref_ptr<osg::CameraNode> mSceneCamera = new osg::CameraNode;
332 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
333 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
334 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
335 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
337 FGRenderer::FGRenderer()
339 #ifdef FG_JPEG_SERVER
340 jpgRenderFrame = FGRenderer::update;
344 FGRenderer::~FGRenderer()
346 #ifdef FG_JPEG_SERVER
347 jpgRenderFrame = NULL;
351 // Initialize various GL/view parameters
353 FGRenderer::init( void ) {
355 osg::initNotifyLevel();
357 // The number of polygon-offset "units" to place between layers. In
358 // principle, one is supposed to be enough. In practice, I find that
359 // my hardware/driver requires many more.
360 osg::PolygonOffset::setUnitsMultiplier(1);
361 osg::PolygonOffset::setFactorMultiplier(1);
363 // Go full screen if requested ...
364 if ( fgGetBool("/sim/startup/fullscreen") )
367 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
368 (!fgGetBool("/sim/rendering/shading"))) {
369 // if fastest fog requested, or if flat shading force fastest
370 glHint ( GL_FOG_HINT, GL_FASTEST );
371 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
372 glHint ( GL_FOG_HINT, GL_DONT_CARE );
375 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
376 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
377 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
379 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
381 mFog->setMode(osg::Fog::EXP2);
382 mRunwayLightingFog->setMode(osg::Fog::EXP2);
383 mTaxiLightingFog->setMode(osg::Fog::EXP2);
384 mGroundLightingFog->setMode(osg::Fog::EXP2);
386 sceneView->setFrameStamp(mFrameStamp.get());
388 mUpdateVisitor = new SGUpdateVisitor;
389 sceneView->setUpdateVisitor(mUpdateVisitor.get());
391 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
392 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
394 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
396 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
398 stateSet->setAttribute(new osg::Depth(osg::Depth::LEQUAL));
399 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
401 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
402 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
403 stateSet->setAttribute(new osg::BlendFunc);
404 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
406 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
408 // this will be set below
409 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
411 osg::Material* material = new osg::Material;
412 stateSet->setAttribute(material);
414 stateSet->setTextureAttribute(0, new osg::TexEnv);
415 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
418 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
419 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
422 // this is the topmost scenegraph node for osg
423 mBackGroundCamera->addChild(thesky->getPreRoot());
424 mBackGroundCamera->setClearMask(0);
426 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
427 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
428 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
429 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
430 mBackGroundCamera->setInheritanceMask(inheritanceMask);
431 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
432 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
433 mBackGroundCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
435 stateSet = mBackGroundCamera->getOrCreateStateSet();
436 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
439 mSceneCamera->setClearMask(0);
440 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
441 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
442 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
443 mSceneCamera->setInheritanceMask(inheritanceMask);
444 mSceneCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
445 mSceneCamera->setCullingMode(osg::CullSettings::DEFAULT_CULLING);
446 mSceneCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
447 mSceneCamera->addChild(globals->get_scenery()->get_scene_graph());
448 mSceneCamera->addChild(thesky->getCloudRoot());
450 stateSet = mSceneCamera->getOrCreateStateSet();
451 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
452 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
454 // need to update the light on every frame
455 osg::LightSource* lightSource = new osg::LightSource;
456 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
457 // relative because of CameraView being just a clever transform node
458 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
459 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
460 mRoot->addChild(lightSource);
462 lightSource->addChild(mBackGroundCamera.get());
463 lightSource->addChild(mSceneCamera.get());
466 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
467 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
468 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
469 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
470 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
472 // enable disable specular highlights.
473 // is the place where we might plug in an other fragment shader ...
474 osg::LightModel* lightModel = new osg::LightModel;
475 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
476 stateSet->setAttribute(lightModel);
478 // switch to enable wireframe
479 osg::PolygonMode* polygonMode = new osg::PolygonMode;
480 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
481 stateSet->setAttributeAndModes(polygonMode);
483 // scene fog handling
484 stateSet->setAttributeAndModes(mFog.get());
485 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
488 osg::CameraNode* guiCamera = new osg::CameraNode;
489 guiCamera->setRenderOrder(osg::CameraNode::POST_RENDER);
490 guiCamera->setClearMask(0);
491 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
492 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
493 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
494 guiCamera->setInheritanceMask(inheritanceMask);
495 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
496 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
497 mRoot->addChild(guiCamera);
498 osg::Geode* geode = new osg::Geode;
499 geode->addDrawable(new SGPuDrawable);
500 geode->addDrawable(new SGHUDAndPanelDrawable);
501 guiCamera->addChild(geode);
503 // this one contains all lights, here we set the light states we did
504 // in the plib case with plain OpenGL
505 osg::Group* lightGroup = new osg::Group;
506 mSceneCamera->addChild(lightGroup);
507 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
508 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
509 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
510 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
512 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
513 stateSet->setAttributeAndModes(mFog.get());
514 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
515 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
516 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
517 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
518 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
519 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
520 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
521 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
522 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
523 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
525 mCameraView->addChild(mRoot.get());
526 sceneView->setSceneData(mCameraView.get());
528 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
532 // Update all Visuals (redraws anything graphics related)
534 FGRenderer::update( bool refresh_camera_settings ) {
535 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
536 || fgGetBool("sim/sceneryloaded-override");
538 if ( idle_state < 1000 || !scenery_loaded ) {
539 if (sceneView.valid() && sceneView->getState()) {
540 sceneView->getState()->setActiveTextureUnit(0);
541 sceneView->getState()->setClientActiveTextureUnit(0);
543 // still initializing, draw the splash screen
544 glPushAttrib(GL_ALL_ATTRIB_BITS);
545 glPushClientAttrib(~0u);
552 // Keep resetting sim time while the sim is initializing
553 globals->set_sim_time_sec( 0.0 );
557 bool skyblend = fgGetBool("/sim/rendering/skyblend");
558 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
559 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
560 bool distance_attenuation
561 = fgGetBool("/sim/rendering/distance-attenuation");
563 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
564 distance_attenuation );
566 static const SGPropertyNode *groundlevel_nearplane
567 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
569 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
572 double actual_visibility;
573 if (fgGetBool("/environment/clouds/status")) {
574 actual_visibility = thesky->get_visibility();
576 actual_visibility = fgGetDouble("/environment/visibility-m");
579 static double last_visibility = -9999;
580 if ( actual_visibility != last_visibility ) {
581 last_visibility = actual_visibility;
583 fog_exp_density = m_log01 / actual_visibility;
584 fog_exp2_density = sqrt_m_log01 / actual_visibility;
585 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
586 if ( actual_visibility < 8000 ) {
587 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
588 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
590 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
591 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
593 mFog->setDensity(fog_exp2_density);
594 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
595 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
596 mGroundLightingFog->setDensity(ground_exp2_punch_through);
599 // idle_state is now 1000 meaning we've finished all our
600 // initializations and are running the main loop, so this will
601 // now work without seg faulting the system.
603 FGViewer *current__view = globals->get_current_view();
604 // Force update of center dependent values ...
605 current__view->set_dirty();
607 if ( refresh_camera_settings ) {
609 resize( fgGetInt("/sim/startup/xsize"),
610 fgGetInt("/sim/startup/ysize") );
612 SGVec3d center = globals->get_scenery()->get_center();
613 SGVec3d position = current__view->getViewPosition();
614 SGQuatd attitude = current__view->getViewOrientation();
615 SGVec3d osgPosition = attitude.transform(center - position);
616 mCameraView->setPosition(osgPosition.osg());
617 mCameraView->setAttitude(inverse(attitude).osg());
621 if ( fgGetBool("/sim/rendering/textures") ) {
622 SGVec4f clearColor(l->adj_fog_color());
623 sceneView->getCamera()->setClearColor(clearColor.osg());
626 SGVec4f clearColor(l->sky_color());
627 sceneView->getCamera()->setClearColor(clearColor.osg());
630 // update fog params if visibility has changed
631 double visibility_meters = fgGetDouble("/environment/visibility-m");
632 thesky->set_visibility(visibility_meters);
634 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
635 ( global_multi_loop * fgGetInt("/sim/speed-up") )
636 / (double)fgGetInt("/sim/model-hz") );
638 // update the sky dome
641 // The sun and moon distances are scaled down versions
642 // of the actual distance to get both the moon and the sun
643 // within the range of the far clip plane.
644 // Moon distance: 384,467 kilometers
645 // Sun distance: 150,000,000 kilometers
647 double sun_horiz_eff, moon_horiz_eff;
648 if (fgGetBool("/sim/rendering/horizon-effect")) {
649 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
650 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
652 sun_horiz_eff = moon_horiz_eff = 1.0;
655 static SGSkyState sstate;
657 sstate.view_pos = current__view->get_view_pos();
658 sstate.zero_elev = current__view->get_zero_elev();
659 sstate.view_up = current__view->get_world_up();
660 sstate.lon = current__view->getLongitude_deg()
661 * SGD_DEGREES_TO_RADIANS;
662 sstate.lat = current__view->getLatitude_deg()
663 * SGD_DEGREES_TO_RADIANS;
664 sstate.alt = current__view->getAltitudeASL_ft()
666 sstate.spin = l->get_sun_rotation();
667 sstate.gst = globals->get_time_params()->getGst();
668 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
669 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
670 sstate.sun_dist = 50000.0 * sun_horiz_eff;
671 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
672 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
673 sstate.moon_dist = 40000.0 * moon_horiz_eff;
674 sstate.sun_angle = l->get_sun_angle();
678 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
679 << l->sky_color()[0] << " "
680 << l->sky_color()[1] << " "
681 << l->sky_color()[2] << " "
682 << l->sky_color()[3] );
683 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
684 << l->fog_color()[0] << " "
685 << l->fog_color()[1] << " "
686 << l->fog_color()[2] << " "
687 << l->fog_color()[3] );
688 SG_LOG( SG_GENERAL, SG_BULK,
689 " sun_angle = " << l->sun_angle
690 << " moon_angle = " << l->moon_angle );
693 static SGSkyColor scolor;
695 scolor.sky_color = SGVec3f(l->sky_color().data());
696 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
697 scolor.cloud_color = SGVec3f(l->cloud_color().data());
698 scolor.sun_angle = l->get_sun_angle();
699 scolor.moon_angle = l->get_moon_angle();
700 scolor.nplanets = globals->get_ephem()->getNumPlanets();
701 scolor.nstars = globals->get_ephem()->getNumStars();
702 scolor.planet_data = globals->get_ephem()->getPlanets();
703 scolor.star_data = globals->get_ephem()->getStars();
705 thesky->reposition( sstate, delta_time_sec );
706 thesky->repaint( scolor );
709 SG_LOG( SG_GENERAL, SG_BULK,
710 "thesky->reposition( view_pos = " << view_pos[0] << " "
711 << view_pos[1] << " " << view_pos[2] );
712 SG_LOG( SG_GENERAL, SG_BULK,
713 " zero_elev = " << zero_elev[0] << " "
714 << zero_elev[1] << " " << zero_elev[2]
715 << " lon = " << cur_fdm_state->get_Longitude()
716 << " lat = " << cur_fdm_state->get_Latitude() );
717 SG_LOG( SG_GENERAL, SG_BULK,
718 " sun_rot = " << l->get_sun_rotation
719 << " gst = " << SGTime::cur_time_params->getGst() );
720 SG_LOG( SG_GENERAL, SG_BULK,
721 " sun ra = " << globals->get_ephem()->getSunRightAscension()
722 << " sun dec = " << globals->get_ephem()->getSunDeclination()
723 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
724 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
728 // shadows->setupShadows(
729 // current__view->getLongitude_deg(),
730 // current__view->getLatitude_deg(),
731 // globals->get_time_params()->getGst(),
732 // globals->get_ephem()->getSunRightAscension(),
733 // globals->get_ephem()->getSunDeclination(),
734 // l->get_sun_angle());
738 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
739 SGVec4f color(l->adj_fog_color());
740 mFog->setColor(color.osg());
741 mRunwayLightingFog->setColor(color.osg());
742 mTaxiLightingFog->setColor(color.osg());
743 mGroundLightingFog->setColor(color.osg());
747 // sgEnviro.setLight(l->adj_fog_color());
749 // texture parameters
750 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
752 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
753 - current__view->getSGLocation()->get_cur_elev_m();
755 float scene_nearplane, scene_farplane;
757 scene_nearplane = 10.0f;
758 scene_farplane = 120000.0f;
760 scene_nearplane = groundlevel_nearplane->getDoubleValue();
761 scene_farplane = 120000.0f;
764 setNearFar( 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);
780 // TODO:find the real view speed, not the AC one
781 // sgEnviro.drawPrecipitation(
782 // fgGetDouble("/environment/metar/rain-norm", 0.0),
783 // fgGetDouble("/environment/metar/snow-norm", 0.0),
784 // fgGetDouble("/environment/metar/hail-norm", 0.0),
785 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
786 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
787 // - current__view->getHeadingOffset_deg(),
788 // current_view_origin_airspeed_horiz_kt
793 // shadows->endOfFrame();
795 // need to call the update visitor once
796 globals->get_aircraft_model()->select( true );
797 FGTileMgr::set_tile_filter( true );
798 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
799 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
800 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
801 mUpdateVisitor->setViewData(current__view->getViewPosition(),
802 current__view->getViewOrientation());
803 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
804 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
805 mUpdateVisitor->setLight(direction, l->scene_ambient(),
806 l->scene_diffuse(), l->scene_specular());
807 mUpdateVisitor->setVisibility(actual_visibility);
809 if (fgGetBool("/sim/panel-hotspots"))
810 sceneView->setCullMask(~0u);
812 sceneView->setCullMask(~SG_NODEMASK_PICK_BIT);
821 // options.cxx needs to see this for toggle_panel()
822 // Handle new window size or exposure
824 FGRenderer::resize( int width, int height ) {
827 if ( (!fgGetBool("/sim/virtual-cockpit"))
828 && fgPanelVisible() && idle_state == 1000 ) {
829 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
830 globals->get_current_panel()->getYOffset()) / 768.0);
835 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
837 static int lastwidth = 0;
838 static int lastheight = 0;
839 if (width != lastwidth)
840 fgSetInt("/sim/startup/xsize", lastwidth = width);
841 if (height != lastheight)
842 fgSetInt("/sim/startup/ysize", lastheight = height);
844 guiInitMouse(width, height);
847 FGViewMgr *viewmgr = globals->get_viewmgr();
849 for ( int i = 0; i < viewmgr->size(); ++i ) {
850 viewmgr->get_view(i)->
851 set_aspect_ratio((float)view_h / (float)width);
854 setFOV( viewmgr->get_current_view()->get_h_fov(),
855 viewmgr->get_current_view()->get_v_fov() );
860 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
861 // which will post process and rewrite the resulting frustum if we
862 // want to do asymmetric view frustums.
864 static void fgHackFrustum() {
866 // specify a percent of the configured view frustum to actually
867 // display. This is a bit of a hack to achieve asymmetric view
868 // frustums. For instance, if you want to display two monitors
869 // side by side, you could specify each with a double fov, a 0.5
870 // aspect ratio multiplier, and then the left side monitor would
871 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
872 // and a top_pct = 1.0. The right side monitor would have a
873 // left_pct = 0.5 and a right_pct = 1.0.
875 static SGPropertyNode *left_pct
876 = fgGetNode("/sim/current-view/frustum-left-pct");
877 static SGPropertyNode *right_pct
878 = fgGetNode("/sim/current-view/frustum-right-pct");
879 static SGPropertyNode *bottom_pct
880 = fgGetNode("/sim/current-view/frustum-bottom-pct");
881 static SGPropertyNode *top_pct
882 = fgGetNode("/sim/current-view/frustum-top-pct");
887 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
888 // cout << " l = " << f->getLeft()
889 // << " r = " << f->getRight()
890 // << " b = " << f->getBot()
891 // << " t = " << f->getTop()
892 // << " n = " << f->getNear()
893 // << " f = " << f->getFar()
896 double width = right - left;
897 double height = top - bottom;
901 if ( left_pct != NULL ) {
902 l = left + width * left_pct->getDoubleValue();
907 if ( right_pct != NULL ) {
908 r = left + width * right_pct->getDoubleValue();
913 if ( bottom_pct != NULL ) {
914 b = bottom + height * bottom_pct->getDoubleValue();
919 if ( top_pct != NULL ) {
920 t = bottom + height * top_pct->getDoubleValue();
925 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
929 // we need some static storage space for these values. However, we
930 // can't store it in a renderer class object because the functions
931 // that manipulate these are static. They are static so they can
932 // interface to the display callback system. There's probably a
933 // better way, there has to be a better way, but I'm not seeing it
935 static float fov_width = 55.0;
936 static float fov_height = 42.0;
937 static float fov_near = 1.0;
938 static float fov_far = 1000.0;
941 /** FlightGear code should use this routine to set the FOV rather than
942 * calling the ssg routine directly
944 void FGRenderer::setFOV( float w, float h ) {
948 sceneView->setProjectionMatrixAsPerspective(fov_height,
949 fov_width/fov_height,
951 // fully specify the view frustum before hacking it (so we don't
952 // accumulate hacked effects
954 // sgEnviro.setFOV( w, h );
958 /** FlightGear code should use this routine to set the Near/Far clip
959 * planes rather than calling the ssg routine directly
961 void FGRenderer::setNearFar( float n, float f ) {
962 // OSGFIXME: we have currently too much z-buffer fights
967 sceneView->setProjectionMatrixAsPerspective(fov_height,
968 fov_width/fov_height,
971 sceneView->getCamera()->setNearFarRatio(fov_near/fov_far);
972 mSceneCamera->setNearFarRatio(fov_near/fov_far);
974 // fully specify the view frustum before hacking it (so we don't
975 // accumulate hacked effects
980 FGRenderer::pick( unsigned x, unsigned y,
981 std::vector<SGSceneryPick>& pickList )
983 // wipe out the return ...
986 // we can get called early ...
987 if (!sceneView.valid())
990 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
993 osg::Viewport* viewport = sceneView->getViewport();
997 // good old scenery center
998 SGVec3d center = globals->get_scenery()->get_center();
1000 // don't know why, but the update has partly happened somehow,
1001 // so update the scenery part of the viewer
1002 FGViewer *current_view = globals->get_current_view();
1003 // Force update of center dependent values ...
1004 current_view->set_dirty();
1005 SGVec3d position = current_view->getViewPosition();
1006 SGQuatd attitude = current_view->getViewOrientation();
1007 SGVec3d osgPosition = attitude.transform(center - position);
1008 mCameraView->setPosition(osgPosition.osg());
1009 mCameraView->setAttitude(inverse(attitude).osg());
1011 osg::Matrix projection(sceneView->getProjectionMatrix());
1012 osg::Matrix modelview(sceneView->getViewMatrix());
1014 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1015 // modify the view matrix so that it accounts for this nodePath's
1016 // accumulated transform
1017 if (!nodePath.empty())
1018 modelview.preMult(computeLocalToWorld(nodePath.front()));
1020 // swap the y values ...
1021 y = viewport->height() - y;
1022 // set up the pick visitor
1023 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1024 sceneData->accept(pickVisitor);
1025 if (!pickVisitor.hits())
1028 // collect all interaction callbacks on the pick ray.
1029 // They get stored in the pickCallbacks list where they are sorted back
1030 // to front and croasest to finest wrt the scenery node they are attached to
1031 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1032 for (mi = pickVisitor.getSegHitList().begin();
1033 mi != pickVisitor.getSegHitList().end();
1035 osgUtil::IntersectVisitor::HitList::const_iterator hi;
1036 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1037 // ok, go back the nodes and ask for intersection callbacks,
1038 // execute them in top down order
1039 const osg::NodePath& np = hi->getNodePath();
1040 osg::NodePath::const_reverse_iterator npi;
1041 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1042 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1045 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1046 SGPickCallback* pickCallback = ud->getPickCallback(i);
1049 SGSceneryPick sceneryPick;
1050 /// note that this is done totally in doubles instead of
1051 /// just using getWorldIntersectionPoint
1052 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1053 sceneryPick.info.local = SGVec3d(localPt);
1054 if (hi->getMatrix())
1055 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1057 sceneryPick.info.wgs84 = SGVec3d(localPt);
1058 sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1059 sceneryPick.callback = pickCallback;
1060 pickList.push_back(sceneryPick);
1066 return !pickList.empty();
1069 // end of renderer.cxx