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/MatrixTransform>
50 #include <osg/Multisample>
52 #include <osg/PolygonMode>
53 #include <osg/ShadeModel>
55 #include <osg/TexEnvCombine>
58 #include <osg/ColorMatrix>
60 #include <osgUtil/SceneView>
61 #include <osgUtil/UpdateVisitor>
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65 #include <osgDB/ReadFile>
68 #include <simgear/math/SGMath.hxx>
69 #include <simgear/screen/extensions.hxx>
70 #include <simgear/scene/material/matlib.hxx>
71 #include <simgear/scene/model/animation.hxx>
72 #include <simgear/scene/model/model.hxx>
73 #include <simgear/scene/model/modellib.hxx>
74 #include <simgear/scene/model/placement.hxx>
75 #include <simgear/scene/util/SGUpdateVisitor.hxx>
76 #include <simgear/scene/tgdb/pt_lights.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
82 #include <simgear/screen/jpgfactory.hxx>
85 #include <simgear/environment/visual_enviro.hxx>
87 #include <Scenery/tileentry.hxx>
88 #include <Time/light.hxx>
89 #include <Time/light.hxx>
90 #include <Aircraft/aircraft.hxx>
91 #include <Cockpit/panel.hxx>
92 #include <Cockpit/cockpit.hxx>
93 #include <Cockpit/hud.hxx>
94 #include <Model/panelnode.hxx>
95 #include <Model/modelmgr.hxx>
96 #include <Model/acmodel.hxx>
97 #include <Scenery/scenery.hxx>
98 #include <Scenery/tilemgr.hxx>
99 #include <ATC/ATCdisplay.hxx>
100 #include <GUI/new_gui.hxx>
101 #include <Instrumentation/instrument_mgr.hxx>
102 #include <Instrumentation/HUD/HUD.hxx>
104 #include "splash.hxx"
105 #include "renderer.hxx"
108 class SGPuDrawable : public osg::Drawable {
112 // Dynamic stuff, do not store geometry
113 setUseDisplayList(false);
115 osg::StateSet* stateSet = getOrCreateStateSet();
116 stateSet->setRenderBinDetails(1001, "RenderBin");
117 // speed optimization?
118 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
119 // We can do translucent menus, so why not. :-)
120 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
121 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
122 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
124 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
126 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
127 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
129 virtual void drawImplementation(osg::State& state) const
131 state.pushStateSet(getStateSet());
135 if((fgGetBool("/sim/atc/enabled"))
136 || (fgGetBool("/sim/ai-traffic/enabled")))
137 globals->get_ATC_display()->update(delta_time_sec, state);
142 // Fade out the splash screen over the first three seconds.
143 double t = globals->get_sim_time_sec();
145 glPushAttrib(GL_ALL_ATTRIB_BITS);
146 glPushClientAttrib(~0u);
148 fgSplashUpdate((2.5 - t) / 2.5);
157 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
158 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
163 class SGHUDAndPanelDrawable : public osg::Drawable {
165 SGHUDAndPanelDrawable()
167 // Dynamic stuff, do not store geometry
168 setUseDisplayList(false);
170 osg::StateSet* stateSet = getOrCreateStateSet();
171 stateSet->setRenderBinDetails(1000, "RenderBin");
173 // speed optimization?
174 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
175 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
176 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
177 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
178 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
180 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
182 virtual void drawImplementation(osg::State& state) const
184 state.pushStateSet(getStateSet());
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
209 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
210 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
215 class FGLightSourceUpdateCallback : public osg::NodeCallback {
217 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
219 assert(dynamic_cast<osg::LightSource*>(node));
220 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
221 osg::Light* light = lightSource->getLight();
223 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
224 light->setAmbient(l->scene_ambient().osg());
225 light->setDiffuse(l->scene_diffuse().osg());
226 light->setSpecular(l->scene_specular().osg());
227 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
228 light->setPosition(position.osg());
229 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
230 light->setDirection(direction.osg());
231 light->setSpotExponent(0);
232 light->setSpotCutoff(180);
233 light->setConstantAttenuation(1);
234 light->setLinearAttenuation(0);
235 light->setQuadraticAttenuation(0);
241 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
243 FGWireFrameModeUpdateCallback() :
244 mWireframe(fgGetNode("/sim/rendering/wireframe"))
246 virtual void operator()(osg::StateAttribute* stateAttribute,
249 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
250 osg::PolygonMode* polygonMode;
251 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
253 if (mWireframe->getBoolValue())
254 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
255 osg::PolygonMode::LINE);
257 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
258 osg::PolygonMode::FILL);
261 SGSharedPtr<SGPropertyNode> mWireframe;
264 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
266 FGLightModelUpdateCallback() :
267 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
269 virtual void operator()(osg::StateAttribute* stateAttribute,
272 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
273 osg::LightModel* lightModel;
274 lightModel = static_cast<osg::LightModel*>(stateAttribute);
277 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
278 lightModel->setAmbientIntensity(l->scene_ambient().osg());
280 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
282 lightModel->setTwoSided(true);
283 lightModel->setLocalViewer(false);
285 if (mHighlights->getBoolValue()) {
286 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
288 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
292 SGSharedPtr<SGPropertyNode> mHighlights;
295 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
297 FGFogEnableUpdateCallback() :
298 mFogEnabled(fgGetNode("/sim/rendering/fog"))
300 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
302 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
303 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
305 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
309 SGSharedPtr<SGPropertyNode> mFogEnabled;
312 // fog constants. I'm a little nervous about putting actual code out
313 // here but it seems to work (?)
314 static const double m_log01 = -log( 0.01 );
315 static const double sqrt_m_log01 = sqrt( m_log01 );
316 static GLfloat fog_exp_density;
317 static GLfloat fog_exp2_density;
318 static GLfloat rwy_exp2_punch_through;
319 static GLfloat taxi_exp2_punch_through;
320 static GLfloat ground_exp2_punch_through;
325 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
326 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
327 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
329 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
331 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
332 static osg::ref_ptr<osg::CameraNode> mBackGroundCamera = new osg::CameraNode;
333 osg::ref_ptr<osg::CameraNode> mSceneCamera = new osg::CameraNode;
335 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
336 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
337 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
338 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
340 FGRenderer::FGRenderer()
342 #ifdef FG_JPEG_SERVER
343 jpgRenderFrame = FGRenderer::update;
347 FGRenderer::~FGRenderer()
349 #ifdef FG_JPEG_SERVER
350 jpgRenderFrame = NULL;
354 // Initialize various GL/view parameters
356 FGRenderer::init( void ) {
358 osg::initNotifyLevel();
360 // Go full screen if requested ...
361 if ( fgGetBool("/sim/startup/fullscreen") )
364 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
365 (!fgGetBool("/sim/rendering/shading"))) {
366 // if fastest fog requested, or if flat shading force fastest
367 glHint ( GL_FOG_HINT, GL_FASTEST );
368 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
369 glHint ( GL_FOG_HINT, GL_DONT_CARE );
372 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
373 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
374 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
376 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
378 mFog->setMode(osg::Fog::EXP2);
379 mRunwayLightingFog->setMode(osg::Fog::EXP2);
380 mTaxiLightingFog->setMode(osg::Fog::EXP2);
381 mGroundLightingFog->setMode(osg::Fog::EXP2);
383 sceneView->setFrameStamp(mFrameStamp.get());
385 mUpdateVisitor = new SGUpdateVisitor;
386 sceneView->setUpdateVisitor(mUpdateVisitor.get());
388 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
390 sceneView->getCamera()->setViewMatrix(osg::Matrix(0, 0,-1, 0,
394 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
395 sceneView->getCamera()->setClearMask(GL_COLOR_BUFFER_BIT);
397 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
399 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
401 stateSet->setAttribute(new osg::Depth(osg::Depth::LEQUAL));
402 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
404 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
405 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
406 stateSet->setAttribute(new osg::BlendFunc);
407 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
409 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
411 // this will be set below
412 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
414 osg::Material* material = new osg::Material;
415 stateSet->setAttribute(material);
417 stateSet->setTextureAttribute(0, new osg::TexEnv);
418 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
421 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
422 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
425 // this is the topmost scenegraph node for osg
426 mBackGroundCamera->addChild(thesky->getPreRoot());
427 mBackGroundCamera->setClearMask(0);
429 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
430 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
431 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
432 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
433 mBackGroundCamera->setInheritanceMask(inheritanceMask);
434 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
435 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
436 mBackGroundCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
438 mBackGroundCamera->getOrCreateStateSet()->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
440 mRoot->addChild(mBackGroundCamera.get());
442 mSceneCamera->setClearMask(GL_DEPTH_BUFFER_BIT);
443 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
444 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
445 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
446 mSceneCamera->setInheritanceMask(inheritanceMask);
447 mSceneCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
448 mSceneCamera->setCullingMode(osg::CullSettings::DEFAULT_CULLING);
449 mSceneCamera->setRenderOrder(osg::CameraNode::NESTED_RENDER);
450 mRoot->addChild(mSceneCamera.get());
452 stateSet = mSceneCamera->getOrCreateStateSet();
453 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
454 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
456 // need to update the light on every frame
457 osg::LightSource* lightSource = new osg::LightSource;
458 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
459 // relative because of CameraView being just a clever transform node
460 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
461 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
462 mSceneCamera->addChild(lightSource);
464 lightSource->addChild(globals->get_scenery()->get_scene_graph());
465 lightSource->addChild(thesky->getCloudRoot());
467 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
468 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
469 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
470 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
471 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
473 // enable disable specular highlights.
474 // is the place where we might plug in an other fragment shader ...
475 osg::LightModel* lightModel = new osg::LightModel;
476 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
477 stateSet->setAttribute(lightModel);
479 // switch to enable wireframe
480 osg::PolygonMode* polygonMode = new osg::PolygonMode;
481 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
482 stateSet->setAttributeAndModes(polygonMode);
484 // scene fog handling
485 stateSet->setAttributeAndModes(mFog.get());
486 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
489 osg::CameraNode* guiCamera = new osg::CameraNode;
490 guiCamera->setRenderOrder(osg::CameraNode::POST_RENDER);
491 guiCamera->setClearMask(0);
492 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
493 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
494 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
495 guiCamera->setInheritanceMask(inheritanceMask);
496 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
497 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
498 mRoot->addChild(guiCamera);
499 osg::Geode* geode = new osg::Geode;
500 geode->addDrawable(new SGPuDrawable);
501 geode->addDrawable(new SGHUDAndPanelDrawable);
502 guiCamera->addChild(geode);
504 // this one contains all lights, here we set the light states we did
505 // in the plib case with plain OpenGL
506 osg::Group* lightGroup = new osg::Group;
507 mSceneCamera->addChild(lightGroup);
508 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
509 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
510 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
511 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
513 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
514 stateSet->setAttributeAndModes(mFog.get());
515 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
516 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
517 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
518 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
519 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
520 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
521 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
522 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
523 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
524 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
526 mCameraView->addChild(mRoot.get());
527 sceneView->setSceneData(mCameraView.get());
529 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
533 // Update all Visuals (redraws anything graphics related)
535 FGRenderer::update( bool refresh_camera_settings ) {
536 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
537 || fgGetBool("sim/sceneryloaded-override");
539 if ( idle_state < 1000 || !scenery_loaded ) {
540 // still initializing, draw the splash screen
541 glPushAttrib(GL_ALL_ATTRIB_BITS);
542 glPushClientAttrib(~0u);
549 // Keep resetting sim time while the sim is initializing
550 globals->set_sim_time_sec( 0.0 );
554 bool skyblend = fgGetBool("/sim/rendering/skyblend");
555 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
556 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
557 bool distance_attenuation
558 = fgGetBool("/sim/rendering/distance-attenuation");
560 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
561 distance_attenuation );
563 static const SGPropertyNode *groundlevel_nearplane
564 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
566 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
569 double actual_visibility;
570 if (fgGetBool("/environment/clouds/status")) {
571 actual_visibility = thesky->get_visibility();
573 actual_visibility = fgGetDouble("/environment/visibility-m");
576 static double last_visibility = -9999;
577 if ( actual_visibility != last_visibility ) {
578 last_visibility = actual_visibility;
580 fog_exp_density = m_log01 / actual_visibility;
581 fog_exp2_density = sqrt_m_log01 / actual_visibility;
582 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
583 if ( actual_visibility < 8000 ) {
584 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
585 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
587 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
588 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
590 mFog->setDensity(fog_exp2_density);
591 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
592 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
593 mGroundLightingFog->setDensity(ground_exp2_punch_through);
596 // idle_state is now 1000 meaning we've finished all our
597 // initializations and are running the main loop, so this will
598 // now work without seg faulting the system.
600 FGViewer *current__view = globals->get_current_view();
601 // Force update of center dependent values ...
602 current__view->set_dirty();
604 if ( refresh_camera_settings ) {
606 resize( fgGetInt("/sim/startup/xsize"),
607 fgGetInt("/sim/startup/ysize") );
609 SGVec3d center = globals->get_scenery()->get_center();
610 SGVec3d position = current__view->getViewPosition();
611 SGQuatd attitude = current__view->getViewOrientation();
612 SGVec3d osgPosition = attitude.transform(center - position);
613 mCameraView->setPosition(osgPosition.osg());
614 mCameraView->setAttitude(inverse(attitude).osg());
618 if ( fgGetBool("/sim/rendering/textures") ) {
619 SGVec4f clearColor(l->adj_fog_color());
620 sceneView->getCamera()->setClearColor(clearColor.osg());
623 SGVec4f clearColor(l->sky_color());
624 sceneView->getCamera()->setClearColor(clearColor.osg());
627 // update fog params if visibility has changed
628 double visibility_meters = fgGetDouble("/environment/visibility-m");
629 thesky->set_visibility(visibility_meters);
631 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
632 ( global_multi_loop * fgGetInt("/sim/speed-up") )
633 / (double)fgGetInt("/sim/model-hz") );
635 // update the sky dome
638 // The sun and moon distances are scaled down versions
639 // of the actual distance to get both the moon and the sun
640 // within the range of the far clip plane.
641 // Moon distance: 384,467 kilometers
642 // Sun distance: 150,000,000 kilometers
644 double sun_horiz_eff, moon_horiz_eff;
645 if (fgGetBool("/sim/rendering/horizon-effect")) {
646 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
647 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
649 sun_horiz_eff = moon_horiz_eff = 1.0;
652 static SGSkyState sstate;
654 sstate.view_pos = current__view->get_view_pos();
655 sstate.zero_elev = current__view->get_zero_elev();
656 sstate.view_up = current__view->get_world_up();
657 sstate.lon = current__view->getLongitude_deg()
658 * SGD_DEGREES_TO_RADIANS;
659 sstate.lat = current__view->getLatitude_deg()
660 * SGD_DEGREES_TO_RADIANS;
661 sstate.alt = current__view->getAltitudeASL_ft()
663 sstate.spin = l->get_sun_rotation();
664 sstate.gst = globals->get_time_params()->getGst();
665 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
666 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
667 sstate.sun_dist = 50000.0 * sun_horiz_eff;
668 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
669 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
670 sstate.moon_dist = 40000.0 * moon_horiz_eff;
671 sstate.sun_angle = l->get_sun_angle();
675 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
676 << l->sky_color()[0] << " "
677 << l->sky_color()[1] << " "
678 << l->sky_color()[2] << " "
679 << l->sky_color()[3] );
680 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
681 << l->fog_color()[0] << " "
682 << l->fog_color()[1] << " "
683 << l->fog_color()[2] << " "
684 << l->fog_color()[3] );
685 SG_LOG( SG_GENERAL, SG_BULK,
686 " sun_angle = " << l->sun_angle
687 << " moon_angle = " << l->moon_angle );
690 static SGSkyColor scolor;
692 scolor.sky_color = SGVec3f(l->sky_color().data());
693 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
694 scolor.cloud_color = SGVec3f(l->cloud_color().data());
695 scolor.sun_angle = l->get_sun_angle();
696 scolor.moon_angle = l->get_moon_angle();
697 scolor.nplanets = globals->get_ephem()->getNumPlanets();
698 scolor.nstars = globals->get_ephem()->getNumStars();
699 scolor.planet_data = globals->get_ephem()->getPlanets();
700 scolor.star_data = globals->get_ephem()->getStars();
702 thesky->reposition( sstate, delta_time_sec );
703 thesky->repaint( scolor );
706 SG_LOG( SG_GENERAL, SG_BULK,
707 "thesky->reposition( view_pos = " << view_pos[0] << " "
708 << view_pos[1] << " " << view_pos[2] );
709 SG_LOG( SG_GENERAL, SG_BULK,
710 " zero_elev = " << zero_elev[0] << " "
711 << zero_elev[1] << " " << zero_elev[2]
712 << " lon = " << cur_fdm_state->get_Longitude()
713 << " lat = " << cur_fdm_state->get_Latitude() );
714 SG_LOG( SG_GENERAL, SG_BULK,
715 " sun_rot = " << l->get_sun_rotation
716 << " gst = " << SGTime::cur_time_params->getGst() );
717 SG_LOG( SG_GENERAL, SG_BULK,
718 " sun ra = " << globals->get_ephem()->getSunRightAscension()
719 << " sun dec = " << globals->get_ephem()->getSunDeclination()
720 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
721 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
725 // shadows->setupShadows(
726 // current__view->getLongitude_deg(),
727 // current__view->getLatitude_deg(),
728 // globals->get_time_params()->getGst(),
729 // globals->get_ephem()->getSunRightAscension(),
730 // globals->get_ephem()->getSunDeclination(),
731 // l->get_sun_angle());
735 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
736 SGVec4f color(l->adj_fog_color());
737 mFog->setColor(color.osg());
738 mRunwayLightingFog->setColor(color.osg());
739 mTaxiLightingFog->setColor(color.osg());
740 mGroundLightingFog->setColor(color.osg());
744 // sgEnviro.setLight(l->adj_fog_color());
746 // texture parameters
747 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
749 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
750 - current__view->getSGLocation()->get_cur_elev_m();
752 float scene_nearplane, scene_farplane;
754 scene_nearplane = 10.0f;
755 scene_farplane = 120000.0f;
757 scene_nearplane = groundlevel_nearplane->getDoubleValue();
758 scene_farplane = 120000.0f;
761 setNearFar( scene_nearplane, scene_farplane );
763 // sgEnviro.startOfFrame(current__view->get_view_pos(),
764 // current__view->get_world_up(),
765 // current__view->getLongitude_deg(),
766 // current__view->getLatitude_deg(),
767 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
771 // sgEnviro.drawLightning();
773 // double current_view_origin_airspeed_horiz_kt =
774 // fgGetDouble("/velocities/airspeed-kt", 0.0)
775 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
776 // * SGD_DEGREES_TO_RADIANS);
777 // TODO:find the real view speed, not the AC one
778 // sgEnviro.drawPrecipitation(
779 // fgGetDouble("/environment/metar/rain-norm", 0.0),
780 // fgGetDouble("/environment/metar/snow-norm", 0.0),
781 // fgGetDouble("/environment/metar/hail-norm", 0.0),
782 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
783 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
784 // - current__view->getHeadingOffset_deg(),
785 // current_view_origin_airspeed_horiz_kt
790 // shadows->endOfFrame();
792 // need to call the update visitor once
793 globals->get_aircraft_model()->select( true );
794 FGTileMgr::set_tile_filter( true );
795 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
796 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
797 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
798 mUpdateVisitor->setViewData(current__view->getViewPosition(),
799 current__view->getViewOrientation());
800 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
801 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
802 mUpdateVisitor->setLight(direction, l->scene_ambient(),
803 l->scene_diffuse(), l->scene_specular());
804 mUpdateVisitor->setVisibility(actual_visibility);
812 // options.cxx needs to see this for toggle_panel()
813 // Handle new window size or exposure
815 FGRenderer::resize( int width, int height ) {
818 if ( (!fgGetBool("/sim/virtual-cockpit"))
819 && fgPanelVisible() && idle_state == 1000 ) {
820 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
821 globals->get_current_panel()->getYOffset()) / 768.0);
826 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
828 static int lastwidth = 0;
829 static int lastheight = 0;
830 if (width != lastwidth)
831 fgSetInt("/sim/startup/xsize", lastwidth = width);
832 if (height != lastheight)
833 fgSetInt("/sim/startup/ysize", lastheight = height);
835 guiInitMouse(width, height);
838 FGViewMgr *viewmgr = globals->get_viewmgr();
840 for ( int i = 0; i < viewmgr->size(); ++i ) {
841 viewmgr->get_view(i)->
842 set_aspect_ratio((float)view_h / (float)width);
845 setFOV( viewmgr->get_current_view()->get_h_fov(),
846 viewmgr->get_current_view()->get_v_fov() );
847 // cout << "setFOV(" << viewmgr->get_current_view()->get_h_fov()
848 // << ", " << viewmgr->get_current_view()->get_v_fov() << ")"
854 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
855 // which will post process and rewrite the resulting frustum if we
856 // want to do asymmetric view frustums.
858 static void fgHackFrustum() {
860 // specify a percent of the configured view frustum to actually
861 // display. This is a bit of a hack to achieve asymmetric view
862 // frustums. For instance, if you want to display two monitors
863 // side by side, you could specify each with a double fov, a 0.5
864 // aspect ratio multiplier, and then the left side monitor would
865 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
866 // and a top_pct = 1.0. The right side monitor would have a
867 // left_pct = 0.5 and a right_pct = 1.0.
869 static SGPropertyNode *left_pct
870 = fgGetNode("/sim/current-view/frustum-left-pct");
871 static SGPropertyNode *right_pct
872 = fgGetNode("/sim/current-view/frustum-right-pct");
873 static SGPropertyNode *bottom_pct
874 = fgGetNode("/sim/current-view/frustum-bottom-pct");
875 static SGPropertyNode *top_pct
876 = fgGetNode("/sim/current-view/frustum-top-pct");
881 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
882 // cout << " l = " << f->getLeft()
883 // << " r = " << f->getRight()
884 // << " b = " << f->getBot()
885 // << " t = " << f->getTop()
886 // << " n = " << f->getNear()
887 // << " f = " << f->getFar()
890 double width = right - left;
891 double height = top - bottom;
895 if ( left_pct != NULL ) {
896 l = left + width * left_pct->getDoubleValue();
901 if ( right_pct != NULL ) {
902 r = left + width * right_pct->getDoubleValue();
907 if ( bottom_pct != NULL ) {
908 b = bottom + height * bottom_pct->getDoubleValue();
913 if ( top_pct != NULL ) {
914 t = bottom + height * top_pct->getDoubleValue();
919 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
923 // we need some static storage space for these values. However, we
924 // can't store it in a renderer class object because the functions
925 // that manipulate these are static. They are static so they can
926 // interface to the display callback system. There's probably a
927 // better way, there has to be a better way, but I'm not seeing it
929 static float fov_width = 55.0;
930 static float fov_height = 42.0;
931 static float fov_near = 1.0;
932 static float fov_far = 1000.0;
935 /** FlightGear code should use this routine to set the FOV rather than
936 * calling the ssg routine directly
938 void FGRenderer::setFOV( float w, float h ) {
942 sceneView->setProjectionMatrixAsPerspective(fov_height,
943 fov_width/fov_height,
945 // fully specify the view frustum before hacking it (so we don't
946 // accumulate hacked effects
948 // sgEnviro.setFOV( w, h );
952 /** FlightGear code should use this routine to set the Near/Far clip
953 * planes rather than calling the ssg routine directly
955 void FGRenderer::setNearFar( float n, float f ) {
956 // OSGFIXME: we have currently too much z-buffer fights
961 sceneView->setProjectionMatrixAsPerspective(fov_height,
962 fov_width/fov_height,
965 sceneView->getCamera()->setNearFarRatio(fov_near/fov_far);
966 mSceneCamera->setNearFarRatio(fov_near/fov_far);
968 // fully specify the view frustum before hacking it (so we don't
969 // accumulate hacked effects
973 bool FGRenderer::getPickInfo( SGVec3d& pt, SGVec3d& dir,
974 unsigned x, unsigned y )
976 // Get the matrices involved in the transform from global to screen
978 osg::Matrix pm = sceneView->getCamera()->getProjectionMatrix();
981 osg::NodePathList paths;
982 paths = globals->get_scenery()->get_scene_graph()->getParentalNodePaths();
983 if (!paths.empty()) {
984 // Ok, we know that this should not have multiple parents ...
985 // FIXME: is this allways true?
986 mv = osg::computeLocalToEye(sceneView->getCamera()->getViewMatrix(),
987 paths.front(), false);
990 // Compose and invert
991 osg::Matrix m = osg::Matrix::inverse(mv*pm);
993 // Get the width and height of the display to be able to normalize the
995 float width = fgGetInt("/sim/startup/xsize");
996 float height = fgGetInt("/sim/startup/ysize");
998 // Compute some coordinates of in the line from the eyepoint to the
999 // mouse click coodinates.
1000 // First build the normalized projection coordinates
1001 osg::Vec4 normPt((2*x - width)/width, -(2*y - height)/height, 1, 1);
1002 // Transform them into the real world
1003 osg::Vec4 worldPt4 = m.preMult(normPt);
1004 if (fabs(worldPt4[3]) < SGLimitsf::min())
1006 SGVec3f worldPt(worldPt4[0]/worldPt4[3],
1007 worldPt4[1]/worldPt4[3],
1008 worldPt4[2]/worldPt4[3]);
1010 // Now build a direction from the point
1011 FGViewer* view = globals->get_current_view();
1012 dir = normalize(toVec3d(worldPt - SGVec3f(view->get_view_pos())));
1014 // Copy the start point
1015 pt = SGVec3d(view->get_absolute_view_pos());
1017 // OSGFIXME: ist this sufficient??? especially the precision problems here??
1018 // bool mSceneView->projectWindowXYIntoObject(int x,int y,osg::Vec3& near_point,osg::Vec3& far_point) const;
1024 // end of renderer.cxx