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>
52 #include <osg/Version>
55 #include <osgUtil/SceneView>
56 #include <osgUtil/UpdateVisitor>
57 #include <osgUtil/IntersectVisitor>
58 #include <osgUtil/LineSegmentIntersector>
60 #include <osg/io_utils>
61 #include <osgDB/WriteFile>
62 #include <osgDB/ReadFile>
65 #include <simgear/math/SGMath.hxx>
66 #include <simgear/screen/extensions.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/model.hxx>
70 #include <simgear/scene/model/modellib.hxx>
71 #include <simgear/scene/model/placement.hxx>
72 #include <simgear/scene/util/SGUpdateVisitor.hxx>
73 #include <simgear/scene/tgdb/pt_lights.hxx>
74 #include <simgear/props/props.hxx>
75 #include <simgear/timing/sg_time.hxx>
76 #include <simgear/ephemeris/ephemeris.hxx>
77 #include <simgear/math/sg_random.h>
79 #include <simgear/screen/jpgfactory.hxx>
82 #include <simgear/environment/visual_enviro.hxx>
84 #include <Scenery/tileentry.hxx>
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Aircraft/aircraft.hxx>
88 #include <Cockpit/panel.hxx>
89 #include <Cockpit/cockpit.hxx>
90 #include <Cockpit/hud.hxx>
91 #include <Model/panelnode.hxx>
92 #include <Model/modelmgr.hxx>
93 #include <Model/acmodel.hxx>
94 #include <Scenery/scenery.hxx>
95 #include <Scenery/redout.hxx>
96 #include <Scenery/tilemgr.hxx>
97 #include <GUI/new_gui.hxx>
98 #include <Instrumentation/instrument_mgr.hxx>
99 #include <Instrumentation/HUD/HUD.hxx>
101 #include <Include/general.hxx>
102 #include "splash.hxx"
103 #include "renderer.hxx"
106 // XXX Make this go away when OSG 2.2 is released.
107 #if (FG_OSG_VERSION >= 21004)
108 #define UPDATE_VISITOR_IN_VIEWER 1
111 class SGPuDrawable : public osg::Drawable {
115 // Dynamic stuff, do not store geometry
116 setUseDisplayList(false);
118 osg::StateSet* stateSet = getOrCreateStateSet();
119 stateSet->setRenderBinDetails(1001, "RenderBin");
120 // speed optimization?
121 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
122 // We can do translucent menus, so why not. :-)
123 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
124 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
125 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
127 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
129 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
130 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
132 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
133 { drawImplementation(*renderInfo.getState()); }
134 void drawImplementation(osg::State& state) const
136 if (!fgOSIsMainContext(state.getGraphicsContext()))
139 state.pushStateSet(getStateSet());
141 state.setActiveTextureUnit(0);
142 state.setClientActiveTextureUnit(0);
143 state.disableAllVertexArrays();
145 glPushAttrib(GL_ALL_ATTRIB_BITS);
146 glPushClientAttrib(~0u);
154 state.dirtyAllModes();
155 state.dirtyAllAttributes();
156 state.dirtyAllVertexArrays();
159 virtual osg::Object* cloneType() const { return new SGPuDrawable; }
160 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
165 class SGHUDAndPanelDrawable : public osg::Drawable {
167 SGHUDAndPanelDrawable()
169 // Dynamic stuff, do not store geometry
170 setUseDisplayList(false);
172 osg::StateSet* stateSet = getOrCreateStateSet();
173 stateSet->setRenderBinDetails(1000, "RenderBin");
175 // speed optimization?
176 stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
177 stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
178 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
179 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
180 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
182 stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
184 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
185 { drawImplementation(*renderInfo.getState()); }
186 void drawImplementation(osg::State& state) const
188 // std::cout << state.getGraphicsContext() << std::endl;
189 if (!fgOSIsMainContext(state.getGraphicsContext()))
192 state.pushStateSet(getStateSet());
194 state.setActiveTextureUnit(0);
195 state.setClientActiveTextureUnit(0);
196 state.disableAllVertexArrays();
198 glPushAttrib(GL_ALL_ATTRIB_BITS);
199 glPushClientAttrib(~0u);
201 fgCockpitUpdate(&state);
203 FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
204 HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
207 // update the panel subsystem
208 if ( globals->get_current_panel() != NULL )
209 globals->get_current_panel()->update(state);
210 // We don't need a state here - can be safely removed when we can pick
218 state.dirtyAllModes();
219 state.dirtyAllAttributes();
220 state.dirtyAllVertexArrays();
223 virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
224 virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
229 class FGLightSourceUpdateCallback : public osg::NodeCallback {
231 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
233 assert(dynamic_cast<osg::LightSource*>(node));
234 osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
235 osg::Light* light = lightSource->getLight();
237 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
238 light->setAmbient(l->scene_ambient().osg());
239 light->setDiffuse(l->scene_diffuse().osg());
240 light->setSpecular(l->scene_specular().osg());
241 SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
242 light->setPosition(position.osg());
243 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
244 light->setDirection(direction.osg());
245 light->setSpotExponent(0);
246 light->setSpotCutoff(180);
247 light->setConstantAttenuation(1);
248 light->setLinearAttenuation(0);
249 light->setQuadraticAttenuation(0);
255 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
257 FGWireFrameModeUpdateCallback() :
258 mWireframe(fgGetNode("/sim/rendering/wireframe"))
260 virtual void operator()(osg::StateAttribute* stateAttribute,
263 assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
264 osg::PolygonMode* polygonMode;
265 polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
267 if (mWireframe->getBoolValue())
268 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
269 osg::PolygonMode::LINE);
271 polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
272 osg::PolygonMode::FILL);
275 SGSharedPtr<SGPropertyNode> mWireframe;
278 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
280 FGLightModelUpdateCallback() :
281 mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
283 virtual void operator()(osg::StateAttribute* stateAttribute,
286 assert(dynamic_cast<osg::LightModel*>(stateAttribute));
287 osg::LightModel* lightModel;
288 lightModel = static_cast<osg::LightModel*>(stateAttribute);
291 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
292 lightModel->setAmbientIntensity(l->scene_ambient().osg());
294 lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
296 lightModel->setTwoSided(true);
297 lightModel->setLocalViewer(false);
299 if (mHighlights->getBoolValue()) {
300 lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
302 lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
306 SGSharedPtr<SGPropertyNode> mHighlights;
309 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
311 FGFogEnableUpdateCallback() :
312 mFogEnabled(fgGetNode("/sim/rendering/fog"))
314 virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
316 if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
317 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
319 stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
323 SGSharedPtr<SGPropertyNode> mFogEnabled;
326 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
328 virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
330 assert(dynamic_cast<SGUpdateVisitor*>(nv));
331 assert(dynamic_cast<osg::Fog*>(sa));
332 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
333 osg::Fog* fog = static_cast<osg::Fog*>(sa);
334 fog->setMode(osg::Fog::EXP2);
335 fog->setColor(updateVisitor->getFogColor().osg());
336 fog->setDensity(updateVisitor->getFogExp2Density());
340 // update callback for the switch node guarding that splash
341 class FGScenerySwitchCallback : public osg::NodeCallback {
343 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
345 assert(dynamic_cast<osg::Switch*>(node));
346 osg::Switch* sw = static_cast<osg::Switch*>(node);
348 double t = globals->get_sim_time_sec();
349 bool enabled = 0 < t;
350 sw->setValue(0, enabled);
360 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView; // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
361 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
362 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
364 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
366 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
368 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
369 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
371 FGRenderer::FGRenderer()
373 #ifdef FG_JPEG_SERVER
374 jpgRenderFrame = FGRenderer::update;
376 manipulator = new FGManipulator;
379 FGRenderer::~FGRenderer()
381 #ifdef FG_JPEG_SERVER
382 jpgRenderFrame = NULL;
386 // Initialize various GL/view parameters
387 // XXX This should be called "preinit" or something, as it initializes
388 // critical parts of the scene graph in addition to the splash screen.
390 FGRenderer::splashinit( void ) {
391 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
394 mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
395 mRealRoot->addChild(fgCreateSplashNode());
396 mFrameStamp = viewer->getFrameStamp();
397 // Scene doesn't seem to pass the frame stamp to the update
398 // visitor automatically.
399 mUpdateVisitor->setFrameStamp(mFrameStamp.get());
400 #ifdef UPDATE_VISITOR_IN_VIEWER
401 viewer->setUpdateVisitor(mUpdateVisitor.get());
403 osgViewer::Scene* scene = viewer->getScene();
404 scene->setUpdateVisitor(mUpdateVisitor.get());
407 // Add the splash screen node
408 mRealRoot->addChild(fgCreateSplashNode());
409 sceneView->setSceneData(mRealRoot.get());
410 sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
411 sceneView->setFrameStamp(mFrameStamp.get());
412 sceneView->setUpdateVisitor(mUpdateVisitor.get());
417 FGRenderer::init( void ) {
418 // The viewer can call this before the graphics context is current
419 // in the main thread; indeed, in a multithreaded setup it might
420 // never be current in the main thread.
422 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
423 osg::initNotifyLevel();
425 // The number of polygon-offset "units" to place between layers. In
426 // principle, one is supposed to be enough. In practice, I find that
427 // my hardware/driver requires many more.
428 osg::PolygonOffset::setUnitsMultiplier(1);
429 osg::PolygonOffset::setFactorMultiplier(1);
431 // Go full screen if requested ...
432 if ( fgGetBool("/sim/startup/fullscreen") )
435 if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) ||
436 (!fgGetBool("/sim/rendering/shading"))) {
437 // if fastest fog requested, or if flat shading force fastest
438 glHint ( GL_FOG_HINT, GL_FASTEST );
439 } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
440 glHint ( GL_FOG_HINT, GL_DONT_CARE );
443 glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
444 glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
445 glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
449 ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
451 sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
452 sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
456 osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
458 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
460 stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
461 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
463 stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
464 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
465 stateSet->setAttribute(new osg::BlendFunc);
466 stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
468 stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
470 // this will be set below
471 stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
473 osg::Material* material = new osg::Material;
474 stateSet->setAttribute(material);
476 stateSet->setTextureAttribute(0, new osg::TexEnv);
477 stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
480 // stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
481 // stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
483 // this is the topmost scenegraph node for osg
484 mBackGroundCamera->addChild(thesky->getPreRoot());
485 mBackGroundCamera->setClearMask(0);
487 GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
488 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
489 inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
490 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
491 mBackGroundCamera->setInheritanceMask(inheritanceMask);
492 mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
493 mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
494 mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
496 stateSet = mBackGroundCamera->getOrCreateStateSet();
497 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
499 osg::Group* sceneGroup = new osg::Group;
500 sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
501 sceneGroup->addChild(thesky->getCloudRoot());
503 stateSet = sceneGroup->getOrCreateStateSet();
504 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
505 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
507 // need to update the light on every frame
508 osg::LightSource* lightSource = new osg::LightSource;
509 lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
510 // relative because of CameraView being just a clever transform node
511 lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
512 lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
513 mRoot->addChild(lightSource);
515 lightSource->addChild(mBackGroundCamera.get());
516 lightSource->addChild(sceneGroup);
519 stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
520 stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
521 stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
522 stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
523 stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
525 // enable disable specular highlights.
526 // is the place where we might plug in an other fragment shader ...
527 osg::LightModel* lightModel = new osg::LightModel;
528 lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
529 stateSet->setAttribute(lightModel);
531 // switch to enable wireframe
532 osg::PolygonMode* polygonMode = new osg::PolygonMode;
533 polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
534 stateSet->setAttributeAndModes(polygonMode);
536 // scene fog handling
537 osg::Fog* fog = new osg::Fog;
538 fog->setUpdateCallback(new FGFogUpdateCallback);
539 stateSet->setAttributeAndModes(fog);
540 stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
543 osg::Camera* guiCamera = new osg::Camera;
544 guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
545 guiCamera->setClearMask(0);
546 inheritanceMask = osg::CullSettings::ALL_VARIABLES;
547 inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
548 inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
549 guiCamera->setInheritanceMask(inheritanceMask);
550 guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
551 guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
552 osg::Geode* geode = new osg::Geode;
553 geode->addDrawable(new SGPuDrawable);
554 geode->addDrawable(new SGHUDAndPanelDrawable);
555 guiCamera->addChild(geode);
557 mCameraView->addChild(mRoot.get());
559 osg::Switch* sw = new osg::Switch;
560 sw->setUpdateCallback(new FGScenerySwitchCallback);
561 sw->addChild(mCameraView.get());
563 mRealRoot->addChild(sw);
564 mRealRoot->addChild(FGCreateRedoutNode());
565 mRealRoot->addChild(guiCamera);
566 // sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
570 // Update all Visuals (redraws anything graphics related)
572 FGRenderer::update( bool refresh_camera_settings ) {
573 bool scenery_loaded = fgGetBool("sim/sceneryloaded")
574 || fgGetBool("sim/sceneryloaded-override");
575 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
576 if ( idle_state < 1000 || !scenery_loaded ) {
577 fgSetDouble("/sim/startup/splash-alpha", 1.0);
579 // Keep resetting sim time while the sim is initializing
580 globals->set_sim_time_sec( 0.0 );
582 // the splash screen is now in the scenegraph
591 // Fade out the splash screen over the first three seconds.
592 double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
593 fgSetDouble("/sim/startup/splash-alpha", sAlpha);
595 bool skyblend = fgGetBool("/sim/rendering/skyblend");
596 bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
597 bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
598 bool distance_attenuation
599 = fgGetBool("/sim/rendering/distance-attenuation");
601 SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
602 distance_attenuation );
604 static const SGPropertyNode *groundlevel_nearplane
605 = fgGetNode("/sim/current-view/ground-level-nearplane-m");
607 FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
610 double actual_visibility;
611 if (fgGetBool("/environment/clouds/status")) {
612 actual_visibility = thesky->get_visibility();
614 actual_visibility = fgGetDouble("/environment/visibility-m");
617 // idle_state is now 1000 meaning we've finished all our
618 // initializations and are running the main loop, so this will
619 // now work without seg faulting the system.
621 FGViewer *current__view = globals->get_current_view();
622 // Force update of center dependent values ...
623 current__view->set_dirty();
625 if ( refresh_camera_settings ) {
627 resize( fgGetInt("/sim/startup/xsize"),
628 fgGetInt("/sim/startup/ysize") );
630 SGVec3d position = current__view->getViewPosition();
631 SGQuatd attitude = current__view->getViewOrientation();
632 SGVec3d osgPosition = attitude.transform(-position);
634 FGManipulator *manipulator
635 = globals->get_renderer()->getManipulator();
636 manipulator->setPosition(position.osg());
637 manipulator->setAttitude(attitude.osg());
639 mCameraView->setPosition(osgPosition.osg());
640 mCameraView->setAttitude(inverse(attitude).osg());
645 camera = viewer->getCamera();
647 camera = sceneView->getCamera();
650 if ( fgGetBool("/sim/rendering/textures") ) {
651 SGVec4f clearColor(l->adj_fog_color());
652 camera->setClearColor(clearColor.osg());
655 SGVec4f clearColor(l->sky_color());
656 camera->setClearColor(clearColor.osg());
659 // update fog params if visibility has changed
660 double visibility_meters = fgGetDouble("/environment/visibility-m");
661 thesky->set_visibility(visibility_meters);
663 thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
664 ( global_multi_loop * fgGetInt("/sim/speed-up") )
665 / (double)fgGetInt("/sim/model-hz") );
667 // update the sky dome
670 // The sun and moon distances are scaled down versions
671 // of the actual distance to get both the moon and the sun
672 // within the range of the far clip plane.
673 // Moon distance: 384,467 kilometers
674 // Sun distance: 150,000,000 kilometers
676 double sun_horiz_eff, moon_horiz_eff;
677 if (fgGetBool("/sim/rendering/horizon-effect")) {
678 sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
679 moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
681 sun_horiz_eff = moon_horiz_eff = 1.0;
684 static SGSkyState sstate;
686 sstate.view_pos = toVec3f(current__view->get_view_pos());
687 sstate.zero_elev = toVec3f(current__view->get_zero_elev());
688 sstate.view_up = current__view->get_world_up();
689 sstate.lon = current__view->getLongitude_deg()
690 * SGD_DEGREES_TO_RADIANS;
691 sstate.lat = current__view->getLatitude_deg()
692 * SGD_DEGREES_TO_RADIANS;
693 sstate.alt = current__view->getAltitudeASL_ft()
695 sstate.spin = l->get_sun_rotation();
696 sstate.gst = globals->get_time_params()->getGst();
697 sstate.sun_ra = globals->get_ephem()->getSunRightAscension();
698 sstate.sun_dec = globals->get_ephem()->getSunDeclination();
699 sstate.sun_dist = 50000.0 * sun_horiz_eff;
700 sstate.moon_ra = globals->get_ephem()->getMoonRightAscension();
701 sstate.moon_dec = globals->get_ephem()->getMoonDeclination();
702 sstate.moon_dist = 40000.0 * moon_horiz_eff;
703 sstate.sun_angle = l->get_sun_angle();
707 SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
708 << l->sky_color()[0] << " "
709 << l->sky_color()[1] << " "
710 << l->sky_color()[2] << " "
711 << l->sky_color()[3] );
712 SG_LOG( SG_GENERAL, SG_BULK, " fog = "
713 << l->fog_color()[0] << " "
714 << l->fog_color()[1] << " "
715 << l->fog_color()[2] << " "
716 << l->fog_color()[3] );
717 SG_LOG( SG_GENERAL, SG_BULK,
718 " sun_angle = " << l->sun_angle
719 << " moon_angle = " << l->moon_angle );
722 static SGSkyColor scolor;
724 scolor.sky_color = SGVec3f(l->sky_color().data());
725 scolor.fog_color = SGVec3f(l->adj_fog_color().data());
726 scolor.cloud_color = SGVec3f(l->cloud_color().data());
727 scolor.sun_angle = l->get_sun_angle();
728 scolor.moon_angle = l->get_moon_angle();
729 scolor.nplanets = globals->get_ephem()->getNumPlanets();
730 scolor.nstars = globals->get_ephem()->getNumStars();
731 scolor.planet_data = globals->get_ephem()->getPlanets();
732 scolor.star_data = globals->get_ephem()->getStars();
734 thesky->reposition( sstate, delta_time_sec );
735 thesky->repaint( scolor );
738 SG_LOG( SG_GENERAL, SG_BULK,
739 "thesky->reposition( view_pos = " << view_pos[0] << " "
740 << view_pos[1] << " " << view_pos[2] );
741 SG_LOG( SG_GENERAL, SG_BULK,
742 " zero_elev = " << zero_elev[0] << " "
743 << zero_elev[1] << " " << zero_elev[2]
744 << " lon = " << cur_fdm_state->get_Longitude()
745 << " lat = " << cur_fdm_state->get_Latitude() );
746 SG_LOG( SG_GENERAL, SG_BULK,
747 " sun_rot = " << l->get_sun_rotation
748 << " gst = " << SGTime::cur_time_params->getGst() );
749 SG_LOG( SG_GENERAL, SG_BULK,
750 " sun ra = " << globals->get_ephem()->getSunRightAscension()
751 << " sun dec = " << globals->get_ephem()->getSunDeclination()
752 << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
753 << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
757 // shadows->setupShadows(
758 // current__view->getLongitude_deg(),
759 // current__view->getLatitude_deg(),
760 // globals->get_time_params()->getGst(),
761 // globals->get_ephem()->getSunRightAscension(),
762 // globals->get_ephem()->getSunDeclination(),
763 // l->get_sun_angle());
767 // sgEnviro.setLight(l->adj_fog_color());
769 // texture parameters
770 glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
772 double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
773 - current__view->getSGLocation()->get_cur_elev_m();
775 float scene_nearplane, scene_farplane;
777 scene_nearplane = 10.0f;
778 scene_farplane = 120000.0f;
780 scene_nearplane = groundlevel_nearplane->getDoubleValue();
781 scene_farplane = 120000.0f;
783 setNearFar( scene_nearplane, scene_farplane );
785 // sgEnviro.startOfFrame(current__view->get_view_pos(),
786 // current__view->get_world_up(),
787 // current__view->getLongitude_deg(),
788 // current__view->getLatitude_deg(),
789 // current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
793 // sgEnviro.drawLightning();
795 // double current_view_origin_airspeed_horiz_kt =
796 // fgGetDouble("/velocities/airspeed-kt", 0.0)
797 // * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
798 // * SGD_DEGREES_TO_RADIANS);
799 // TODO:find the real view speed, not the AC one
800 // sgEnviro.drawPrecipitation(
801 // fgGetDouble("/environment/metar/rain-norm", 0.0),
802 // fgGetDouble("/environment/metar/snow-norm", 0.0),
803 // fgGetDouble("/environment/metar/hail-norm", 0.0),
804 // current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
805 // current__view->getRoll_deg() + current__view->getRollOffset_deg(),
806 // - current__view->getHeadingOffset_deg(),
807 // current_view_origin_airspeed_horiz_kt
812 // shadows->endOfFrame();
814 // need to call the update visitor once
816 mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
817 mFrameStamp->setSimulationTime(globals->get_sim_time_sec());
818 mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
820 mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
821 mUpdateVisitor->setViewData(current__view->getViewPosition(),
822 current__view->getViewOrientation());
823 SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
824 mUpdateVisitor->setLight(direction, l->scene_ambient(),
825 l->scene_diffuse(), l->scene_specular(),
827 l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
828 mUpdateVisitor->setVisibility(actual_visibility);
829 bool hotspots = fgGetBool("/sim/panel-hotspots");
832 camera->setCullMask(camera->getCullMask()|SG_NODEMASK_PICK_BIT);
834 camera->setCullMask(camera->getCullMask()
835 & ~SG_NODEMASK_PICK_BIT);
838 sceneView->setCullMask(sceneView->getCullMask()
839 |SG_NODEMASK_PICK_BIT);
841 sceneView->setCullMask(sceneView->getCullMask()
842 &(~SG_NODEMASK_PICK_BIT));
851 // options.cxx needs to see this for toggle_panel()
852 // Handle new window size or exposure
854 FGRenderer::resize( int width, int height ) {
857 if ( (!fgGetBool("/sim/virtual-cockpit"))
858 && fgPanelVisible() && idle_state == 1000 ) {
859 view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
860 globals->get_current_panel()->getYOffset()) / 768.0);
864 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
867 // viewer->getCamera()->getViewport()->setViewport(0, height - view_h,
870 sceneView->getViewport()->setViewport(0, height - view_h,
873 static int lastwidth = 0;
874 static int lastheight = 0;
875 if (width != lastwidth)
876 fgSetInt("/sim/startup/xsize", lastwidth = width);
877 if (height != lastheight)
878 fgSetInt("/sim/startup/ysize", lastheight = height);
880 guiInitMouse(width, height);
883 FGViewMgr *viewmgr = globals->get_viewmgr();
885 for ( int i = 0; i < viewmgr->size(); ++i ) {
886 viewmgr->get_view(i)->
887 set_aspect_ratio((float)view_h / (float)width);
890 setFOV( viewmgr->get_current_view()->get_h_fov(),
891 viewmgr->get_current_view()->get_v_fov() );
896 // we need some static storage space for these values. However, we
897 // can't store it in a renderer class object because the functions
898 // that manipulate these are static. They are static so they can
899 // interface to the display callback system. There's probably a
900 // better way, there has to be a better way, but I'm not seeing it
902 static float fov_width = 55.0;
903 static float fov_height = 42.0;
904 static float fov_near = 1.0;
905 static float fov_far = 1000.0;
908 /** FlightGear code should use this routine to set the FOV rather than
909 * calling the ssg routine directly
911 void FGRenderer::setFOV( float w, float h ) {
914 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
916 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0, fov_near, fov_far);
918 sceneView->setProjectionMatrixAsPerspective(fov_height,
919 fov_width/fov_height,
924 /** FlightGear code should use this routine to set the Near/Far clip
925 * planes rather than calling the ssg routine directly
927 void FGRenderer::setNearFar( float n, float f ) {
928 // OSGFIXME: we have currently too much z-buffer fights
932 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
934 viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height, 4.0/3.0, fov_near, fov_far);
936 sceneView->setProjectionMatrixAsPerspective(fov_height,
937 fov_width/fov_height,
943 FGRenderer::pick( unsigned x, unsigned y,
944 std::vector<SGSceneryPick>& pickList,
945 const osgGA::GUIEventAdapter* ea )
947 osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
948 // wipe out the return ...
951 if (sceneView.valid()) {
952 osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
956 osg::Viewport* viewport = sceneView->getViewport();
959 // don't know why, but the update has partly happened somehow,
960 // so update the scenery part of the viewer
961 FGViewer *current_view = globals->get_current_view();
962 // Force update of center dependent values ...
963 current_view->set_dirty();
964 SGVec3d position = current_view->getViewPosition();
965 SGQuatd attitude = current_view->getViewOrientation();
966 SGVec3d osgPosition = attitude.transform(-position);
967 mCameraView->setPosition(osgPosition.osg());
968 mCameraView->setAttitude(inverse(attitude).osg());
970 osg::Matrix projection(sceneView->getProjectionMatrix());
971 osg::Matrix modelview(sceneView->getViewMatrix());
973 osg::NodePathList nodePath = sceneData->getParentalNodePaths();
974 // modify the view matrix so that it accounts for this nodePath's
975 // accumulated transform
976 if (!nodePath.empty())
977 modelview.preMult(computeLocalToWorld(nodePath.front()));
979 // swap the y values ...
980 y = viewport->height() - y;
981 // set up the pick visitor
982 osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
983 sceneData->accept(pickVisitor);
984 if (!pickVisitor.hits())
987 // collect all interaction callbacks on the pick ray.
988 // They get stored in the pickCallbacks list where they are sorted back
989 // to front and croasest to finest wrt the scenery node they are attached to
990 osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
991 for (mi = pickVisitor.getSegHitList().begin();
992 mi != pickVisitor.getSegHitList().end();
994 osgUtil::IntersectVisitor::HitList::const_iterator hi;
995 for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
996 // ok, go back the nodes and ask for intersection callbacks,
997 // execute them in top down order
998 const osg::NodePath& np = hi->getNodePath();
999 osg::NodePath::const_reverse_iterator npi;
1000 for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1001 SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1004 for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1005 SGPickCallback* pickCallback = ud->getPickCallback(i);
1008 SGSceneryPick sceneryPick;
1009 /// note that this is done totally in doubles instead of
1010 /// just using getWorldIntersectionPoint
1011 osg::Vec3d localPt = hi->getLocalIntersectPoint();
1012 sceneryPick.info.local = SGVec3d(localPt);
1013 if (hi->getMatrix())
1014 sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1016 sceneryPick.info.wgs84 = SGVec3d(localPt);
1017 sceneryPick.callback = pickCallback;
1018 pickList.push_back(sceneryPick);
1024 return !pickList.empty();
1026 } else if (viewer) {
1028 // just compute intersections in the viewers method ...
1029 typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
1030 Intersections intersections;
1031 viewer->computeIntersections(ea->getX(), ea->getY(), intersections);
1033 Intersections::iterator hit;
1034 for (hit = intersections.begin(); hit != intersections.end(); ++hit) {
1035 const osg::NodePath& np = hit->nodePath;
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 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
1047 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
1048 sceneryPick.callback = pickCallback;
1049 pickList.push_back(sceneryPick);
1054 return !pickList.empty();
1055 } else { // we can get called early ...
1061 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
1063 mRealRoot->addChild(camera);
1067 fgDumpSceneGraphToFile(const char* filename)
1069 return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1073 fgDumpTerrainBranchToFile(const char* filename)
1075 return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
1079 // end of renderer.cxx