]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Modified Files:
[flightgear.git] / src / Main / renderer.cxx
1 // renderer.cxx -- top level sim routines
2 //
3 // Written by Curtis Olson, started May 1997.
4 // This file contains parts of main.cxx prior to october 2004
5 //
6 // Copyright (C) 1997 - 2002  Curtis L. Olson  - http://www.flightgear.org/~curt
7 //
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.
12 //
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.
17 //
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.
21 //
22 // $Id$
23
24
25 #ifdef HAVE_CONFIG_H
26 #  include <config.h>
27 #endif
28
29 #include <simgear/compiler.h>
30
31 #ifdef HAVE_WINDOWS_H
32 #  include <windows.h>
33 #endif
34
35 #include <osg/ref_ptr>
36 #include <osg/AlphaFunc>
37 #include <osg/BlendFunc>
38 #include <osg/Camera>
39 #include <osg/CameraView>
40 #include <osg/CullFace>
41 #include <osg/Depth>
42 #include <osg/Fog>
43 #include <osg/Group>
44 #include <osg/Light>
45 #include <osg/LightModel>
46 #include <osg/LightSource>
47 #include <osg/NodeCallback>
48 #include <osg/Notify>
49 #include <osg/PolygonMode>
50 #include <osg/PolygonOffset>
51 #include <osg/ShadeModel>
52 #include <osg/TexEnv>
53
54 #include <osgUtil/SceneView>
55 #include <osgUtil/UpdateVisitor>
56 #include <osgUtil/IntersectVisitor>
57
58 #include <osg/io_utils>
59 #include <osgDB/WriteFile>
60 #include <osgDB/ReadFile>
61 #include <sstream>
62
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>
76 #ifdef FG_JPEG_SERVER
77 #include <simgear/screen/jpgfactory.hxx>
78 #endif
79
80 #include <simgear/environment/visual_enviro.hxx>
81
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/redout.hxx>
94 #include <Scenery/tilemgr.hxx>
95 #include <GUI/new_gui.hxx>
96 #include <Instrumentation/instrument_mgr.hxx>
97 #include <Instrumentation/HUD/HUD.hxx>
98
99 #include "splash.hxx"
100 #include "renderer.hxx"
101 #include "main.hxx"
102
103 class SGPuDrawable : public osg::Drawable {
104 public:
105   SGPuDrawable()
106   {
107     // Dynamic stuff, do not store geometry
108     setUseDisplayList(false);
109
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);
118
119     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
120
121     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
122     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
123   }
124   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
125   { drawImplementation(*renderInfo.getState()); }
126   void drawImplementation(osg::State& state) const
127   {
128     state.pushStateSet(getStateSet());
129     state.apply();
130     state.setActiveTextureUnit(0);
131     state.setClientActiveTextureUnit(0);
132     state.disableAllVertexArrays();
133
134     glPushAttrib(GL_ALL_ATTRIB_BITS);
135     glPushClientAttrib(~0u);
136
137     puDisplay();
138
139     glPopClientAttrib();
140     glPopAttrib();
141
142     state.popStateSet();
143     state.dirtyAllModes();
144     state.dirtyAllAttributes();
145     state.dirtyAllVertexArrays();
146   }
147
148   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
149   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
150   
151 private:
152 };
153
154 class SGHUDAndPanelDrawable : public osg::Drawable {
155 public:
156   SGHUDAndPanelDrawable()
157   {
158     // Dynamic stuff, do not store geometry
159     setUseDisplayList(false);
160
161     osg::StateSet* stateSet = getOrCreateStateSet();
162     stateSet->setRenderBinDetails(1000, "RenderBin");
163
164     // speed optimization?
165     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
166     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
167     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
168     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
169     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
170
171     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
172   }
173   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
174   { drawImplementation(*renderInfo.getState()); }
175   void drawImplementation(osg::State& state) const
176   {
177     state.pushStateSet(getStateSet());
178     state.apply();
179     state.setActiveTextureUnit(0);
180     state.setClientActiveTextureUnit(0);
181     state.disableAllVertexArrays();
182
183     glPushAttrib(GL_ALL_ATTRIB_BITS);
184     glPushClientAttrib(~0u);
185
186     fgCockpitUpdate(&state);
187
188     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
189     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
190     hud->draw(state);
191
192     // update the panel subsystem
193     if ( globals->get_current_panel() != NULL )
194         globals->get_current_panel()->update(state);
195     // We don't need a state here - can be safely removed when we can pick
196     // correctly
197     fgUpdate3DPanels();
198
199     glPopClientAttrib();
200     glPopAttrib();
201
202     state.popStateSet();
203     state.dirtyAllModes();
204     state.dirtyAllAttributes();
205     state.dirtyAllVertexArrays();
206   }
207
208   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
209   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
210   
211 private:
212 };
213
214 class FGLightSourceUpdateCallback : public osg::NodeCallback {
215 public:
216   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
217   {
218     assert(dynamic_cast<osg::LightSource*>(node));
219     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
220     osg::Light* light = lightSource->getLight();
221     
222     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
223     light->setAmbient(l->scene_ambient().osg());
224     light->setDiffuse(l->scene_diffuse().osg());
225     light->setSpecular(l->scene_specular().osg());
226     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
227     light->setPosition(position.osg());
228     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
229     light->setDirection(direction.osg());
230     light->setSpotExponent(0);
231     light->setSpotCutoff(180);
232     light->setConstantAttenuation(1);
233     light->setLinearAttenuation(0);
234     light->setQuadraticAttenuation(0);
235
236     traverse(node, nv);
237   }
238 };
239
240 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
241 public:
242   FGWireFrameModeUpdateCallback() :
243     mWireframe(fgGetNode("/sim/rendering/wireframe"))
244   { }
245   virtual void operator()(osg::StateAttribute* stateAttribute,
246                           osg::NodeVisitor*)
247   {
248     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
249     osg::PolygonMode* polygonMode;
250     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
251
252     if (mWireframe->getBoolValue())
253       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
254                            osg::PolygonMode::LINE);
255     else
256       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
257                            osg::PolygonMode::FILL);
258   }
259 private:
260   SGSharedPtr<SGPropertyNode> mWireframe;
261 };
262
263 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
264 public:
265   FGLightModelUpdateCallback() :
266     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
267   { }
268   virtual void operator()(osg::StateAttribute* stateAttribute,
269                           osg::NodeVisitor*)
270   {
271     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
272     osg::LightModel* lightModel;
273     lightModel = static_cast<osg::LightModel*>(stateAttribute);
274
275 #if 0
276     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
277     lightModel->setAmbientIntensity(l->scene_ambient().osg());
278 #else
279     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
280 #endif
281     lightModel->setTwoSided(true);
282     lightModel->setLocalViewer(false);
283
284     if (mHighlights->getBoolValue()) {
285       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
286     } else {
287       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
288     }
289   }
290 private:
291   SGSharedPtr<SGPropertyNode> mHighlights;
292 };
293
294 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
295 public:
296   FGFogEnableUpdateCallback() :
297     mFogEnabled(fgGetNode("/sim/rendering/fog"))
298   { }
299   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
300   {
301     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
302       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
303     } else {
304       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
305     }
306   }
307 private:
308   SGSharedPtr<SGPropertyNode> mFogEnabled;
309 };
310
311 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
312 public:
313   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
314   {
315     assert(dynamic_cast<SGUpdateVisitor*>(nv));
316     assert(dynamic_cast<osg::Fog*>(sa));
317     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
318     osg::Fog* fog = static_cast<osg::Fog*>(sa);
319     fog->setMode(osg::Fog::EXP2);
320     fog->setColor(updateVisitor->getFogColor().osg());
321     fog->setDensity(updateVisitor->getFogExp2Density());
322   }
323 };
324
325 // update callback for the switch node guarding that splash
326 class FGScenerySwitchCallback : public osg::NodeCallback {
327 public:
328   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
329   {
330     assert(dynamic_cast<osg::Switch*>(node));
331     osg::Switch* sw = static_cast<osg::Switch*>(node);
332
333     double t = globals->get_sim_time_sec();
334     bool enabled = 0 < t;
335     sw->setValue(0, enabled);
336     if (!enabled)
337       return;
338     traverse(node, nv);
339   }
340 };
341
342 // Sky structures
343 SGSky *thesky;
344
345 osg::ref_ptr<osgUtil::SceneView> sceneView = new osgUtil::SceneView;  // This SceneView is used by class FGJpegHttpd ( jpg-httpd.cxx )
346 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
347 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
348
349 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
350
351 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
352
353 static osg::ref_ptr<osg::CameraView> mCameraView = new osg::CameraView;
354 static osg::ref_ptr<osg::Camera> mBackGroundCamera = new osg::Camera;
355
356 FGRenderer::FGRenderer()
357 {
358 #ifdef FG_JPEG_SERVER
359    jpgRenderFrame = FGRenderer::update;
360 #endif
361 #ifdef ENABLE_OSGVIEWER
362    manipulator = new FGManipulator;
363 #endif   
364 }
365
366 FGRenderer::~FGRenderer()
367 {
368 #ifdef FG_JPEG_SERVER
369    jpgRenderFrame = NULL;
370 #endif
371 }
372
373 // Initialize various GL/view parameters
374 // XXX This should be called "preinit" or something, as it initializes
375 // critical parts of the scene graph in addition to the splash screen.
376 void
377 FGRenderer::splashinit( void ) {
378     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
379     if (viewer) {
380         sceneView = 0;
381         mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
382         mRealRoot->addChild(fgCreateSplashNode());
383         osgViewer::Scene* scene = viewer->getScene();
384         mFrameStamp = viewer->getFrameStamp();
385         // Scene doesn't seem to pass the frame stamp to the update
386         // visitor automatically.
387         mUpdateVisitor->setFrameStamp(mFrameStamp.get());
388         scene->setUpdateVisitor(mUpdateVisitor.get());
389     } else {
390         // Add the splash screen node
391         mRealRoot->addChild(fgCreateSplashNode());
392         sceneView->setSceneData(mRealRoot.get());
393         sceneView->setDefaults(osgUtil::SceneView::COMPILE_GLOBJECTS_AT_INIT);
394         sceneView->setFrameStamp(mFrameStamp.get());
395         sceneView->setUpdateVisitor(mUpdateVisitor.get());
396     }
397 }
398
399 void
400 FGRenderer::init( void ) {
401     // The viewer can call this before the graphics context is current
402     // in the main thread; indeed, in a multithreaded setup it might
403     // never be current in the main thread.
404     fgMakeCurrent();
405     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
406     osg::initNotifyLevel();
407
408     // The number of polygon-offset "units" to place between layers.  In
409     // principle, one is supposed to be enough.  In practice, I find that
410     // my hardware/driver requires many more.
411     osg::PolygonOffset::setUnitsMultiplier(1);
412     osg::PolygonOffset::setFactorMultiplier(1);
413
414     // Go full screen if requested ...
415     if ( fgGetBool("/sim/startup/fullscreen") )
416         fgOSFullScreen();
417
418     if ( (!strcmp(fgGetString("/sim/rendering/fog"), "disabled")) || 
419          (!fgGetBool("/sim/rendering/shading"))) {
420         // if fastest fog requested, or if flat shading force fastest
421         glHint ( GL_FOG_HINT, GL_FASTEST );
422     } else if ( !strcmp(fgGetString("/sim/rendering/fog"), "nicest") ) {
423         glHint ( GL_FOG_HINT, GL_DONT_CARE );
424     }
425
426     glHint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
427     glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
428     glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
429
430     if (viewer) {
431         viewer->getCamera()
432             ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
433     } else {
434         sceneView->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
435         sceneView->getCamera()->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
436     }
437
438
439     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
440
441     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
442     
443     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
444     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
445
446     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
447     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
448     stateSet->setAttribute(new osg::BlendFunc);
449     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
450
451     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
452     
453     // this will be set below
454     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
455
456     osg::Material* material = new osg::Material;
457     stateSet->setAttribute(material);
458     
459     stateSet->setTextureAttribute(0, new osg::TexEnv);
460     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
461
462
463 //     stateSet->setAttribute(new osg::CullFace(osg::CullFace::BACK));
464 //     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::ON);
465
466     // this is the topmost scenegraph node for osg
467     mBackGroundCamera->addChild(thesky->getPreRoot());
468     mBackGroundCamera->setClearMask(0);
469
470     GLbitfield inheritanceMask = osg::CullSettings::ALL_VARIABLES;
471     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
472     inheritanceMask &= ~osg::CullSettings::NEAR_FAR_RATIO;
473     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
474     mBackGroundCamera->setInheritanceMask(inheritanceMask);
475     mBackGroundCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
476     mBackGroundCamera->setCullingMode(osg::CullSettings::NO_CULLING);
477     mBackGroundCamera->setRenderOrder(osg::Camera::NESTED_RENDER);
478
479     stateSet = mBackGroundCamera->getOrCreateStateSet();
480     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
481
482     osg::Group* sceneGroup = new osg::Group;
483     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
484     sceneGroup->addChild(thesky->getCloudRoot());
485
486     stateSet = sceneGroup->getOrCreateStateSet();
487     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
488     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
489
490     // need to update the light on every frame
491     osg::LightSource* lightSource = new osg::LightSource;
492     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
493     // relative because of CameraView being just a clever transform node
494     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
495     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
496     mRoot->addChild(lightSource);
497
498     lightSource->addChild(mBackGroundCamera.get());
499     lightSource->addChild(sceneGroup);
500
501
502     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
503     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
504     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
505     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
506     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
507
508     // enable disable specular highlights.
509     // is the place where we might plug in an other fragment shader ...
510     osg::LightModel* lightModel = new osg::LightModel;
511     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
512     stateSet->setAttribute(lightModel);
513
514     // switch to enable wireframe
515     osg::PolygonMode* polygonMode = new osg::PolygonMode;
516     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
517     stateSet->setAttributeAndModes(polygonMode);
518
519     // scene fog handling
520     osg::Fog* fog = new osg::Fog;
521     fog->setUpdateCallback(new FGFogUpdateCallback);
522     stateSet->setAttributeAndModes(fog);
523     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
524
525     // plug in the GUI
526     osg::Camera* guiCamera = new osg::Camera;
527     guiCamera->setRenderOrder(osg::Camera::POST_RENDER, 100);
528     guiCamera->setClearMask(0);
529     inheritanceMask = osg::CullSettings::ALL_VARIABLES;
530     inheritanceMask &= ~osg::CullSettings::COMPUTE_NEAR_FAR_MODE;
531     inheritanceMask &= ~osg::CullSettings::CULLING_MODE;
532     guiCamera->setInheritanceMask(inheritanceMask);
533     guiCamera->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
534     guiCamera->setCullingMode(osg::CullSettings::NO_CULLING);
535     osg::Geode* geode = new osg::Geode;
536     geode->addDrawable(new SGPuDrawable);
537     geode->addDrawable(new SGHUDAndPanelDrawable);
538     guiCamera->addChild(geode);
539
540     mCameraView->addChild(mRoot.get());
541
542     osg::Switch* sw = new osg::Switch;
543     sw->setUpdateCallback(new FGScenerySwitchCallback);
544     sw->addChild(mCameraView.get());
545
546     mRealRoot->addChild(sw);
547     mRealRoot->addChild(FGCreateRedoutNode());
548     mRealRoot->addChild(guiCamera);
549 //  sceneView->getState()->setCheckForGLErrors(osg::State::ONCE_PER_ATTRIBUTE);
550 }
551
552
553 // Update all Visuals (redraws anything graphics related)
554 void
555 FGRenderer::update( bool refresh_camera_settings ) {
556     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
557                           || fgGetBool("sim/sceneryloaded-override");
558     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
559     if ( idle_state < 1000 || !scenery_loaded ) {
560         fgSetDouble("/sim/startup/splash-alpha", 1.0);
561
562         // Keep resetting sim time while the sim is initializing
563         globals->set_sim_time_sec( 0.0 );
564
565         // the splash screen is now in the scenegraph
566         if (!viewer) {
567             sceneView->update();
568             sceneView->cull();
569             sceneView->draw();
570         }
571         return;
572     }
573
574     // Fade out the splash screen over the first three seconds.
575     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
576     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
577
578     bool skyblend = fgGetBool("/sim/rendering/skyblend");
579     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
580     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
581     bool distance_attenuation
582         = fgGetBool("/sim/rendering/distance-attenuation");
583     // OSGFIXME
584     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
585                                   distance_attenuation );
586
587     static const SGPropertyNode *groundlevel_nearplane
588         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
589
590     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
591
592     // update fog params
593     double actual_visibility;
594     if (fgGetBool("/environment/clouds/status")) {
595         actual_visibility = thesky->get_visibility();
596     } else {
597         actual_visibility = fgGetDouble("/environment/visibility-m");
598     }
599
600     // idle_state is now 1000 meaning we've finished all our
601     // initializations and are running the main loop, so this will
602     // now work without seg faulting the system.
603
604     FGViewer *current__view = globals->get_current_view();
605     // Force update of center dependent values ...
606     current__view->set_dirty();
607
608     if ( refresh_camera_settings ) {
609         // update view port
610         resize( fgGetInt("/sim/startup/xsize"),
611                 fgGetInt("/sim/startup/ysize") );
612
613         SGVec3d position = current__view->getViewPosition();
614         SGQuatd attitude = current__view->getViewOrientation();
615         SGVec3d osgPosition = attitude.transform(-position);
616         if (viewer) {
617             FGManipulator *manipulator
618                 = globals->get_renderer()->getManipulator();
619             manipulator->setPosition(position.osg());
620             manipulator->setAttitude(attitude.osg());
621         } else {
622             mCameraView->setPosition(osgPosition.osg());
623             mCameraView->setAttitude(inverse(attitude).osg());
624         }
625     }
626     osg::Camera *camera;
627     if (viewer)
628         camera = viewer->getCamera();
629     else
630         camera = sceneView->getCamera();
631     if ( skyblend ) {
632         
633         if ( fgGetBool("/sim/rendering/textures") ) {
634             SGVec4f clearColor(l->adj_fog_color());
635             camera->setClearColor(clearColor.osg());
636         }
637     } else {
638         SGVec4f clearColor(l->sky_color());
639         camera->setClearColor(clearColor.osg());
640     }
641
642     // update fog params if visibility has changed
643     double visibility_meters = fgGetDouble("/environment/visibility-m");
644     thesky->set_visibility(visibility_meters);
645
646     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
647                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
648                         / (double)fgGetInt("/sim/model-hz") );
649
650     // update the sky dome
651     if ( skyblend ) {
652
653         // The sun and moon distances are scaled down versions
654         // of the actual distance to get both the moon and the sun
655         // within the range of the far clip plane.
656         // Moon distance:    384,467 kilometers
657         // Sun distance: 150,000,000 kilometers
658
659         double sun_horiz_eff, moon_horiz_eff;
660         if (fgGetBool("/sim/rendering/horizon-effect")) {
661            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
662            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
663         } else {
664            sun_horiz_eff = moon_horiz_eff = 1.0;
665         }
666
667         static SGSkyState sstate;
668
669         sstate.view_pos  = toVec3f(current__view->get_view_pos());
670         sstate.zero_elev = toVec3f(current__view->get_zero_elev());
671         sstate.view_up   = current__view->get_world_up();
672         sstate.lon       = current__view->getLongitude_deg()
673                             * SGD_DEGREES_TO_RADIANS;
674         sstate.lat       = current__view->getLatitude_deg()
675                             * SGD_DEGREES_TO_RADIANS;
676         sstate.alt       = current__view->getAltitudeASL_ft()
677                             * SG_FEET_TO_METER;
678         sstate.spin      = l->get_sun_rotation();
679         sstate.gst       = globals->get_time_params()->getGst();
680         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
681         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
682         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
683         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
684         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
685         sstate.moon_dist = 40000.0 * moon_horiz_eff;
686         sstate.sun_angle = l->get_sun_angle();
687
688
689         /*
690          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
691          << l->sky_color()[0] << " "
692          << l->sky_color()[1] << " "
693          << l->sky_color()[2] << " "
694          << l->sky_color()[3] );
695         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
696          << l->fog_color()[0] << " "
697          << l->fog_color()[1] << " "
698          << l->fog_color()[2] << " "
699          << l->fog_color()[3] );
700         SG_LOG( SG_GENERAL, SG_BULK,
701                 "    sun_angle = " << l->sun_angle
702          << "    moon_angle = " << l->moon_angle );
703         */
704
705         static SGSkyColor scolor;
706
707         scolor.sky_color   = SGVec3f(l->sky_color().data());
708         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
709         scolor.cloud_color = SGVec3f(l->cloud_color().data());
710         scolor.sun_angle   = l->get_sun_angle();
711         scolor.moon_angle  = l->get_moon_angle();
712         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
713         scolor.nstars      = globals->get_ephem()->getNumStars();
714         scolor.planet_data = globals->get_ephem()->getPlanets();
715         scolor.star_data   = globals->get_ephem()->getStars();
716
717         thesky->reposition( sstate, delta_time_sec );
718         thesky->repaint( scolor );
719
720         /*
721         SG_LOG( SG_GENERAL, SG_BULK,
722                 "thesky->reposition( view_pos = " << view_pos[0] << " "
723          << view_pos[1] << " " << view_pos[2] );
724         SG_LOG( SG_GENERAL, SG_BULK,
725                 "    zero_elev = " << zero_elev[0] << " "
726          << zero_elev[1] << " " << zero_elev[2]
727          << " lon = " << cur_fdm_state->get_Longitude()
728          << " lat = " << cur_fdm_state->get_Latitude() );
729         SG_LOG( SG_GENERAL, SG_BULK,
730                 "    sun_rot = " << l->get_sun_rotation
731          << " gst = " << SGTime::cur_time_params->getGst() );
732         SG_LOG( SG_GENERAL, SG_BULK,
733              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
734           << " sun dec = " << globals->get_ephem()->getSunDeclination()
735           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
736           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
737         */
738
739         //OSGFIXME
740 //         shadows->setupShadows(
741 //           current__view->getLongitude_deg(),
742 //           current__view->getLatitude_deg(),
743 //           globals->get_time_params()->getGst(),
744 //           globals->get_ephem()->getSunRightAscension(),
745 //           globals->get_ephem()->getSunDeclination(),
746 //           l->get_sun_angle());
747
748     }
749
750 //     sgEnviro.setLight(l->adj_fog_color());
751
752     // texture parameters
753     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
754
755     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
756       - current__view->getSGLocation()->get_cur_elev_m();
757
758     float scene_nearplane, scene_farplane;
759     if ( agl > 10.0 ) {
760         scene_nearplane = 10.0f;
761         scene_farplane = 120000.0f;
762     } else {
763         scene_nearplane = groundlevel_nearplane->getDoubleValue();
764         scene_farplane = 120000.0f;
765     }
766     setNearFar( scene_nearplane, scene_farplane );
767
768 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
769 //         current__view->get_world_up(),
770 //         current__view->getLongitude_deg(),
771 //         current__view->getLatitude_deg(),
772 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
773 //         delta_time_sec);
774
775     // OSGFIXME
776 //     sgEnviro.drawLightning();
777
778 //        double current_view_origin_airspeed_horiz_kt =
779 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
780 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
781 //                                * SGD_DEGREES_TO_RADIANS);
782        // TODO:find the real view speed, not the AC one
783 //     sgEnviro.drawPrecipitation(
784 //         fgGetDouble("/environment/metar/rain-norm", 0.0),
785 //         fgGetDouble("/environment/metar/snow-norm", 0.0),
786 //         fgGetDouble("/environment/metar/hail-norm", 0.0),
787 //         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
788 //         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
789 //         - current__view->getHeadingOffset_deg(),
790 //                current_view_origin_airspeed_horiz_kt
791 //                );
792
793     // OSGFIXME
794 //     if( is_internal )
795 //         shadows->endOfFrame();
796
797     // need to call the update visitor once
798     if (!viewer) {
799         mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
800         mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
801     }
802     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
803     mUpdateVisitor->setViewData(current__view->getViewPosition(),
804                                 current__view->getViewOrientation());
805     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
806     mUpdateVisitor->setLight(direction, l->scene_ambient(),
807                              l->scene_diffuse(), l->scene_specular(),
808                              l->adj_fog_color(),
809                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
810     mUpdateVisitor->setVisibility(actual_visibility);
811     bool hotspots = fgGetBool("/sim/panel-hotspots");
812     if (viewer) {
813         if (hotspots)
814             camera->setCullMask(camera->getCullMask()|SG_NODEMASK_PICK_BIT);
815         else
816             camera->setCullMask(camera->getCullMask()
817                                 & ~SG_NODEMASK_PICK_BIT);
818     } else {
819         if (hotspots)
820             sceneView->setCullMask(sceneView->getCullMask()
821                                    |SG_NODEMASK_PICK_BIT);
822         else
823             sceneView->setCullMask(sceneView->getCullMask()
824                                    &(~SG_NODEMASK_PICK_BIT));
825         sceneView->update();
826         sceneView->cull();
827         sceneView->draw();
828     }
829 }
830
831
832
833 // options.cxx needs to see this for toggle_panel()
834 // Handle new window size or exposure
835 void
836 FGRenderer::resize( int width, int height ) {
837     int view_h;
838
839     if ( (!fgGetBool("/sim/virtual-cockpit"))
840          && fgPanelVisible() && idle_state == 1000 ) {
841         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
842                              globals->get_current_panel()->getYOffset()) / 768.0);
843     } else {
844         view_h = height;
845     }
846     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
847     if (viewer)
848         viewer->getCamera()->getViewport()->setViewport(0, height - view_h,
849                                                         width, view_h);
850     else
851         sceneView->getViewport()->setViewport(0, height - view_h,
852                                               width, view_h);
853
854     static int lastwidth = 0;
855     static int lastheight = 0;
856     if (width != lastwidth)
857         fgSetInt("/sim/startup/xsize", lastwidth = width);
858     if (height != lastheight)
859         fgSetInt("/sim/startup/ysize", lastheight = height);
860
861     guiInitMouse(width, height);
862
863     // for all views
864     FGViewMgr *viewmgr = globals->get_viewmgr();
865     if (viewmgr) {
866       for ( int i = 0; i < viewmgr->size(); ++i ) {
867         viewmgr->get_view(i)->
868           set_aspect_ratio((float)view_h / (float)width);
869       }
870
871       setFOV( viewmgr->get_current_view()->get_h_fov(),
872               viewmgr->get_current_view()->get_v_fov() );
873     }
874 }
875
876
877 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
878 // which will post process and rewrite the resulting frustum if we
879 // want to do asymmetric view frustums.
880
881 static void fgHackFrustum() {
882
883     // specify a percent of the configured view frustum to actually
884     // display.  This is a bit of a hack to achieve asymmetric view
885     // frustums.  For instance, if you want to display two monitors
886     // side by side, you could specify each with a double fov, a 0.5
887     // aspect ratio multiplier, and then the left side monitor would
888     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
889     // and a top_pct = 1.0.  The right side monitor would have a
890     // left_pct = 0.5 and a right_pct = 1.0.
891
892     static SGPropertyNode *left_pct
893         = fgGetNode("/sim/current-view/frustum-left-pct");
894     static SGPropertyNode *right_pct
895         = fgGetNode("/sim/current-view/frustum-right-pct");
896     static SGPropertyNode *bottom_pct
897         = fgGetNode("/sim/current-view/frustum-bottom-pct");
898     static SGPropertyNode *top_pct
899         = fgGetNode("/sim/current-view/frustum-top-pct");
900     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
901     double left, right;
902     double bottom, top;
903     double zNear, zFar;
904     if (viewer)
905         viewer->getCamera()->getProjectionMatrixAsFrustum(left, right,
906                                                           bottom, top,
907                                                           zNear, zFar);
908     else
909         sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top,
910                                                 zNear, zFar);
911     // cout << " l = " << f->getLeft()
912     //      << " r = " << f->getRight()
913     //      << " b = " << f->getBot()
914     //      << " t = " << f->getTop()
915     //      << " n = " << f->getNear()
916     //      << " f = " << f->getFar()
917     //      << endl;
918
919     double width = right - left;
920     double height = top - bottom;
921
922     double l, r, t, b;
923
924     if ( left_pct != NULL ) {
925         l = left + width * left_pct->getDoubleValue();
926     } else {
927         l = left;
928     }
929
930     if ( right_pct != NULL ) {
931         r = left + width * right_pct->getDoubleValue();
932     } else {
933         r = right;
934     }
935
936     if ( bottom_pct != NULL ) {
937         b = bottom + height * bottom_pct->getDoubleValue();
938     } else {
939         b = bottom;
940     }
941
942     if ( top_pct != NULL ) {
943         t = bottom + height * top_pct->getDoubleValue();
944     } else {
945         t = top;
946     }
947     if (viewer)
948         viewer->getCamera()->setProjectionMatrixAsFrustum(l, r, b, t,
949                                                           zNear, zFar);
950     else
951         sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
952 }
953
954
955 // we need some static storage space for these values.  However, we
956 // can't store it in a renderer class object because the functions
957 // that manipulate these are static.  They are static so they can
958 // interface to the display callback system.  There's probably a
959 // better way, there has to be a better way, but I'm not seeing it
960 // right now.
961 static float fov_width = 55.0;
962 static float fov_height = 42.0;
963 static float fov_near = 1.0;
964 static float fov_far = 1000.0;
965
966
967 /** FlightGear code should use this routine to set the FOV rather than
968  *  calling the ssg routine directly
969  */
970 void FGRenderer::setFOV( float w, float h ) {
971     fov_width = w;
972     fov_height = h;
973     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
974     if (viewer)
975         viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height,
976                                                               fov_width/fov_height,
977                                                               fov_near, fov_far);
978     else
979         sceneView->setProjectionMatrixAsPerspective(fov_height,
980                                                     fov_width/fov_height,
981                                                     fov_near, fov_far);
982     // fully specify the view frustum before hacking it (so we don't
983     // accumulate hacked effects
984     fgHackFrustum();
985 //     sgEnviro.setFOV( w, h );
986 }
987
988
989 /** FlightGear code should use this routine to set the Near/Far clip
990  *  planes rather than calling the ssg routine directly
991  */
992 void FGRenderer::setNearFar( float n, float f ) {
993 // OSGFIXME: we have currently too much z-buffer fights
994 n = 0.1;
995     fov_near = n;
996     fov_far = f;
997     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
998     if (viewer)
999         viewer->getCamera()->setProjectionMatrixAsPerspective(fov_height,
1000                                                               fov_width/fov_height,
1001                                                               fov_near, fov_far);
1002     else 
1003         sceneView->setProjectionMatrixAsPerspective(fov_height,
1004                                                     fov_width/fov_height,
1005                                                     fov_near, fov_far);
1006
1007     // fully specify the view frustum before hacking it (so we don't
1008     // accumulate hacked effects
1009     fgHackFrustum();
1010 }
1011
1012 bool
1013 FGRenderer::pick( unsigned x, unsigned y,
1014                   std::vector<SGSceneryPick>& pickList )
1015 {
1016   osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
1017   // wipe out the return ...
1018   pickList.resize(0);
1019
1020   osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
1021   if (!sceneData)
1022     return false;
1023   osg::Viewport* viewport = 0;
1024   osg::Matrix projection;
1025   osg::Matrix modelview;
1026
1027   if (sceneView.valid()) {
1028     viewport = sceneView->getViewport();
1029     if (!viewport)
1030       return false;
1031     // don't know why, but the update has partly happened somehow,
1032     // so update the scenery part of the viewer
1033     FGViewer *current_view = globals->get_current_view();
1034     // Force update of center dependent values ...
1035     current_view->set_dirty();
1036     SGVec3d position = current_view->getViewPosition();
1037     SGQuatd attitude = current_view->getViewOrientation();
1038     SGVec3d osgPosition = attitude.transform(-position);
1039     mCameraView->setPosition(osgPosition.osg());
1040     mCameraView->setAttitude(inverse(attitude).osg());
1041
1042     osg::Matrix projection(sceneView->getProjectionMatrix());
1043     osg::Matrix modelview(sceneView->getViewMatrix());
1044
1045     osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1046     // modify the view matrix so that it accounts for this nodePath's
1047     // accumulated transform
1048     if (!nodePath.empty())
1049       modelview.preMult(computeLocalToWorld(nodePath.front()));
1050   } else if (viewer) {
1051     // I don't think the Viewer case needs to update the camera
1052     // matrices before picking. The user has clicked on the old scene
1053     // -- that which is displayed in the front buffer -- so we need to
1054     // use the camera state in effect for that view of the scene.
1055     osg::Camera *camera = viewer->getCamera();
1056     viewport = camera->getViewport();
1057     projection = camera->getProjectionMatrix();
1058     modelview = camera->getViewMatrix();
1059     // Accumulated transforms? Don't think that applies for the
1060     // Viewer's camera.
1061   } else {                      // we can get called early ...
1062     return false;
1063   }
1064   // swap the y values ...
1065   y = viewport->height() - y;
1066   // set up the pick visitor
1067   osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1068   sceneData->accept(pickVisitor);
1069   if (!pickVisitor.hits())
1070     return false;
1071
1072   // collect all interaction callbacks on the pick ray.
1073   // They get stored in the pickCallbacks list where they are sorted back
1074   // to front and croasest to finest wrt the scenery node they are attached to
1075   osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1076   for (mi = pickVisitor.getSegHitList().begin();
1077        mi != pickVisitor.getSegHitList().end();
1078        ++mi) {
1079     osgUtil::IntersectVisitor::HitList::const_iterator hi;
1080     for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1081       // ok, go back the nodes and ask for intersection callbacks,
1082       // execute them in top down order
1083       const osg::NodePath& np = hi->getNodePath();
1084       osg::NodePath::const_reverse_iterator npi;
1085       for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1086         SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1087         if (!ud)
1088           continue;
1089         for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1090           SGPickCallback* pickCallback = ud->getPickCallback(i);
1091           if (!pickCallback)
1092             continue;
1093           SGSceneryPick sceneryPick;
1094           /// note that this is done totally in doubles instead of
1095           /// just using getWorldIntersectionPoint
1096           osg::Vec3d localPt = hi->getLocalIntersectPoint();
1097           sceneryPick.info.local = SGVec3d(localPt);
1098           if (hi->getMatrix())
1099             sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1100           else
1101             sceneryPick.info.wgs84 = SGVec3d(localPt);
1102           sceneryPick.callback = pickCallback;
1103           pickList.push_back(sceneryPick);
1104         }
1105       }
1106     }
1107   }
1108
1109   return !pickList.empty();
1110 }
1111
1112 bool fgDumpSceneGraphToFile(const char* filename)
1113 {
1114     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
1115 }
1116
1117 // end of renderer.cxx
1118