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::State& state) const
126 state.pushStateSet(getStateSet());
128 state.setActiveTextureUnit(0);
129 state.setClientActiveTextureUnit(0);
130 state.disableAllVertexArrays();
132 if((fgGetBool("/sim/atc/enabled"))
133 || (fgGetBool("/sim/ai-traffic/enabled")))
134 globals->get_ATC_display()->update(delta_time_sec, state);
138 // Fade out the splash screen over the first three seconds.
139 double t = globals->get_sim_time_sec();
141 glPushAttrib(GL_ALL_ATTRIB_BITS);
142 glPushClientAttrib(~0u);
144 fgSplashUpdate((2.5 - t) / 2.5);
151 state.dirtyAllModes();
152 state.dirtyAllAttributes();
153 state.dirtyAllVertexArrays();
156 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
157 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
162 class SGHUDAndPanelDrawable : public osg::Drawable {
164 SGHUDAndPanelDrawable()
166 // Dynamic stuff, do not store geometry
167 setUseDisplayList(false);
169 osg::StateSet* stateSet = getOrCreateStateSet();
170 stateSet->setRenderBinDetails(1000, "RenderBin");
172 // speed optimization?
173 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
174 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
175 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
176 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
177 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
179 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
181 virtual void drawImplementation(osg::State& state) const
183 state.pushStateSet(getStateSet());
185 state.setActiveTextureUnit(0);
186 state.setClientActiveTextureUnit(0);
187 state.disableAllVertexArrays();
189 glPushAttrib(GL_ALL_ATTRIB_BITS);
190 glPushClientAttrib(~0u);
192 fgCockpitUpdate(&state);
194 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
195 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
198 // update the panel subsystem
199 if ( globals->get_current_panel() != NULL )
200 globals->get_current_panel()->update(state);
201 // We don't need a state here - can be safely removed when we can pick
209 state.dirtyAllModes();
210 state.dirtyAllAttributes();
211 state.dirtyAllVertexArrays();
214 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
215 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
220 class FGLightSourceUpdateCallback : public osg::NodeCallback {
222 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
224 assert(dynamic_cast<osg::LightSource*>(node));
225 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
226 osg::Light* light = lightSource->getLight();
228 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
229 light->setAmbient(l->scene_ambient().osg());
230 light->setDiffuse(l->scene_diffuse().osg());
231 light->setSpecular(l->scene_specular().osg());
232 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
233 light->setPosition(position.osg());
234 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
235 light->setDirection(direction.osg());
236 light->setSpotExponent(0);
237 light->setSpotCutoff(180);
238 light->setConstantAttenuation(1);
239 light->setLinearAttenuation(0);
240 light->setQuadraticAttenuation(0);
246 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
248 FGWireFrameModeUpdateCallback() :
249 mWireframe(fgGetNode("/sim/rendering/wireframe"))
251 virtual void operator()(osg::StateAttribute* stateAttribute,
254 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
255 osg::PolygonMode* polygonMode;
256 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
258 if (mWireframe->getBoolValue())
259 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
260 osg::PolygonMode::LINE);
262 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
263 osg::PolygonMode::FILL);
266 SGSharedPtr<SGPropertyNode> mWireframe;
269 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
271 FGLightModelUpdateCallback() :
272 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
274 virtual void operator()(osg::StateAttribute* stateAttribute,
277 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
278 osg::LightModel* lightModel;
279 lightModel = static_cast<osg::LightModel*>(stateAttribute);
282 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
283 lightModel->setAmbientIntensity(l->scene_ambient().osg());
285 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
287 lightModel->setTwoSided(true);
288 lightModel->setLocalViewer(false);
290 if (mHighlights->getBoolValue()) {
291 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
293 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
297 SGSharedPtr<SGPropertyNode> mHighlights;
300 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
302 FGFogEnableUpdateCallback() :
303 mFogEnabled(fgGetNode("/sim/rendering/fog"))
305 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
307 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
308 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
310 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
314 SGSharedPtr<SGPropertyNode> mFogEnabled;
317 // fog constants. I'm a little nervous about putting actual code out
318 // here but it seems to work (?)
319 static const double m_log01 = -log( 0.01 );
320 static const double sqrt_m_log01 = sqrt( m_log01 );
321 static GLfloat fog_exp_density;
322 static GLfloat fog_exp2_density;
323 static GLfloat rwy_exp2_punch_through;
324 static GLfloat taxi_exp2_punch_through;
325 static GLfloat ground_exp2_punch_through;
330 static osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;
331 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
332 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
334 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
336 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
337 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
339 static osg::ref_ptr<osg::Fog> mFog = new osg::Fog;
340 static osg::ref_ptr<osg::Fog> mRunwayLightingFog = new osg::Fog;
341 static osg::ref_ptr<osg::Fog> mTaxiLightingFog = new osg::Fog;
342 static osg::ref_ptr<osg::Fog> mGroundLightingFog = new osg::Fog;
344 FGRenderer::FGRenderer()
346 #ifdef FG_JPEG_SERVER
347 jpgRenderFrame = FGRenderer::update;
351 FGRenderer::~FGRenderer()
353 #ifdef FG_JPEG_SERVER
354 jpgRenderFrame = NULL;
358 // Initialize various GL/view parameters
360 FGRenderer::init( void ) {
362 osg::initNotifyLevel();
364 // The number of polygon-offset "units" to place between layers. In
365 // principle, one is supposed to be enough. In practice, I find that
366 // my hardware/driver requires many more.
367 osg::PolygonOffset::setUnitsMultiplier(1);
368 osg::PolygonOffset::setFactorMultiplier(1);
370 // Go full screen if requested ...
371 if ( fgGetBool("/sim/startup/fullscreen") )
374 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
375 (!fgGetBool("/sim/rendering/shading"))) {
376 // if fastest fog requested, or if flat shading force fastest
377 glHint ( GL_FOG_HINT, GL_FASTEST );
378 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
379 glHint ( GL_FOG_HINT, GL_DONT_CARE );
382 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
383 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
384 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
386 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
388 mFog->setMode(osg::Fog::EXP2);
389 mRunwayLightingFog->setMode(osg::Fog::EXP2);
390 mTaxiLightingFog->setMode(osg::Fog::EXP2);
391 mGroundLightingFog->setMode(osg::Fog::EXP2);
393 sceneView->setFrameStamp(mFrameStamp.get());
395 mUpdateVisitor = new SGUpdateVisitor;
396 sceneView->setUpdateVisitor(mUpdateVisitor.get());
398 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
399 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
402 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
404 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
406 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
407 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
409 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
410 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
411 stateSet->setAttribute(new osg::BlendFunc);
412 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
414 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
416 // this will be set below
417 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
419 osg::Material* material = new osg::Material;
420 stateSet->setAttribute(material);
422 stateSet->setTextureAttribute(0, new osg::TexEnv);
423 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
426 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
427 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
429 // this is the topmost scenegraph node for osg
430 mBackGroundCamera->addChild(thesky->getPreRoot());
431 mBackGroundCamera->setClearMask(0);
433 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
434 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
435 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
436 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
437 mBackGroundCamera->setInheritanceMask(inheritanceMask);
438 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
439 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
440 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
442 stateSet = mBackGroundCamera->getOrCreateStateSet();
443 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
445 osg::Group* sceneGroup = new osg::Group;
446 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
447 sceneGroup->addChild(thesky->getCloudRoot());
449 stateSet = sceneGroup->getOrCreateStateSet();
450 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
451 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
453 // need to update the light on every frame
454 osg::LightSource* lightSource = new osg::LightSource;
455 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
456 // relative because of CameraView being just a clever transform node
457 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
458 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
459 mRoot->addChild(lightSource);
461 lightSource->addChild(mBackGroundCamera.get());
462 lightSource->addChild(sceneGroup);
465 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
466 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
467 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
468 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
469 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
471 // enable disable specular highlights.
472 // is the place where we might plug in an other fragment shader ...
473 osg::LightModel* lightModel = new osg::LightModel;
474 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
475 stateSet->setAttribute(lightModel);
477 // switch to enable wireframe
478 osg::PolygonMode* polygonMode = new osg::PolygonMode;
479 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
480 stateSet->setAttributeAndModes(polygonMode);
482 // scene fog handling
483 stateSet->setAttributeAndModes(mFog.get());
484 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
487 osg::Camera* guiCamera = new osg::Camera;
488 guiCamera->setRenderOrder(osg::Camera::POST_RENDER);
489 guiCamera->setClearMask(0);
490 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
491 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
492 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
493 guiCamera->setInheritanceMask(inheritanceMask);
494 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
495 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
496 mRoot->addChild(guiCamera);
497 osg::Geode* geode = new osg::Geode;
498 geode->addDrawable(new SGPuDrawable);
499 geode->addDrawable(new SGHUDAndPanelDrawable);
500 guiCamera->addChild(geode);
502 // this one contains all lights, here we set the light states we did
503 // in the plib case with plain OpenGL
504 osg::Group* lightGroup = new osg::Group;
505 sceneGroup->addChild(lightGroup);
506 lightGroup->addChild(globals->get_scenery()->get_gnd_lights_root());
507 lightGroup->addChild(globals->get_scenery()->get_vasi_lights_root());
508 lightGroup->addChild(globals->get_scenery()->get_rwy_lights_root());
509 lightGroup->addChild(globals->get_scenery()->get_taxi_lights_root());
511 stateSet = globals->get_scenery()->get_gnd_lights_root()->getOrCreateStateSet();
512 stateSet->setAttributeAndModes(mFog.get());
513 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
514 stateSet = globals->get_scenery()->get_vasi_lights_root()->getOrCreateStateSet();
515 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
516 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
517 stateSet = globals->get_scenery()->get_rwy_lights_root()->getOrCreateStateSet();
518 stateSet->setAttributeAndModes(mRunwayLightingFog.get());
519 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
520 stateSet = globals->get_scenery()->get_taxi_lights_root()->getOrCreateStateSet();
521 stateSet->setAttributeAndModes(mTaxiLightingFog.get());
522 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
524 mCameraView->addChild(mRoot.get());
525 sceneView->setSceneData(mCameraView.get());
527 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
531 // Update all Visuals (redraws anything graphics related)
533 FGRenderer::update( bool refresh_camera_settings ) {
534 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
535 || fgGetBool("sim/sceneryloaded-override");
537 if ( idle_state < 1000 || !scenery_loaded ) {
538 if (sceneView.valid() && sceneView->getState()) {
539 sceneView->getState()->setActiveTextureUnit(0);
540 sceneView->getState()->setClientActiveTextureUnit(0);
541 sceneView->getState()->disableAllVertexArrays();
543 // still initializing, draw the splash screen
544 glPushAttrib(GL_ALL_ATTRIB_BITS);
545 glPushClientAttrib(~0u);
552 // Keep resetting sim time while the sim is initializing
553 globals->set_sim_time_sec( 0.0 );
557 bool skyblend = fgGetBool("/sim/rendering/skyblend");
558 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
559 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
560 bool distance_attenuation
561 = fgGetBool("/sim/rendering/distance-attenuation");
563 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
564 distance_attenuation );
566 static const SGPropertyNode *groundlevel_nearplane
567 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
569 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
572 double actual_visibility;
573 if (fgGetBool("/environment/clouds/status")) {
574 actual_visibility = thesky->get_visibility();
576 actual_visibility = fgGetDouble("/environment/visibility-m");
579 static double last_visibility = -9999;
580 if ( actual_visibility != last_visibility ) {
581 last_visibility = actual_visibility;
583 fog_exp_density = m_log01 / actual_visibility;
584 fog_exp2_density = sqrt_m_log01 / actual_visibility;
585 ground_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
586 if ( actual_visibility < 8000 ) {
587 rwy_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 2.5);
588 taxi_exp2_punch_through = sqrt_m_log01 / (actual_visibility * 1.5);
590 rwy_exp2_punch_through = sqrt_m_log01 / ( 8000 * 2.5 );
591 taxi_exp2_punch_through = sqrt_m_log01 / ( 8000 * 1.5 );
593 mFog->setDensity(fog_exp2_density);
594 mRunwayLightingFog->setDensity(rwy_exp2_punch_through);
595 mTaxiLightingFog->setDensity(taxi_exp2_punch_through);
596 mGroundLightingFog->setDensity(ground_exp2_punch_through);
599 // idle_state is now 1000 meaning we've finished all our
600 // initializations and are running the main loop, so this will
601 // now work without seg faulting the system.
603 FGViewer *current__view = globals->get_current_view();
604 // Force update of center dependent values ...
605 current__view->set_dirty();
607 if ( refresh_camera_settings ) {
609 resize( fgGetInt("/sim/startup/xsize"),
610 fgGetInt("/sim/startup/ysize") );
612 SGVec3d center = globals->get_scenery()->get_center();
613 SGVec3d position = current__view->getViewPosition();
614 SGQuatd attitude = current__view->getViewOrientation();
615 SGVec3d osgPosition = attitude.transform(center - position);
616 mCameraView->setPosition(osgPosition.osg());
617 mCameraView->setAttitude(inverse(attitude).osg());
621 if ( fgGetBool("/sim/rendering/textures") ) {
622 SGVec4f clearColor(l->adj_fog_color());
623 sceneView->getCamera()->setClearColor(clearColor.osg());
626 SGVec4f clearColor(l->sky_color());
627 sceneView->getCamera()->setClearColor(clearColor.osg());
630 // update fog params if visibility has changed
631 double visibility_meters = fgGetDouble("/environment/visibility-m");
632 thesky->set_visibility(visibility_meters);
634 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
635 ( global_multi_loop * fgGetInt("/sim/speed-up") )
636 / (double)fgGetInt("/sim/model-hz") );
638 // update the sky dome
641 // The sun and moon distances are scaled down versions
642 // of the actual distance to get both the moon and the sun
643 // within the range of the far clip plane.
644 // Moon distance: 384,467 kilometers
645 // Sun distance: 150,000,000 kilometers
647 double sun_horiz_eff, moon_horiz_eff;
648 if (fgGetBool("/sim/rendering/horizon-effect")) {
649 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
650 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
652 sun_horiz_eff = moon_horiz_eff = 1.0;
655 static SGSkyState sstate;
657 sstate.view_pos = current__view->get_view_pos();
658 sstate.zero_elev = current__view->get_zero_elev();
659 sstate.view_up = current__view->get_world_up();
660 sstate.lon = current__view->getLongitude_deg()
661 * SGD_DEGREES_TO_RADIANS;
662 sstate.lat = current__view->getLatitude_deg()
663 * SGD_DEGREES_TO_RADIANS;
664 sstate.alt = current__view->getAltitudeASL_ft()
666 sstate.spin = l->get_sun_rotation();
667 sstate.gst = globals->get_time_params()->getGst();
668 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
669 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
670 sstate.sun_dist = 50000.0 * sun_horiz_eff;
671 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
672 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
673 sstate.moon_dist = 40000.0 * moon_horiz_eff;
674 sstate.sun_angle = l->get_sun_angle();
678 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
679 << l->sky_color()[0] << " "
680 << l->sky_color()[1] << " "
681 << l->sky_color()[2] << " "
682 << l->sky_color()[3] );
683 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
684 << l->fog_color()[0] << " "
685 << l->fog_color()[1] << " "
686 << l->fog_color()[2] << " "
687 << l->fog_color()[3] );
688 SG_LOG( SG_GENERAL, SG_BULK,
689 " sun_angle = " << l->sun_angle
690 << " moon_angle = " << l->moon_angle );
693 static SGSkyColor scolor;
695 scolor.sky_color = SGVec3f(l->sky_color().data());
696 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
697 scolor.cloud_color = SGVec3f(l->cloud_color().data());
698 scolor.sun_angle = l->get_sun_angle();
699 scolor.moon_angle = l->get_moon_angle();
700 scolor.nplanets = globals->get_ephem()->getNumPlanets();
701 scolor.nstars = globals->get_ephem()->getNumStars();
702 scolor.planet_data = globals->get_ephem()->getPlanets();
703 scolor.star_data = globals->get_ephem()->getStars();
705 thesky->reposition( sstate, delta_time_sec );
706 thesky->repaint( scolor );
709 SG_LOG( SG_GENERAL, SG_BULK,
710 "thesky->reposition( view_pos = " << view_pos[0] << " "
711 << view_pos[1] << " " << view_pos[2] );
712 SG_LOG( SG_GENERAL, SG_BULK,
713 " zero_elev = " << zero_elev[0] << " "
714 << zero_elev[1] << " " << zero_elev[2]
715 << " lon = " << cur_fdm_state->get_Longitude()
716 << " lat = " << cur_fdm_state->get_Latitude() );
717 SG_LOG( SG_GENERAL, SG_BULK,
718 " sun_rot = " << l->get_sun_rotation
719 << " gst = " << SGTime::cur_time_params->getGst() );
720 SG_LOG( SG_GENERAL, SG_BULK,
721 " sun ra = " << globals->get_ephem()->getSunRightAscension()
722 << " sun dec = " << globals->get_ephem()->getSunDeclination()
723 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
724 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
728 // shadows->setupShadows(
729 // current__view->getLongitude_deg(),
730 // current__view->getLatitude_deg(),
731 // globals->get_time_params()->getGst(),
732 // globals->get_ephem()->getSunRightAscension(),
733 // globals->get_ephem()->getSunDeclination(),
734 // l->get_sun_angle());
738 if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
739 SGVec4f color(l->adj_fog_color());
740 mFog->setColor(color.osg());
741 mRunwayLightingFog->setColor(color.osg());
742 mTaxiLightingFog->setColor(color.osg());
743 mGroundLightingFog->setColor(color.osg());
747 // sgEnviro.setLight(l->adj_fog_color());
749 // texture parameters
750 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
752 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
753 - current__view->getSGLocation()->get_cur_elev_m();
755 float scene_nearplane, scene_farplane;
757 scene_nearplane = 10.0f;
758 scene_farplane = 120000.0f;
760 scene_nearplane = groundlevel_nearplane->getDoubleValue();
761 scene_farplane = 120000.0f;
763 setNearFar( scene_nearplane, scene_farplane );
765 // sgEnviro.startOfFrame(current__view->get_view_pos(),
766 // current__view->get_world_up(),
767 // current__view->getLongitude_deg(),
768 // current__view->getLatitude_deg(),
769 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
773 // sgEnviro.drawLightning();
775 // double current_view_origin_airspeed_horiz_kt =
776 // fgGetDouble("/velocities/airspeed-kt", 0.0)
777 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
778 // * SGD_DEGREES_TO_RADIANS);
779 // TODO:find the real view speed, not the AC one
780 // sgEnviro.drawPrecipitation(
781 // fgGetDouble("/environment/metar/rain-norm", 0.0),
782 // fgGetDouble("/environment/metar/snow-norm", 0.0),
783 // fgGetDouble("/environment/metar/hail-norm", 0.0),
784 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
785 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
786 // - current__view->getHeadingOffset_deg(),
787 // current_view_origin_airspeed_horiz_kt
792 // shadows->endOfFrame();
794 // need to call the update visitor once
795 globals->get_aircraft_model()->select( true );
796 FGTileMgr::set_tile_filter( true );
797 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
798 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
799 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
800 mUpdateVisitor->setViewData(current__view->getViewPosition(),
801 current__view->getViewOrientation());
802 mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
803 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
804 mUpdateVisitor->setLight(direction, l->scene_ambient(),
805 l->scene_diffuse(), l->scene_specular());
806 mUpdateVisitor->setVisibility(actual_visibility);
808 if (fgGetBool("/sim/panel-hotspots"))
809 sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
811 sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
820 // options.cxx needs to see this for toggle_panel()
821 // Handle new window size or exposure
823 FGRenderer::resize( int width, int height ) {
826 if ( (!fgGetBool("/sim/virtual-cockpit"))
827 && fgPanelVisible() && idle_state == 1000 ) {
828 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
829 globals->get_current_panel()->getYOffset()) / 768.0);
834 sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
836 static int lastwidth = 0;
837 static int lastheight = 0;
838 if (width != lastwidth)
839 fgSetInt("/sim/startup/xsize", lastwidth = width);
840 if (height != lastheight)
841 fgSetInt("/sim/startup/ysize", lastheight = height);
843 guiInitMouse(width, height);
846 FGViewMgr *viewmgr = globals->get_viewmgr();
848 for ( int i = 0; i < viewmgr->size(); ++i ) {
849 viewmgr->get_view(i)->
850 set_aspect_ratio((float)view_h / (float)width);
853 setFOV( viewmgr->get_current_view()->get_h_fov(),
854 viewmgr->get_current_view()->get_v_fov() );
859 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
860 // which will post process and rewrite the resulting frustum if we
861 // want to do asymmetric view frustums.
863 static void fgHackFrustum() {
865 // specify a percent of the configured view frustum to actually
866 // display. This is a bit of a hack to achieve asymmetric view
867 // frustums. For instance, if you want to display two monitors
868 // side by side, you could specify each with a double fov, a 0.5
869 // aspect ratio multiplier, and then the left side monitor would
870 // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
871 // and a top_pct = 1.0. The right side monitor would have a
872 // left_pct = 0.5 and a right_pct = 1.0.
874 static SGPropertyNode *left_pct
875 = fgGetNode("/sim/current-view/frustum-left-pct");
876 static SGPropertyNode *right_pct
877 = fgGetNode("/sim/current-view/frustum-right-pct");
878 static SGPropertyNode *bottom_pct
879 = fgGetNode("/sim/current-view/frustum-bottom-pct");
880 static SGPropertyNode *top_pct
881 = fgGetNode("/sim/current-view/frustum-top-pct");
886 sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
887 // cout << " l = " << f->getLeft()
888 // << " r = " << f->getRight()
889 // << " b = " << f->getBot()
890 // << " t = " << f->getTop()
891 // << " n = " << f->getNear()
892 // << " f = " << f->getFar()
895 double width = right - left;
896 double height = top - bottom;
900 if ( left_pct != NULL ) {
901 l = left + width * left_pct->getDoubleValue();
906 if ( right_pct != NULL ) {
907 r = left + width * right_pct->getDoubleValue();
912 if ( bottom_pct != NULL ) {
913 b = bottom + height * bottom_pct->getDoubleValue();
918 if ( top_pct != NULL ) {
919 t = bottom + height * top_pct->getDoubleValue();
924 sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
928 // we need some static storage space for these values. However, we
929 // can't store it in a renderer class object because the functions
930 // that manipulate these are static. They are static so they can
931 // interface to the display callback system. There's probably a
932 // better way, there has to be a better way, but I'm not seeing it
934 static float fov_width = 55.0;
935 static float fov_height = 42.0;
936 static float fov_near = 1.0;
937 static float fov_far = 1000.0;
940 /** FlightGear code should use this routine to set the FOV rather than
941 * calling the ssg routine directly
943 void FGRenderer::setFOV( float w, float h ) {
947 sceneView->setProjectionMatrixAsPerspective(fov_height,
948 fov_width/fov_height,
950 // fully specify the view frustum before hacking it (so we don't
951 // accumulate hacked effects
953 // sgEnviro.setFOV( w, h );
957 /** FlightGear code should use this routine to set the Near/Far clip
958 * planes rather than calling the ssg routine directly
960 void FGRenderer::setNearFar( float n, float f ) {
961 // OSGFIXME: we have currently too much z-buffer fights
966 sceneView->setProjectionMatrixAsPerspective(fov_height,
967 fov_width/fov_height,
970 // fully specify the view frustum before hacking it (so we don't
971 // accumulate hacked effects
976 FGRenderer::pick( unsigned x, unsigned y,
977 std::vector<SGSceneryPick>& pickList )
979 // wipe out the return ...
982 // we can get called early ...
983 if (!sceneView.valid())
986 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
989 osg::Viewport* viewport = sceneView->getViewport();
993 // good old scenery center
994 SGVec3d center = globals->get_scenery()->get_center();
996 // don't know why, but the update has partly happened somehow,
997 // so update the scenery part of the viewer
998 FGViewer *current_view = globals->get_current_view();
999 // Force update of center dependent values ...
1000 current_view->set_dirty();
1001 SGVec3d position = current_view->getViewPosition();
1002 SGQuatd attitude = current_view->getViewOrientation();
1003 SGVec3d osgPosition = attitude.transform(center - position);
1004 mCameraView->setPosition(osgPosition.osg());
1005 mCameraView->setAttitude(inverse(attitude).osg());
1007 osg::Matrix projection(sceneView->getProjectionMatrix());
1008 osg::Matrix modelview(sceneView->getViewMatrix());
1010 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1011 // modify the view matrix so that it accounts for this nodePath's
1012 // accumulated transform
1013 if (!nodePath.empty())
1014 modelview.preMult(computeLocalToWorld(nodePath.front()));
1016 // swap the y values ...
1017 y = viewport->height() - y;
1018 // set up the pick visitor
1019 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1020 sceneData->accept(pickVisitor);
1021 if (!pickVisitor.hits())
1024 // collect all interaction callbacks on the pick ray.
1025 // They get stored in the pickCallbacks list where they are sorted back
1026 // to front and croasest to finest wrt the scenery node they are attached to
1027 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1028 for (mi = pickVisitor.getSegHitList().begin();
1029 mi != pickVisitor.getSegHitList().end();
1031 osgUtil::IntersectVisitor::HitList::const_iterator hi;
1032 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1033 // ok, go back the nodes and ask for intersection callbacks,
1034 // execute them in top down order
1035 const osg::NodePath& np = hi->getNodePath();
1036 osg::NodePath::const_reverse_iterator npi;
1037 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1038 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1041 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1042 SGPickCallback* pickCallback = ud->getPickCallback(i);
1045 SGSceneryPick sceneryPick;
1046 /// note that this is done totally in doubles instead of
1047 /// just using getWorldIntersectionPoint
1048 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1049 sceneryPick.info.local = SGVec3d(localPt);
1050 if (hi->getMatrix())
1051 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1053 sceneryPick.info.wgs84 = SGVec3d(localPt);
1054 sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1055 sceneryPick.callback = pickCallback;
1056 pickList.push_back(sceneryPick);
1062 return !pickList.empty();
1065 // end of renderer.cxx