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);
146 // Fade out the splash screen over the first three seconds.
147 double t = globals->get_sim_time_sec();
149 glPushAttrib(GL_ALL_ATTRIB_BITS);
150 glPushClientAttrib(~0u);
152 fgSplashUpdate((2.5 - t) / 2.5);
159 state.dirtyAllModes();
160 state.dirtyAllAttributes();
161 state.dirtyAllVertexArrays();
164 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
165 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
170 class SGHUDAndPanelDrawable : public osg::Drawable {
172 SGHUDAndPanelDrawable()
174 // Dynamic stuff, do not store geometry
175 setUseDisplayList(false);
177 osg::StateSet* stateSet = getOrCreateStateSet();
178 stateSet->setRenderBinDetails(1000, "RenderBin");
180 // speed optimization?
181 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
182 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
183 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
184 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
185 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
187 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
189 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
190 { drawImplementation(*renderInfo.getState()); }
191 void drawImplementation(osg::State& state) const
193 state.pushStateSet(getStateSet());
195 state.setActiveTextureUnit(0);
196 state.setClientActiveTextureUnit(0);
197 state.disableAllVertexArrays();
199 glPushAttrib(GL_ALL_ATTRIB_BITS);
200 glPushClientAttrib(~0u);
202 fgCockpitUpdate(&state);
204 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
205 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
208 // update the panel subsystem
209 if ( globals->get_current_panel() != NULL )
210 globals->get_current_panel()->update(state);
211 // We don't need a state here - can be safely removed when we can pick
219 state.dirtyAllModes();
220 state.dirtyAllAttributes();
221 state.dirtyAllVertexArrays();
224 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
225 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230 class FGLightSourceUpdateCallback : public osg::NodeCallback {
232 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
234 assert(dynamic_cast<osg::LightSource*>(node));
235 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
236 osg::Light* light = lightSource->getLight();
238 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
239 light->setAmbient(l->scene_ambient().osg());
240 light->setDiffuse(l->scene_diffuse().osg());
241 light->setSpecular(l->scene_specular().osg());
242 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
243 light->setPosition(position.osg());
244 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
245 light->setDirection(direction.osg());
246 light->setSpotExponent(0);
247 light->setSpotCutoff(180);
248 light->setConstantAttenuation(1);
249 light->setLinearAttenuation(0);
250 light->setQuadraticAttenuation(0);
256 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
258 FGWireFrameModeUpdateCallback() :
259 mWireframe(fgGetNode("/sim/rendering/wireframe"))
261 virtual void operator()(osg::StateAttribute* stateAttribute,
264 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
265 osg::PolygonMode* polygonMode;
266 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
268 if (mWireframe->getBoolValue())
269 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
270 osg::PolygonMode::LINE);
272 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
273 osg::PolygonMode::FILL);
276 SGSharedPtr<SGPropertyNode> mWireframe;
279 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
281 FGLightModelUpdateCallback() :
282 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
284 virtual void operator()(osg::StateAttribute* stateAttribute,
287 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
288 osg::LightModel* lightModel;
289 lightModel = static_cast<osg::LightModel*>(stateAttribute);
292 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
293 lightModel->setAmbientIntensity(l->scene_ambient().osg());
295 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
297 lightModel->setTwoSided(true);
298 lightModel->setLocalViewer(false);
300 if (mHighlights->getBoolValue()) {
301 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
303 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
307 SGSharedPtr<SGPropertyNode> mHighlights;
310 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
312 FGFogEnableUpdateCallback() :
313 mFogEnabled(fgGetNode("/sim/rendering/fog"))
315 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
317 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
318 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
320 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
324 SGSharedPtr<SGPropertyNode> mFogEnabled;
327 // fog constants. I'm a little nervous about putting actual code out
328 // here but it seems to work (?)
329 static const double m_log01 = -log( 0.01 );
330 static const double sqrt_m_log01 = sqrt( m_log01 );
331 static GLfloat fog_exp_density;
332 static GLfloat fog_exp2_density;
333 static GLfloat rwy_exp2_punch_through;
334 static GLfloat taxi_exp2_punch_through;
335 static GLfloat ground_exp2_punch_through;
340 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
341 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
342 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
344 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
346 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
347 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
349 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
350 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
351 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
352 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
354 FGRenderer::FGRenderer()
356 #ifdef FG_JPEG_SERVER
357 jpgRenderFrame = FGRenderer::update;
361 FGRenderer::~FGRenderer()
363 #ifdef FG_JPEG_SERVER
364 jpgRenderFrame = NULL;
368 // Initialize various GL/view parameters
370 FGRenderer::init( void ) {
372 osg::initNotifyLevel();
374 // The number of polygon-offset "units" to place between layers. In
375 // principle, one is supposed to be enough. In practice, I find that
376 // my hardware/driver requires many more.
377 osg::PolygonOffset::setUnitsMultiplier(1);
378 osg::PolygonOffset::setFactorMultiplier(1);
380 // Go full screen if requested ...
381 if ( fgGetBool("/sim/startup/fullscreen") )
384 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
385 (!fgGetBool("/sim/rendering/shading"))) {
386 // if fastest fog requested, or if flat shading force fastest
387 glHint ( GL_FOG_HINT, GL_FASTEST );
388 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
389 glHint ( GL_FOG_HINT, GL_DONT_CARE );
392 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
393 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
394 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
396 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
398 mFog->setMode(osg::Fog::EXP2);
399 mRunwayLightingFog->setMode(osg::Fog::EXP2);
400 mTaxiLightingFog->setMode(osg::Fog::EXP2);
401 mGroundLightingFog->setMode(osg::Fog::EXP2);
403 sceneView->setFrameStamp(mFrameStamp.get());
405 mUpdateVisitor = new SGUpdateVisitor;
406 sceneView->setUpdateVisitor(mUpdateVisitor.get());
408 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
409 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
412 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
414 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
416 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
417 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
419 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
420 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
421 stateSet->setAttribute(new osg::BlendFunc);
422 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
424 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
426 // this will be set below
427 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
429 osg::Material* material = new osg::Material;
430 stateSet->setAttribute(material);
432 stateSet->setTextureAttribute(0, new osg::TexEnv);
433 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
436 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
437 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
439 // this is the topmost scenegraph node for osg
440 mBackGroundCamera->addChild(thesky->getPreRoot());
441 mBackGroundCamera->setClearMask(0);
443 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
444 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
445 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
446 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
447 mBackGroundCamera->setInheritanceMask(inheritanceMask);
448 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
449 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
450 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
452 stateSet = mBackGroundCamera->getOrCreateStateSet();
453 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
455 osg::Group* sceneGroup = new osg::Group;
456 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
457 sceneGroup->addChild(thesky->getCloudRoot());
459 stateSet = sceneGroup->getOrCreateStateSet();
460 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
461 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
463 // need to update the light on every frame
464 osg::LightSource* lightSource = new osg::LightSource;
465 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
466 // relative because of CameraView being just a clever transform node
467 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
468 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
469 mRoot->addChild(lightSource);
471 lightSource->addChild(mBackGroundCamera.get());
472 lightSource->addChild(sceneGroup);
475 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
476 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
477 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
478 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
479 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
481 // enable disable specular highlights.
482 // is the place where we might plug in an other fragment shader ...
483 osg::LightModel* lightModel = new osg::LightModel;
484 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
485 stateSet->setAttribute(lightModel);
487 // switch to enable wireframe
488 osg::PolygonMode* polygonMode = new osg::PolygonMode;
489 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
490 stateSet->setAttributeAndModes(polygonMode);
492 // scene fog handling
493 stateSet->setAttributeAndModes(mFog.get());
494 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
497 osg::Camera* guiCamera = new osg::Camera;
498 guiCamera->setRenderOrder(osg::Camera::POST_RENDER);
499 guiCamera->setClearMask(0);
500 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
501 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
502 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
503 guiCamera->setInheritanceMask(inheritanceMask);
504 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
505 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
506 mRoot->addChild(guiCamera);
507 osg::Geode* geode = new osg::Geode;
508 geode->addDrawable(new SGPuDrawable);
509 geode->addDrawable(new SGHUDAndPanelDrawable);
510 guiCamera->addChild(geode);
512 // this one contains all lights, here we set the light states we did
513 // in the plib case with plain OpenGL
514 osg::Group* lightGroup = new osg::Group;
515 sceneGroup->addChild(lightGroup);
516 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
517 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
518 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
519 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
521 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
522 stateSet->setAttributeAndModes(mFog.get());
523 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
524 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
525 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
526 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
527 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
528 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
529 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
530 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
531 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
532 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
534 mCameraView->addChild(mRoot.get());
535 sceneView->setSceneData(mCameraView.get());
537 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
541 // Update all Visuals (redraws anything graphics related)
543 FGRenderer::update( bool refresh_camera_settings ) {
544 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
545 || fgGetBool("sim/sceneryloaded-override");
547 if ( idle_state < 1000 || !scenery_loaded ) {
548 if (sceneView.valid() && sceneView->getState()) {
549 sceneView->getState()->setActiveTextureUnit(0);
550 sceneView->getState()->setClientActiveTextureUnit(0);
551 sceneView->getState()->disableAllVertexArrays();
553 // still initializing, draw the splash screen
554 glPushAttrib(GL_ALL_ATTRIB_BITS);
555 glPushClientAttrib(~0u);
562 // Keep resetting sim time while the sim is initializing
563 globals->set_sim_time_sec( 0.0 );
567 bool skyblend = fgGetBool("/sim/rendering/skyblend");
568 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
569 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
570 bool distance_attenuation
571 = fgGetBool("/sim/rendering/distance-attenuation");
573 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
574 distance_attenuation );
576 static const SGPropertyNode *groundlevel_nearplane
577 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
579 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
582 double actual_visibility;
583 if (fgGetBool("/environment/clouds/status")) {
584 actual_visibility = thesky->get_visibility();
586 actual_visibility = fgGetDouble("/environment/visibility-m");
589 static double last_visibility = -9999;
590 if ( actual_visibility != last_visibility ) {
591 last_visibility = actual_visibility;
593 fog_exp_density = m_log01 / actual_visibility;
594 fog_exp2_density = sqrt_m_log01 / actual_visibility;
595 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
596 if ( actual_visibility < 8000 ) {
597 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
598 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
600 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
601 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
603 mFog->setDensity(fog_exp2_density);
604 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
605 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
606 mGroundLightingFog->setDensity(ground_exp2_punch_through);
609 // idle_state is now 1000 meaning we've finished all our
610 // initializations and are running the main loop, so this will
611 // now work without seg faulting the system.
613 FGViewer *current__view = globals->get_current_view();
614 // Force update of center dependent values ...
615 current__view->set_dirty();
617 if ( refresh_camera_settings ) {
619 resize( fgGetInt("/sim/startup/xsize"),
620 fgGetInt("/sim/startup/ysize") );
622 SGVec3d center = globals->get_scenery()->get_center();
623 SGVec3d position = current__view->getViewPosition();
624 SGQuatd attitude = current__view->getViewOrientation();
625 SGVec3d osgPosition = attitude.transform(center - position);
626 mCameraView->setPosition(osgPosition.osg());
627 mCameraView->setAttitude(inverse(attitude).osg());
631 if ( fgGetBool("/sim/rendering/textures") ) {
632 SGVec4f clearColor(l->adj_fog_color());
633 sceneView->getCamera()->setClearColor(clearColor.osg());
636 SGVec4f clearColor(l->sky_color());
637 sceneView->getCamera()->setClearColor(clearColor.osg());
640 // update fog params if visibility has changed
641 double visibility_meters = fgGetDouble("/environment/visibility-m");
642 thesky->set_visibility(visibility_meters);
644 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
645 ( global_multi_loop * fgGetInt("/sim/speed-up") )
646 / (double)fgGetInt("/sim/model-hz") );
648 // update the sky dome
651 // The sun and moon distances are scaled down versions
652 // of the actual distance to get both the moon and the sun
653 // within the range of the far clip plane.
654 // Moon distance: 384,467 kilometers
655 // Sun distance: 150,000,000 kilometers
657 double sun_horiz_eff, moon_horiz_eff;
658 if (fgGetBool("/sim/rendering/horizon-effect")) {
659 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
660 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
662 sun_horiz_eff = moon_horiz_eff = 1.0;
665 static SGSkyState sstate;
667 sstate.view_pos = current__view->get_view_pos();
668 sstate.zero_elev = current__view->get_zero_elev();
669 sstate.view_up = current__view->get_world_up();
670 sstate.lon = current__view->getLongitude_deg()
671 * SGD_DEGREES_TO_RADIANS;
672 sstate.lat = current__view->getLatitude_deg()
673 * SGD_DEGREES_TO_RADIANS;
674 sstate.alt = current__view->getAltitudeASL_ft()
676 sstate.spin = l->get_sun_rotation();
677 sstate.gst = globals->get_time_params()->getGst();
678 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
679 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
680 sstate.sun_dist = 50000.0 * sun_horiz_eff;
681 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
682 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
683 sstate.moon_dist = 40000.0 * moon_horiz_eff;
684 sstate.sun_angle = l->get_sun_angle();
688 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
689 << l->sky_color()[0] << " "
690 << l->sky_color()[1] << " "
691 << l->sky_color()[2] << " "
692 << l->sky_color()[3] );
693 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
694 << l->fog_color()[0] << " "
695 << l->fog_color()[1] << " "
696 << l->fog_color()[2] << " "
697 << l->fog_color()[3] );
698 SG_LOG( SG_GENERAL, SG_BULK,
699 " sun_angle = " << l->sun_angle
700 << " moon_angle = " << l->moon_angle );
703 static SGSkyColor scolor;
705 scolor.sky_color = SGVec3f(l->sky_color().data());
706 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
707 scolor.cloud_color = SGVec3f(l->cloud_color().data());
708 scolor.sun_angle = l->get_sun_angle();
709 scolor.moon_angle = l->get_moon_angle();
710 scolor.nplanets = globals->get_ephem()->getNumPlanets();
711 scolor.nstars = globals->get_ephem()->getNumStars();
712 scolor.planet_data = globals->get_ephem()->getPlanets();
713 scolor.star_data = globals->get_ephem()->getStars();
715 thesky->reposition( sstate, delta_time_sec );
716 thesky->repaint( scolor );
719 SG_LOG( SG_GENERAL, SG_BULK,
720 "thesky->reposition( view_pos = " << view_pos[0] << " "
721 << view_pos[1] << " " << view_pos[2] );
722 SG_LOG( SG_GENERAL, SG_BULK,
723 " zero_elev = " << zero_elev[0] << " "
724 << zero_elev[1] << " " << zero_elev[2]
725 << " lon = " << cur_fdm_state->get_Longitude()
726 << " lat = " << cur_fdm_state->get_Latitude() );
727 SG_LOG( SG_GENERAL, SG_BULK,
728 " sun_rot = " << l->get_sun_rotation
729 << " gst = " << SGTime::cur_time_params->getGst() );
730 SG_LOG( SG_GENERAL, SG_BULK,
731 " sun ra = " << globals->get_ephem()->getSunRightAscension()
732 << " sun dec = " << globals->get_ephem()->getSunDeclination()
733 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
734 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
738 // shadows->setupShadows(
739 // current__view->getLongitude_deg(),
740 // current__view->getLatitude_deg(),
741 // globals->get_time_params()->getGst(),
742 // globals->get_ephem()->getSunRightAscension(),
743 // globals->get_ephem()->getSunDeclination(),
744 // l->get_sun_angle());
748 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
749 SGVec4f color(l->adj_fog_color());
750 mFog->setColor(color.osg());
751 mRunwayLightingFog->setColor(color.osg());
752 mTaxiLightingFog->setColor(color.osg());
753 mGroundLightingFog->setColor(color.osg());
757 // sgEnviro.setLight(l->adj_fog_color());
759 // texture parameters
760 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
762 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
763 - current__view->getSGLocation()->get_cur_elev_m();
765 float scene_nearplane, scene_farplane;
767 scene_nearplane = 10.0f;
768 scene_farplane = 120000.0f;
770 scene_nearplane = groundlevel_nearplane->getDoubleValue();
771 scene_farplane = 120000.0f;
773 setNearFar( scene_nearplane, scene_farplane );
775 // sgEnviro.startOfFrame(current__view->get_view_pos(),
776 // current__view->get_world_up(),
777 // current__view->getLongitude_deg(),
778 // current__view->getLatitude_deg(),
779 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
783 // sgEnviro.drawLightning();
785 // double current_view_origin_airspeed_horiz_kt =
786 // fgGetDouble("/velocities/airspeed-kt", 0.0)
787 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
788 // * SGD_DEGREES_TO_RADIANS);
789 // TODO:find the real view speed, not the AC one
790 // sgEnviro.drawPrecipitation(
791 // fgGetDouble("/environment/metar/rain-norm", 0.0),
792 // fgGetDouble("/environment/metar/snow-norm", 0.0),
793 // fgGetDouble("/environment/metar/hail-norm", 0.0),
794 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
795 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
796 // - current__view->getHeadingOffset_deg(),
797 // current_view_origin_airspeed_horiz_kt
802 // shadows->endOfFrame();
804 // need to call the update visitor once
805 globals->get_aircraft_model()->select( true );
806 FGTileMgr::set_tile_filter( true );
807 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
808 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
809 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
810 mUpdateVisitor->setViewData(current__view->getViewPosition(),
811 current__view->getViewOrientation());
812 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
813 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
814 mUpdateVisitor->setLight(direction, l->scene_ambient(),
815 l->scene_diffuse(), l->scene_specular());
816 mUpdateVisitor->setVisibility(actual_visibility);
818 if (fgGetBool("/sim/panel-hotspots"))
819 sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
821 sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
830 // options.cxx needs to see this for toggle_panel()
831 // Handle new window size or exposure
833 FGRenderer::resize( int width, int height ) {
836 if ( (!fgGetBool("/sim/virtual-cockpit"))
837 && fgPanelVisible() && idle_state == 1000 ) {
838 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
839 globals->get_current_panel()->getYOffset()) / 768.0);
844 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
846 static int lastwidth = 0;
847 static int lastheight = 0;
848 if (width != lastwidth)
849 fgSetInt("/sim/startup/xsize", lastwidth = width);
850 if (height != lastheight)
851 fgSetInt("/sim/startup/ysize", lastheight = height);
853 guiInitMouse(width, height);
856 FGViewMgr *viewmgr = globals->get_viewmgr();
858 for ( int i = 0; i < viewmgr->size(); ++i ) {
859 viewmgr->get_view(i)->
860 set_aspect_ratio((float)view_h / (float)width);
863 setFOV( viewmgr->get_current_view()->get_h_fov(),
864 viewmgr->get_current_view()->get_v_fov() );
869 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
870 // which will post process and rewrite the resulting frustum if we
871 // want to do asymmetric view frustums.
873 static void fgHackFrustum() {
875 // specify a percent of the configured view frustum to actually
876 // display. This is a bit of a hack to achieve asymmetric view
877 // frustums. For instance, if you want to display two monitors
878 // side by side, you could specify each with a double fov, a 0.5
879 // aspect ratio multiplier, and then the left side monitor would
880 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
881 // and a top_pct = 1.0. The right side monitor would have a
882 // left_pct = 0.5 and a right_pct = 1.0.
884 static SGPropertyNode *left_pct
885 = fgGetNode("/sim/current-view/frustum-left-pct");
886 static SGPropertyNode *right_pct
887 = fgGetNode("/sim/current-view/frustum-right-pct");
888 static SGPropertyNode *bottom_pct
889 = fgGetNode("/sim/current-view/frustum-bottom-pct");
890 static SGPropertyNode *top_pct
891 = fgGetNode("/sim/current-view/frustum-top-pct");
896 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
897 // cout << " l = " << f->getLeft()
898 // << " r = " << f->getRight()
899 // << " b = " << f->getBot()
900 // << " t = " << f->getTop()
901 // << " n = " << f->getNear()
902 // << " f = " << f->getFar()
905 double width = right - left;
906 double height = top - bottom;
910 if ( left_pct != NULL ) {
911 l = left + width * left_pct->getDoubleValue();
916 if ( right_pct != NULL ) {
917 r = left + width * right_pct->getDoubleValue();
922 if ( bottom_pct != NULL ) {
923 b = bottom + height * bottom_pct->getDoubleValue();
928 if ( top_pct != NULL ) {
929 t = bottom + height * top_pct->getDoubleValue();
934 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
938 // we need some static storage space for these values. However, we
939 // can't store it in a renderer class object because the functions
940 // that manipulate these are static. They are static so they can
941 // interface to the display callback system. There's probably a
942 // better way, there has to be a better way, but I'm not seeing it
944 static float fov_width = 55.0;
945 static float fov_height = 42.0;
946 static float fov_near = 1.0;
947 static float fov_far = 1000.0;
950 /** FlightGear code should use this routine to set the FOV rather than
951 * calling the ssg routine directly
953 void FGRenderer::setFOV( float w, float h ) {
957 sceneView->setProjectionMatrixAsPerspective(fov_height,
958 fov_width/fov_height,
960 // fully specify the view frustum before hacking it (so we don't
961 // accumulate hacked effects
963 // sgEnviro.setFOV( w, h );
967 /** FlightGear code should use this routine to set the Near/Far clip
968 * planes rather than calling the ssg routine directly
970 void FGRenderer::setNearFar( float n, float f ) {
971 // OSGFIXME: we have currently too much z-buffer fights
976 sceneView->setProjectionMatrixAsPerspective(fov_height,
977 fov_width/fov_height,
980 // fully specify the view frustum before hacking it (so we don't
981 // accumulate hacked effects
986 FGRenderer::pick( unsigned x, unsigned y,
987 std::vector<SGSceneryPick>& pickList )
989 // wipe out the return ...
992 // we can get called early ...
993 if (!sceneView.valid())
996 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
999 osg::Viewport* viewport = sceneView->getViewport();
1003 // good old scenery center
1004 SGVec3d center = globals->get_scenery()->get_center();
1006 // don't know why, but the update has partly happened somehow,
1007 // so update the scenery part of the viewer
1008 FGViewer *current_view = globals->get_current_view();
1009 // Force update of center dependent values ...
1010 current_view->set_dirty();
1011 SGVec3d position = current_view->getViewPosition();
1012 SGQuatd attitude = current_view->getViewOrientation();
1013 SGVec3d osgPosition = attitude.transform(center - position);
1014 mCameraView->setPosition(osgPosition.osg());
1015 mCameraView->setAttitude(inverse(attitude).osg());
1017 osg::Matrix projection(sceneView->getProjectionMatrix());
1018 osg::Matrix modelview(sceneView->getViewMatrix());
1020 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1021 // modify the view matrix so that it accounts for this nodePath's
1022 // accumulated transform
1023 if (!nodePath.empty())
1024 modelview.preMult(computeLocalToWorld(nodePath.front()));
1026 // swap the y values ...
1027 y = viewport->height() - y;
1028 // set up the pick visitor
1029 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1030 sceneData->accept(pickVisitor);
1031 if (!pickVisitor.hits())
1034 // collect all interaction callbacks on the pick ray.
1035 // They get stored in the pickCallbacks list where they are sorted back
1036 // to front and croasest to finest wrt the scenery node they are attached to
1037 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1038 for (mi = pickVisitor.getSegHitList().begin();
1039 mi != pickVisitor.getSegHitList().end();
1041 osgUtil::IntersectVisitor::HitList::const_iterator hi;
1042 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1043 // ok, go back the nodes and ask for intersection callbacks,
1044 // execute them in top down order
1045 const osg::NodePath& np = hi->getNodePath();
1046 osg::NodePath::const_reverse_iterator npi;
1047 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1048 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1051 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1052 SGPickCallback* pickCallback = ud->getPickCallback(i);
1055 SGSceneryPick sceneryPick;
1056 /// note that this is done totally in doubles instead of
1057 /// just using getWorldIntersectionPoint
1058 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1059 sceneryPick.info.local = SGVec3d(localPt);
1060 if (hi->getMatrix())
1061 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1063 sceneryPick.info.wgs84 = SGVec3d(localPt);
1064 sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1065 sceneryPick.callback = pickCallback;
1066 pickList.push_back(sceneryPick);
1072 return !pickList.empty();
1075 // end of renderer.cxx