1 // renderer.cxx -- top level sim routines
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
6 // Copyright (C) 1997 - 2002 Curtis L. Olson - http://www.flightgear.org/~curt
8 // This program is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU General Public License as
10 // published by the Free Software Foundation; either version 2 of the
11 // License, or (at your option) any later version.
13 // This program is distributed in the hope that it will be useful, but
14 // WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // General Public License for more details.
18 // You should have received a copy of the GNU General Public License
19 // along with this program; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
29 #include <simgear/compiler.h>
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
39 #include <osg/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::RenderInfo& renderInfo) const
125 { drawImplementation(*renderInfo.getState()); }
126 void drawImplementation(osg::State& state) const
128 state.pushStateSet(getStateSet());
130 state.setActiveTextureUnit(0);
131 state.setClientActiveTextureUnit(0);
132 state.disableAllVertexArrays();
134 glPushAttrib(GL_ALL_ATTRIB_BITS);
135 glPushClientAttrib(~0u);
137 if((fgGetBool("/sim/atc/enabled"))
138 || (fgGetBool("/sim/ai-traffic/enabled")))
139 globals->get_ATC_display()->update(delta_time_sec, state);
147 state.dirtyAllModes();
148 state.dirtyAllAttributes();
149 state.dirtyAllVertexArrays();
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::RenderInfo& renderInfo) const
178 { drawImplementation(*renderInfo.getState()); }
179 void drawImplementation(osg::State& state) const
181 state.pushStateSet(getStateSet());
183 state.setActiveTextureUnit(0);
184 state.setClientActiveTextureUnit(0);
185 state.disableAllVertexArrays();
187 glPushAttrib(GL_ALL_ATTRIB_BITS);
188 glPushClientAttrib(~0u);
190 fgCockpitUpdate(&state);
192 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
193 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
196 // update the panel subsystem
197 if ( globals->get_current_panel() != NULL )
198 globals->get_current_panel()->update(state);
199 // We don't need a state here - can be safely removed when we can pick
207 state.dirtyAllModes();
208 state.dirtyAllAttributes();
209 state.dirtyAllVertexArrays();
212 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
213 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
218 class FGLightSourceUpdateCallback : public osg::NodeCallback {
220 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
222 assert(dynamic_cast<osg::LightSource*>(node));
223 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
224 osg::Light* light = lightSource->getLight();
226 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
227 light->setAmbient(l->scene_ambient().osg());
228 light->setDiffuse(l->scene_diffuse().osg());
229 light->setSpecular(l->scene_specular().osg());
230 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
231 light->setPosition(position.osg());
232 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
233 light->setDirection(direction.osg());
234 light->setSpotExponent(0);
235 light->setSpotCutoff(180);
236 light->setConstantAttenuation(1);
237 light->setLinearAttenuation(0);
238 light->setQuadraticAttenuation(0);
244 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
246 FGWireFrameModeUpdateCallback() :
247 mWireframe(fgGetNode("/sim/rendering/wireframe"))
249 virtual void operator()(osg::StateAttribute* stateAttribute,
252 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
253 osg::PolygonMode* polygonMode;
254 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
256 if (mWireframe->getBoolValue())
257 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
258 osg::PolygonMode::LINE);
260 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
261 osg::PolygonMode::FILL);
264 SGSharedPtr<SGPropertyNode> mWireframe;
267 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
269 FGLightModelUpdateCallback() :
270 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
272 virtual void operator()(osg::StateAttribute* stateAttribute,
275 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
276 osg::LightModel* lightModel;
277 lightModel = static_cast<osg::LightModel*>(stateAttribute);
280 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
281 lightModel->setAmbientIntensity(l->scene_ambient().osg());
283 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
285 lightModel->setTwoSided(true);
286 lightModel->setLocalViewer(false);
288 if (mHighlights->getBoolValue()) {
289 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
291 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
295 SGSharedPtr<SGPropertyNode> mHighlights;
298 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
300 FGFogEnableUpdateCallback() :
301 mFogEnabled(fgGetNode("/sim/rendering/fog"))
303 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
305 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
306 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
308 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
312 SGSharedPtr<SGPropertyNode> mFogEnabled;
315 // update callback for the switch node guarding that splash
316 class FGScenerySwitchCallback : public osg::NodeCallback {
318 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
320 assert(dynamic_cast<osg::Switch*>(node));
321 osg::Switch* sw = static_cast<osg::Switch*>(node);
323 double t = globals->get_sim_time_sec();
324 bool enabled = 0 < t;
325 sw->setValue(0, enabled);
332 // fog constants. I'm a little nervous about putting actual code out
333 // here but it seems to work (?)
334 static const double m_log01 = -log( 0.01 );
335 static const double sqrt_m_log01 = sqrt( m_log01 );
336 static GLfloat fog_exp_density;
337 static GLfloat fog_exp2_density;
338 static GLfloat rwy_exp2_punch_through;
339 static GLfloat taxi_exp2_punch_through;
340 static GLfloat ground_exp2_punch_through;
345 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
346 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
347 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
349 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
351 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
353 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
354 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
356 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
357 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
358 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
359 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
361 FGRenderer::FGRenderer()
363 #ifdef FG_JPEG_SERVER
364 jpgRenderFrame = FGRenderer::update;
368 FGRenderer::~FGRenderer()
370 #ifdef FG_JPEG_SERVER
371 jpgRenderFrame = NULL;
375 // Initialize various GL/view parameters
377 FGRenderer::splashinit( void ) {
378 // Add the splash screen node
379 mRealRoot->addChild(fgCreateSplashNode());
380 sceneView->setSceneData(mRealRoot.get());
382 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
383 sceneView->setFrameStamp(mFrameStamp.get());
384 sceneView->setUpdateVisitor(mUpdateVisitor.get());
388 FGRenderer::init( void ) {
390 osg::initNotifyLevel();
392 // The number of polygon-offset "units" to place between layers. In
393 // principle, one is supposed to be enough. In practice, I find that
394 // my hardware/driver requires many more.
395 osg::PolygonOffset::setUnitsMultiplier(1);
396 osg::PolygonOffset::setFactorMultiplier(1);
398 // Go full screen if requested ...
399 if ( fgGetBool("/sim/startup/fullscreen") )
402 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
403 (!fgGetBool("/sim/rendering/shading"))) {
404 // if fastest fog requested, or if flat shading force fastest
405 glHint ( GL_FOG_HINT, GL_FASTEST );
406 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
407 glHint ( GL_FOG_HINT, GL_DONT_CARE );
410 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
411 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
412 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
414 mFog->setMode(osg::Fog::EXP2);
415 mRunwayLightingFog->setMode(osg::Fog::EXP2);
416 mTaxiLightingFog->setMode(osg::Fog::EXP2);
417 mGroundLightingFog->setMode(osg::Fog::EXP2);
419 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
420 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
423 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
425 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
427 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
428 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
430 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
431 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
432 stateSet->setAttribute(new osg::BlendFunc);
433 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
435 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
437 // this will be set below
438 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
440 osg::Material* material = new osg::Material;
441 stateSet->setAttribute(material);
443 stateSet->setTextureAttribute(0, new osg::TexEnv);
444 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
447 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
448 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
450 // this is the topmost scenegraph node for osg
451 mBackGroundCamera->addChild(thesky->getPreRoot());
452 mBackGroundCamera->setClearMask(0);
454 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
455 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
456 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
457 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
458 mBackGroundCamera->setInheritanceMask(inheritanceMask);
459 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
460 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
461 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
463 stateSet = mBackGroundCamera->getOrCreateStateSet();
464 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
466 osg::Group* sceneGroup = new osg::Group;
467 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
468 sceneGroup->addChild(thesky->getCloudRoot());
470 stateSet = sceneGroup->getOrCreateStateSet();
471 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
472 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
474 // need to update the light on every frame
475 osg::LightSource* lightSource = new osg::LightSource;
476 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
477 // relative because of CameraView being just a clever transform node
478 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
479 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
480 mRoot->addChild(lightSource);
482 lightSource->addChild(mBackGroundCamera.get());
483 lightSource->addChild(sceneGroup);
486 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
487 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
488 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
489 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
490 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
492 // enable disable specular highlights.
493 // is the place where we might plug in an other fragment shader ...
494 osg::LightModel* lightModel = new osg::LightModel;
495 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
496 stateSet->setAttribute(lightModel);
498 // switch to enable wireframe
499 osg::PolygonMode* polygonMode = new osg::PolygonMode;
500 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
501 stateSet->setAttributeAndModes(polygonMode);
503 // scene fog handling
504 stateSet->setAttributeAndModes(mFog.get());
505 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
508 osg::Camera* guiCamera = new osg::Camera;
509 guiCamera->setRenderOrder(osg::Camera::POST_RENDER);
510 guiCamera->setClearMask(0);
511 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
512 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
513 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
514 guiCamera->setInheritanceMask(inheritanceMask);
515 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
516 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
517 osg::Geode* geode = new osg::Geode;
518 geode->addDrawable(new SGPuDrawable);
519 geode->addDrawable(new SGHUDAndPanelDrawable);
520 guiCamera->addChild(geode);
522 // this one contains all lights, here we set the light states we did
523 // in the plib case with plain OpenGL
524 osg::Group* lightGroup = new osg::Group;
525 sceneGroup->addChild(lightGroup);
526 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
527 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
528 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
529 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
531 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
532 stateSet->setAttributeAndModes(mFog.get());
533 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
534 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
535 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
536 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
537 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
538 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
539 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
540 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
541 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
542 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
544 mCameraView->addChild(mRoot.get());
546 osg::Switch* sw = new osg::Switch;
547 sw->setUpdateCallback(new FGScenerySwitchCallback);
548 sw->addChild(mCameraView.get());
550 mRealRoot->addChild(sw);
551 mRealRoot->addChild(guiCamera);
555 // Update all Visuals (redraws anything graphics related)
557 FGRenderer::update( bool refresh_camera_settings ) {
558 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
559 || fgGetBool("sim/sceneryloaded-override");
561 if ( idle_state < 1000 || !scenery_loaded ) {
562 fgSetDouble("/sim/startup/splash-alpha", 1.0);
564 // Keep resetting sim time while the sim is initializing
565 globals->set_sim_time_sec( 0.0 );
567 // the splash screen is now in the scenegraph
575 // Fade out the splash screen over the first three seconds.
576 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
577 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
579 bool skyblend = fgGetBool("/sim/rendering/skyblend");
580 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
581 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
582 bool distance_attenuation
583 = fgGetBool("/sim/rendering/distance-attenuation");
585 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
586 distance_attenuation );
588 static const SGPropertyNode *groundlevel_nearplane
589 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
591 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
594 double actual_visibility;
595 if (fgGetBool("/environment/clouds/status")) {
596 actual_visibility = thesky->get_visibility();
598 actual_visibility = fgGetDouble("/environment/visibility-m");
601 static double last_visibility = -9999;
602 if ( actual_visibility != last_visibility ) {
603 last_visibility = actual_visibility;
605 fog_exp_density = m_log01 / actual_visibility;
606 fog_exp2_density = sqrt_m_log01 / actual_visibility;
607 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
608 if ( actual_visibility < 8000 ) {
609 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
610 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
612 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
613 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
615 mFog->setDensity(fog_exp2_density);
616 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
617 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
618 mGroundLightingFog->setDensity(ground_exp2_punch_through);
621 // idle_state is now 1000 meaning we've finished all our
622 // initializations and are running the main loop, so this will
623 // now work without seg faulting the system.
625 FGViewer *current__view = globals->get_current_view();
626 // Force update of center dependent values ...
627 current__view->set_dirty();
629 if ( refresh_camera_settings ) {
631 resize( fgGetInt("/sim/startup/xsize"),
632 fgGetInt("/sim/startup/ysize") );
634 SGVec3d center = globals->get_scenery()->get_center();
635 SGVec3d position = current__view->getViewPosition();
636 SGQuatd attitude = current__view->getViewOrientation();
637 SGVec3d osgPosition = attitude.transform(center - position);
638 mCameraView->setPosition(osgPosition.osg());
639 mCameraView->setAttitude(inverse(attitude).osg());
643 if ( fgGetBool("/sim/rendering/textures") ) {
644 SGVec4f clearColor(l->adj_fog_color());
645 sceneView->getCamera()->setClearColor(clearColor.osg());
648 SGVec4f clearColor(l->sky_color());
649 sceneView->getCamera()->setClearColor(clearColor.osg());
652 // update fog params if visibility has changed
653 double visibility_meters = fgGetDouble("/environment/visibility-m");
654 thesky->set_visibility(visibility_meters);
656 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
657 ( global_multi_loop * fgGetInt("/sim/speed-up") )
658 / (double)fgGetInt("/sim/model-hz") );
660 // update the sky dome
663 // The sun and moon distances are scaled down versions
664 // of the actual distance to get both the moon and the sun
665 // within the range of the far clip plane.
666 // Moon distance: 384,467 kilometers
667 // Sun distance: 150,000,000 kilometers
669 double sun_horiz_eff, moon_horiz_eff;
670 if (fgGetBool("/sim/rendering/horizon-effect")) {
671 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
672 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
674 sun_horiz_eff = moon_horiz_eff = 1.0;
677 static SGSkyState sstate;
679 sstate.view_pos = current__view->get_view_pos();
680 sstate.zero_elev = current__view->get_zero_elev();
681 sstate.view_up = current__view->get_world_up();
682 sstate.lon = current__view->getLongitude_deg()
683 * SGD_DEGREES_TO_RADIANS;
684 sstate.lat = current__view->getLatitude_deg()
685 * SGD_DEGREES_TO_RADIANS;
686 sstate.alt = current__view->getAltitudeASL_ft()
688 sstate.spin = l->get_sun_rotation();
689 sstate.gst = globals->get_time_params()->getGst();
690 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
691 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
692 sstate.sun_dist = 50000.0 * sun_horiz_eff;
693 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
694 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
695 sstate.moon_dist = 40000.0 * moon_horiz_eff;
696 sstate.sun_angle = l->get_sun_angle();
700 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
701 << l->sky_color()[0] << " "
702 << l->sky_color()[1] << " "
703 << l->sky_color()[2] << " "
704 << l->sky_color()[3] );
705 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
706 << l->fog_color()[0] << " "
707 << l->fog_color()[1] << " "
708 << l->fog_color()[2] << " "
709 << l->fog_color()[3] );
710 SG_LOG( SG_GENERAL, SG_BULK,
711 " sun_angle = " << l->sun_angle
712 << " moon_angle = " << l->moon_angle );
715 static SGSkyColor scolor;
717 scolor.sky_color = SGVec3f(l->sky_color().data());
718 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
719 scolor.cloud_color = SGVec3f(l->cloud_color().data());
720 scolor.sun_angle = l->get_sun_angle();
721 scolor.moon_angle = l->get_moon_angle();
722 scolor.nplanets = globals->get_ephem()->getNumPlanets();
723 scolor.nstars = globals->get_ephem()->getNumStars();
724 scolor.planet_data = globals->get_ephem()->getPlanets();
725 scolor.star_data = globals->get_ephem()->getStars();
727 thesky->reposition( sstate, delta_time_sec );
728 thesky->repaint( scolor );
731 SG_LOG( SG_GENERAL, SG_BULK,
732 "thesky->reposition( view_pos = " << view_pos[0] << " "
733 << view_pos[1] << " " << view_pos[2] );
734 SG_LOG( SG_GENERAL, SG_BULK,
735 " zero_elev = " << zero_elev[0] << " "
736 << zero_elev[1] << " " << zero_elev[2]
737 << " lon = " << cur_fdm_state->get_Longitude()
738 << " lat = " << cur_fdm_state->get_Latitude() );
739 SG_LOG( SG_GENERAL, SG_BULK,
740 " sun_rot = " << l->get_sun_rotation
741 << " gst = " << SGTime::cur_time_params->getGst() );
742 SG_LOG( SG_GENERAL, SG_BULK,
743 " sun ra = " << globals->get_ephem()->getSunRightAscension()
744 << " sun dec = " << globals->get_ephem()->getSunDeclination()
745 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
746 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
750 // shadows->setupShadows(
751 // current__view->getLongitude_deg(),
752 // current__view->getLatitude_deg(),
753 // globals->get_time_params()->getGst(),
754 // globals->get_ephem()->getSunRightAscension(),
755 // globals->get_ephem()->getSunDeclination(),
756 // l->get_sun_angle());
760 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
761 SGVec4f color(l->adj_fog_color());
762 mFog->setColor(color.osg());
763 mRunwayLightingFog->setColor(color.osg());
764 mTaxiLightingFog->setColor(color.osg());
765 mGroundLightingFog->setColor(color.osg());
769 // sgEnviro.setLight(l->adj_fog_color());
771 // texture parameters
772 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
774 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
775 - current__view->getSGLocation()->get_cur_elev_m();
777 float scene_nearplane, scene_farplane;
779 scene_nearplane = 10.0f;
780 scene_farplane = 120000.0f;
782 scene_nearplane = groundlevel_nearplane->getDoubleValue();
783 scene_farplane = 120000.0f;
785 setNearFar( scene_nearplane, scene_farplane );
787 // sgEnviro.startOfFrame(current__view->get_view_pos(),
788 // current__view->get_world_up(),
789 // current__view->getLongitude_deg(),
790 // current__view->getLatitude_deg(),
791 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
795 // sgEnviro.drawLightning();
797 // double current_view_origin_airspeed_horiz_kt =
798 // fgGetDouble("/velocities/airspeed-kt", 0.0)
799 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
800 // * SGD_DEGREES_TO_RADIANS);
801 // TODO:find the real view speed, not the AC one
802 // sgEnviro.drawPrecipitation(
803 // fgGetDouble("/environment/metar/rain-norm", 0.0),
804 // fgGetDouble("/environment/metar/snow-norm", 0.0),
805 // fgGetDouble("/environment/metar/hail-norm", 0.0),
806 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
807 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
808 // - current__view->getHeadingOffset_deg(),
809 // current_view_origin_airspeed_horiz_kt
814 // shadows->endOfFrame();
816 // need to call the update visitor once
817 globals->get_aircraft_model()->select( true );
818 FGTileMgr::set_tile_filter( true );
819 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
820 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
821 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
822 mUpdateVisitor->setViewData(current__view->getViewPosition(),
823 current__view->getViewOrientation());
824 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
825 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
826 mUpdateVisitor->setLight(direction, l->scene_ambient(),
827 l->scene_diffuse(), l->scene_specular());
828 mUpdateVisitor->setVisibility(actual_visibility);
830 if (fgGetBool("/sim/panel-hotspots"))
831 sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
833 sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
842 // options.cxx needs to see this for toggle_panel()
843 // Handle new window size or exposure
845 FGRenderer::resize( int width, int height ) {
848 if ( (!fgGetBool("/sim/virtual-cockpit"))
849 && fgPanelVisible() && idle_state == 1000 ) {
850 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
851 globals->get_current_panel()->getYOffset()) / 768.0);
856 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
858 static int lastwidth = 0;
859 static int lastheight = 0;
860 if (width != lastwidth)
861 fgSetInt("/sim/startup/xsize", lastwidth = width);
862 if (height != lastheight)
863 fgSetInt("/sim/startup/ysize", lastheight = height);
865 guiInitMouse(width, height);
868 FGViewMgr *viewmgr = globals->get_viewmgr();
870 for ( int i = 0; i < viewmgr->size(); ++i ) {
871 viewmgr->get_view(i)->
872 set_aspect_ratio((float)view_h / (float)width);
875 setFOV( viewmgr->get_current_view()->get_h_fov(),
876 viewmgr->get_current_view()->get_v_fov() );
881 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
882 // which will post process and rewrite the resulting frustum if we
883 // want to do asymmetric view frustums.
885 static void fgHackFrustum() {
887 // specify a percent of the configured view frustum to actually
888 // display. This is a bit of a hack to achieve asymmetric view
889 // frustums. For instance, if you want to display two monitors
890 // side by side, you could specify each with a double fov, a 0.5
891 // aspect ratio multiplier, and then the left side monitor would
892 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
893 // and a top_pct = 1.0. The right side monitor would have a
894 // left_pct = 0.5 and a right_pct = 1.0.
896 static SGPropertyNode *left_pct
897 = fgGetNode("/sim/current-view/frustum-left-pct");
898 static SGPropertyNode *right_pct
899 = fgGetNode("/sim/current-view/frustum-right-pct");
900 static SGPropertyNode *bottom_pct
901 = fgGetNode("/sim/current-view/frustum-bottom-pct");
902 static SGPropertyNode *top_pct
903 = fgGetNode("/sim/current-view/frustum-top-pct");
908 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
909 // cout << " l = " << f->getLeft()
910 // << " r = " << f->getRight()
911 // << " b = " << f->getBot()
912 // << " t = " << f->getTop()
913 // << " n = " << f->getNear()
914 // << " f = " << f->getFar()
917 double width = right - left;
918 double height = top - bottom;
922 if ( left_pct != NULL ) {
923 l = left + width * left_pct->getDoubleValue();
928 if ( right_pct != NULL ) {
929 r = left + width * right_pct->getDoubleValue();
934 if ( bottom_pct != NULL ) {
935 b = bottom + height * bottom_pct->getDoubleValue();
940 if ( top_pct != NULL ) {
941 t = bottom + height * top_pct->getDoubleValue();
946 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
950 // we need some static storage space for these values. However, we
951 // can't store it in a renderer class object because the functions
952 // that manipulate these are static. They are static so they can
953 // interface to the display callback system. There's probably a
954 // better way, there has to be a better way, but I'm not seeing it
956 static float fov_width = 55.0;
957 static float fov_height = 42.0;
958 static float fov_near = 1.0;
959 static float fov_far = 1000.0;
962 /** FlightGear code should use this routine to set the FOV rather than
963 * calling the ssg routine directly
965 void FGRenderer::setFOV( float w, float h ) {
969 sceneView->setProjectionMatrixAsPerspective(fov_height,
970 fov_width/fov_height,
972 // fully specify the view frustum before hacking it (so we don't
973 // accumulate hacked effects
975 // sgEnviro.setFOV( w, h );
979 /** FlightGear code should use this routine to set the Near/Far clip
980 * planes rather than calling the ssg routine directly
982 void FGRenderer::setNearFar( float n, float f ) {
983 // OSGFIXME: we have currently too much z-buffer fights
988 sceneView->setProjectionMatrixAsPerspective(fov_height,
989 fov_width/fov_height,
992 // fully specify the view frustum before hacking it (so we don't
993 // accumulate hacked effects
998 FGRenderer::pick( unsigned x, unsigned y,
999 std::vector<SGSceneryPick>& pickList )
1001 // wipe out the return ...
1004 // we can get called early ...
1005 if (!sceneView.valid())
1008 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
1011 osg::Viewport* viewport = sceneView->getViewport();
1015 // good old scenery center
1016 SGVec3d center = globals->get_scenery()->get_center();
1018 // don't know why, but the update has partly happened somehow,
1019 // so update the scenery part of the viewer
1020 FGViewer *current_view = globals->get_current_view();
1021 // Force update of center dependent values ...
1022 current_view->set_dirty();
1023 SGVec3d position = current_view->getViewPosition();
1024 SGQuatd attitude = current_view->getViewOrientation();
1025 SGVec3d osgPosition = attitude.transform(center - position);
1026 mCameraView->setPosition(osgPosition.osg());
1027 mCameraView->setAttitude(inverse(attitude).osg());
1029 osg::Matrix projection(sceneView->getProjectionMatrix());
1030 osg::Matrix modelview(sceneView->getViewMatrix());
1032 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1033 // modify the view matrix so that it accounts for this nodePath's
1034 // accumulated transform
1035 if (!nodePath.empty())
1036 modelview.preMult(computeLocalToWorld(nodePath.front()));
1038 // swap the y values ...
1039 y = viewport->height() - y;
1040 // set up the pick visitor
1041 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1042 sceneData->accept(pickVisitor);
1043 if (!pickVisitor.hits())
1046 // collect all interaction callbacks on the pick ray.
1047 // They get stored in the pickCallbacks list where they are sorted back
1048 // to front and croasest to finest wrt the scenery node they are attached to
1049 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1050 for (mi = pickVisitor.getSegHitList().begin();
1051 mi != pickVisitor.getSegHitList().end();
1053 osgUtil::IntersectVisitor::HitList::const_iterator hi;
1054 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1055 // ok, go back the nodes and ask for intersection callbacks,
1056 // execute them in top down order
1057 const osg::NodePath& np = hi->getNodePath();
1058 osg::NodePath::const_reverse_iterator npi;
1059 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1060 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1063 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1064 SGPickCallback* pickCallback = ud->getPickCallback(i);
1067 SGSceneryPick sceneryPick;
1068 /// note that this is done totally in doubles instead of
1069 /// just using getWorldIntersectionPoint
1070 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1071 sceneryPick.info.local = SGVec3d(localPt);
1072 if (hi->getMatrix())
1073 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1075 sceneryPick.info.wgs84 = SGVec3d(localPt);
1076 sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1077 sceneryPick.callback = pickCallback;
1078 pickList.push_back(sceneryPick);
1084 return !pickList.empty();
1087 // end of renderer.cxx