]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Merge branch 'luff/kln89'
[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 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <osg/ref_ptr>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/Camera>
36 #include <osg/CullFace>
37 #include <osg/Depth>
38 #include <osg/Fog>
39 #include <osg/Group>
40 #include <osg/Hint>
41 #include <osg/Light>
42 #include <osg/LightModel>
43 #include <osg/LightSource>
44 #include <osg/Material>
45 #include <osg/Math>
46 #include <osg/NodeCallback>
47 #include <osg/Notify>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/Version>
51 #include <osg/TexEnv>
52
53 #include <osgUtil/LineSegmentIntersector>
54
55 #include <osg/io_utils>
56 #include <osgDB/WriteFile>
57
58 #include <simgear/math/SGMath.hxx>
59 #include <simgear/screen/extensions.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/sky/sky.hxx>
64 #include <simgear/scene/util/SGUpdateVisitor.hxx>
65 #include <simgear/scene/util/RenderConstants.hxx>
66 #include <simgear/scene/util/SGSceneUserData.hxx>
67 #include <simgear/scene/tgdb/GroundLightManager.hxx>
68 #include <simgear/scene/tgdb/pt_lights.hxx>
69 #include <simgear/structure/OSGUtils.hxx>
70 #include <simgear/props/props.hxx>
71 #include <simgear/timing/sg_time.hxx>
72 #include <simgear/ephemeris/ephemeris.hxx>
73 #include <simgear/math/sg_random.h>
74 #ifdef FG_JPEG_SERVER
75 #include <simgear/screen/jpgfactory.hxx>
76 #endif
77
78 #include <simgear/environment/visual_enviro.hxx>
79
80 #include <Time/light.hxx>
81 #include <Time/light.hxx>
82 #include <Aircraft/aircraft.hxx>
83 #include <Cockpit/panel.hxx>
84 #include <Cockpit/cockpit.hxx>
85 #include <Cockpit/hud.hxx>
86 #include <Model/panelnode.hxx>
87 #include <Model/modelmgr.hxx>
88 #include <Model/acmodel.hxx>
89 #include <Scenery/scenery.hxx>
90 #include <Scenery/redout.hxx>
91 #include <Scenery/tilemgr.hxx>
92 #include <GUI/new_gui.hxx>
93 #include <Instrumentation/instrument_mgr.hxx>
94 #include <Instrumentation/HUD/HUD.hxx>
95 #include <Environment/precipitation_mgr.hxx>
96
97 #include <Include/general.hxx>
98 #include "splash.hxx"
99 #include "renderer.hxx"
100 #include "main.hxx"
101 #include "CameraGroup.hxx"
102 #include "FGEventHandler.hxx"
103 #include <Main/viewer.hxx>
104
105 using namespace osg;
106 using namespace simgear;
107 using namespace flightgear;
108
109 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
110 public:
111   FGHintUpdateCallback(const char* configNode) :
112     mConfigNode(fgGetNode(configNode, true))
113   { }
114   virtual void operator()(osg::StateAttribute* stateAttribute,
115                           osg::NodeVisitor*)
116   {
117     assert(dynamic_cast<osg::Hint*>(stateAttribute));
118     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
119
120     const char* value = mConfigNode->getStringValue();
121     if (!value)
122       hint->setMode(GL_DONT_CARE);
123     else if (0 == strcmp(value, "nicest"))
124       hint->setMode(GL_NICEST);
125     else if (0 == strcmp(value, "fastest"))
126       hint->setMode(GL_FASTEST);
127     else
128       hint->setMode(GL_DONT_CARE);
129   }
130 private:
131   SGSharedPtr<SGPropertyNode> mConfigNode;
132 };
133
134
135 class SGPuDrawable : public osg::Drawable {
136 public:
137   SGPuDrawable()
138   {
139     // Dynamic stuff, do not store geometry
140     setUseDisplayList(false);
141
142     osg::StateSet* stateSet = getOrCreateStateSet();
143     stateSet->setRenderBinDetails(1001, "RenderBin");
144     // speed optimization?
145     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
146     // We can do translucent menus, so why not. :-)
147     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
148     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
149     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
150
151     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
152
153     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
154     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
155   }
156   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
157   { drawImplementation(*renderInfo.getState()); }
158   void drawImplementation(osg::State& state) const
159   {
160     state.setActiveTextureUnit(0);
161     state.setClientActiveTextureUnit(0);
162
163     state.disableAllVertexArrays();
164
165     glPushAttrib(GL_ALL_ATTRIB_BITS);
166     glPushClientAttrib(~0u);
167
168     puDisplay();
169
170     glPopClientAttrib();
171     glPopAttrib();
172   }
173
174   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
175   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
176   
177 private:
178 };
179
180 class SGHUDAndPanelDrawable : public osg::Drawable {
181 public:
182   SGHUDAndPanelDrawable()
183   {
184     // Dynamic stuff, do not store geometry
185     setUseDisplayList(false);
186
187     osg::StateSet* stateSet = getOrCreateStateSet();
188     stateSet->setRenderBinDetails(1000, "RenderBin");
189
190     // speed optimization?
191     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
192     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
193     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
194     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
195     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
196
197     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
198   }
199   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
200   { drawImplementation(*renderInfo.getState()); }
201   void drawImplementation(osg::State& state) const
202   {
203     state.setActiveTextureUnit(0);
204     state.setClientActiveTextureUnit(0);
205     state.disableAllVertexArrays();
206
207     glPushAttrib(GL_ALL_ATTRIB_BITS);
208     glPushClientAttrib(~0u);
209
210     fgCockpitUpdate(&state);
211
212     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
213     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
214     hud->draw(state);
215
216     // update the panel subsystem
217     if ( globals->get_current_panel() != NULL )
218         globals->get_current_panel()->update(state);
219     // We don't need a state here - can be safely removed when we can pick
220     // correctly
221     fgUpdate3DPanels();
222
223     glPopClientAttrib();
224     glPopAttrib();
225
226   }
227
228   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
229   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
230   
231 private:
232 };
233
234 class FGLightSourceUpdateCallback : public osg::NodeCallback {
235 public:
236   
237   /**
238    * @param isSun true if the light is the actual sun i.e., for
239    * illuminating the moon.
240    */
241   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
242   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
243                               const CopyOp& op)
244     : NodeCallback(nc, op), _isSun(nc._isSun)
245   {}
246   META_Object(flightgear,FGLightSourceUpdateCallback);
247   
248   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
249   {
250     assert(dynamic_cast<osg::LightSource*>(node));
251     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
252     osg::Light* light = lightSource->getLight();
253     
254     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
255     if (_isSun) {
256       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
257       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
258       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
259     } else {
260       light->setAmbient(toOsg(l->scene_ambient()));
261       light->setDiffuse(toOsg(l->scene_diffuse()));
262       light->setSpecular(toOsg(l->scene_specular()));
263     }
264     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
265     light->setPosition(position);
266
267     traverse(node, nv);
268   }
269 private:
270   const bool _isSun;
271 };
272
273 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
274 public:
275   FGWireFrameModeUpdateCallback() :
276     mWireframe(fgGetNode("/sim/rendering/wireframe"))
277   { }
278   virtual void operator()(osg::StateAttribute* stateAttribute,
279                           osg::NodeVisitor*)
280   {
281     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
282     osg::PolygonMode* polygonMode;
283     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
284
285     if (mWireframe->getBoolValue())
286       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
287                            osg::PolygonMode::LINE);
288     else
289       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
290                            osg::PolygonMode::FILL);
291   }
292 private:
293   SGSharedPtr<SGPropertyNode> mWireframe;
294 };
295
296 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
297 public:
298   FGLightModelUpdateCallback() :
299     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
300   { }
301   virtual void operator()(osg::StateAttribute* stateAttribute,
302                           osg::NodeVisitor*)
303   {
304     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
305     osg::LightModel* lightModel;
306     lightModel = static_cast<osg::LightModel*>(stateAttribute);
307
308 #if 0
309     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
310     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
311 #else
312     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
313 #endif
314     lightModel->setTwoSided(true);
315     lightModel->setLocalViewer(false);
316
317     if (mHighlights->getBoolValue()) {
318       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
319     } else {
320       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
321     }
322   }
323 private:
324   SGSharedPtr<SGPropertyNode> mHighlights;
325 };
326
327 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
328 public:
329   FGFogEnableUpdateCallback() :
330     mFogEnabled(fgGetNode("/sim/rendering/fog"))
331   { }
332   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
333   {
334     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
335       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
336     } else {
337       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
338     }
339   }
340 private:
341   SGSharedPtr<SGPropertyNode> mFogEnabled;
342 };
343
344 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
345 public:
346   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
347   {
348     assert(dynamic_cast<SGUpdateVisitor*>(nv));
349     assert(dynamic_cast<osg::Fog*>(sa));
350     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
351     osg::Fog* fog = static_cast<osg::Fog*>(sa);
352     fog->setMode(osg::Fog::EXP2);
353     fog->setColor(toOsg(updateVisitor->getFogColor()));
354     fog->setDensity(updateVisitor->getFogExp2Density());
355   }
356 };
357
358 // update callback for the switch node guarding that splash
359 class FGScenerySwitchCallback : public osg::NodeCallback {
360 public:
361   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
362   {
363     assert(dynamic_cast<osg::Switch*>(node));
364     osg::Switch* sw = static_cast<osg::Switch*>(node);
365
366     double t = globals->get_sim_time_sec();
367     bool enabled = 0 < t;
368     sw->setValue(0, enabled);
369     if (!enabled)
370       return;
371     traverse(node, nv);
372   }
373 };
374
375 // Sky structures
376 SGSky *thesky;
377
378 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
379 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
380
381 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
382
383 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
384
385 FGRenderer::FGRenderer()
386 {
387 #ifdef FG_JPEG_SERVER
388    jpgRenderFrame = FGRenderer::update;
389 #endif
390    eventHandler = new FGEventHandler;
391 }
392
393 FGRenderer::~FGRenderer()
394 {
395 #ifdef FG_JPEG_SERVER
396    jpgRenderFrame = NULL;
397 #endif
398 }
399
400 // Initialize various GL/view parameters
401 // XXX This should be called "preinit" or something, as it initializes
402 // critical parts of the scene graph in addition to the splash screen.
403 void
404 FGRenderer::splashinit( void ) {
405     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
406     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
407     mRealRoot->addChild(fgCreateSplashNode());
408     mFrameStamp = viewer->getFrameStamp();
409     // Scene doesn't seem to pass the frame stamp to the update
410     // visitor automatically.
411     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
412     viewer->setUpdateVisitor(mUpdateVisitor.get());
413 }
414
415 void
416 FGRenderer::init( void )
417 {
418     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
419     osg::initNotifyLevel();
420
421     // The number of polygon-offset "units" to place between layers.  In
422     // principle, one is supposed to be enough.  In practice, I find that
423     // my hardware/driver requires many more.
424     osg::PolygonOffset::setUnitsMultiplier(1);
425     osg::PolygonOffset::setFactorMultiplier(1);
426
427     // Go full screen if requested ...
428     if ( fgGetBool("/sim/startup/fullscreen") )
429         fgOSFullScreen();
430
431     viewer->getCamera()
432         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
433     
434     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
435
436     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
437     
438     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
439     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
440
441     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
442     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
443     stateSet->setAttribute(new osg::BlendFunc);
444     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
445
446     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
447     
448     // this will be set below
449     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
450
451     osg::Material* material = new osg::Material;
452     stateSet->setAttribute(material);
453     
454     stateSet->setTextureAttribute(0, new osg::TexEnv);
455     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
456
457     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
458     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
459     stateSet->setAttribute(hint);
460     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
461     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
462     stateSet->setAttribute(hint);
463     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
464     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
465     stateSet->setAttribute(hint);
466     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
467     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
468     stateSet->setAttribute(hint);
469     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
470     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
471     stateSet->setAttribute(hint);
472
473     osg::Group* sceneGroup = new osg::Group;
474     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
475     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
476
477     //sceneGroup->addChild(thesky->getCloudRoot());
478
479     stateSet = sceneGroup->getOrCreateStateSet();
480     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
481
482     // need to update the light on every frame
483     // OSG LightSource objects are rather confusing. OSG only supports
484     // the 10 lights specified by OpenGL itself; if more than one
485     // LightSource in the scene graph have the same light number, it's
486     // indeterminate which values will be used to render geometry that
487     // has that light number enabled. Also, adding children to a
488     // LightSource is just a shortcut for setting up a state set that
489     // has the corresponding OpenGL light enabled: a LightSource will
490     // affect geometry anywhere in the scene graph that has its light
491     // number enabled in a state set. 
492     LightSource* lightSource = new LightSource;
493     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
494     // relative because of CameraView being just a clever transform node
495     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
496     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
497     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
498     mRealRoot->addChild(lightSource);
499     // we need a white diffuse light for the phase of the moon
500     osg::LightSource* sunLight = new osg::LightSource;
501     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
502     sunLight->getLight()->setLightNum(1);
503     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
504     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
505     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
506     // Hang a StateSet above the sky subgraph in order to turn off
507     // light 0
508     Group* skyGroup = new Group;
509     StateSet* skySS = skyGroup->getOrCreateStateSet();
510     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
511     skyGroup->addChild(thesky->getPreRoot());
512     sunLight->addChild(skyGroup);
513     mRoot->addChild(sceneGroup);
514     mRoot->addChild(sunLight);
515     // Clouds are added to the scene graph later
516     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
517     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
518     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
519     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
520
521     // enable disable specular highlights.
522     // is the place where we might plug in an other fragment shader ...
523     osg::LightModel* lightModel = new osg::LightModel;
524     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
525     stateSet->setAttribute(lightModel);
526
527     // switch to enable wireframe
528     osg::PolygonMode* polygonMode = new osg::PolygonMode;
529     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
530     stateSet->setAttributeAndModes(polygonMode);
531
532     // scene fog handling
533     osg::Fog* fog = new osg::Fog;
534     fog->setUpdateCallback(new FGFogUpdateCallback);
535     stateSet->setAttributeAndModes(fog);
536     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
537
538     // plug in the GUI
539     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
540     if (guiCamera) {
541         osg::Geode* geode = new osg::Geode;
542         geode->addDrawable(new SGPuDrawable);
543         geode->addDrawable(new SGHUDAndPanelDrawable);
544         guiCamera->addChild(geode);
545     }
546     osg::Switch* sw = new osg::Switch;
547     sw->setUpdateCallback(new FGScenerySwitchCallback);
548     sw->addChild(mRoot.get());
549     mRealRoot->addChild(sw);
550     // The clouds are attached directly to the scene graph root
551     // because, in theory, they don't want the same default state set
552     // as the rest of the scene. This may not be true in practice.
553     mRealRoot->addChild(thesky->getCloudRoot());
554     mRealRoot->addChild(FGCreateRedoutNode());
555 }
556
557
558 // Update all Visuals (redraws anything graphics related)
559 void
560 FGRenderer::update( bool refresh_camera_settings ) {
561     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
562                           || fgGetBool("sim/sceneryloaded-override");
563     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
564     if ( idle_state < 1000 || !scenery_loaded ) {
565         fgSetDouble("/sim/startup/splash-alpha", 1.0);
566
567         // Keep resetting sim time while the sim is initializing
568         // the splash screen is now in the scenegraph
569         globals->set_sim_time_sec( 0.0 );
570         return;
571     }
572
573     // Fade out the splash screen over the first three seconds.
574     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
575     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
576
577     bool skyblend = fgGetBool("/sim/rendering/skyblend");
578     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
579     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
580     bool distance_attenuation
581         = fgGetBool("/sim/rendering/distance-attenuation");
582     // OSGFIXME
583     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
584                                   distance_attenuation );
585
586     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
587
588     // update fog params
589     double actual_visibility;
590     if (fgGetBool("/environment/clouds/status")) {
591         actual_visibility = thesky->get_visibility();
592     } else {
593         actual_visibility = fgGetDouble("/environment/visibility-m");
594     }
595
596     // idle_state is now 1000 meaning we've finished all our
597     // initializations and are running the main loop, so this will
598     // now work without seg faulting the system.
599
600     FGViewer *current__view = globals->get_current_view();
601     // Force update of center dependent values ...
602     current__view->set_dirty();
603
604     if ( refresh_camera_settings ) {
605         // update view port
606         resize( fgGetInt("/sim/startup/xsize"),
607                 fgGetInt("/sim/startup/ysize") );
608     }
609     osg::Camera *camera = viewer->getCamera();
610
611     if ( skyblend ) {
612         
613         if ( fgGetBool("/sim/rendering/textures") ) {
614             SGVec4f clearColor(l->adj_fog_color());
615             camera->setClearColor(toOsg(clearColor));
616         }
617     } else {
618         SGVec4f clearColor(l->sky_color());
619         camera->setClearColor(toOsg(clearColor));
620     }
621
622     // update fog params if visibility has changed
623     double visibility_meters = fgGetDouble("/environment/visibility-m");
624     thesky->set_visibility(visibility_meters);
625
626     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
627                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
628                         / (double)fgGetInt("/sim/model-hz") );
629
630     // update the sky dome
631     if ( skyblend ) {
632
633         // The sun and moon distances are scaled down versions
634         // of the actual distance to get both the moon and the sun
635         // within the range of the far clip plane.
636         // Moon distance:    384,467 kilometers
637         // Sun distance: 150,000,000 kilometers
638
639         double sun_horiz_eff, moon_horiz_eff;
640         if (fgGetBool("/sim/rendering/horizon-effect")) {
641             sun_horiz_eff
642                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
643                                              0.0),
644                              0.33) / 3.0;
645             moon_horiz_eff
646                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
647                                              0.0),
648                              0.33)/3.0;
649         } else {
650            sun_horiz_eff = moon_horiz_eff = 1.0;
651         }
652
653         SGSkyState sstate;
654         sstate.pos       = current__view->getViewPosition();
655         sstate.pos_geod  = current__view->getPosition();
656         sstate.ori       = current__view->getViewOrientation();
657         sstate.spin      = l->get_sun_rotation();
658         sstate.gst       = globals->get_time_params()->getGst();
659         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
660         sstate.moon_dist = 40000.0 * moon_horiz_eff;
661         sstate.sun_angle = l->get_sun_angle();
662
663         SGSkyColor scolor;
664         scolor.sky_color   = SGVec3f(l->sky_color().data());
665         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
666         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
667         scolor.cloud_color = SGVec3f(l->cloud_color().data());
668         scolor.sun_angle   = l->get_sun_angle();
669         scolor.moon_angle  = l->get_moon_angle();
670
671         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
672         thesky->repaint( scolor, *globals->get_ephem() );
673
674         /*
675         SG_LOG( SG_GENERAL, SG_BULK,
676                 "thesky->reposition( view_pos = " << view_pos[0] << " "
677          << view_pos[1] << " " << view_pos[2] );
678         SG_LOG( SG_GENERAL, SG_BULK,
679                 "    zero_elev = " << zero_elev[0] << " "
680          << zero_elev[1] << " " << zero_elev[2]
681          << " lon = " << cur_fdm_state->get_Longitude()
682          << " lat = " << cur_fdm_state->get_Latitude() );
683         SG_LOG( SG_GENERAL, SG_BULK,
684                 "    sun_rot = " << l->get_sun_rotation
685          << " gst = " << SGTime::cur_time_params->getGst() );
686         SG_LOG( SG_GENERAL, SG_BULK,
687              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
688           << " sun dec = " << globals->get_ephem()->getSunDeclination()
689           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
690           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
691         */
692
693         //OSGFIXME
694 //         shadows->setupShadows(
695 //           current__view->getLongitude_deg(),
696 //           current__view->getLatitude_deg(),
697 //           globals->get_time_params()->getGst(),
698 //           globals->get_ephem()->getSunRightAscension(),
699 //           globals->get_ephem()->getSunDeclination(),
700 //           l->get_sun_angle());
701
702     }
703
704 //     sgEnviro.setLight(l->adj_fog_color());
705 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
706 //         current__view->get_world_up(),
707 //         current__view->getLongitude_deg(),
708 //         current__view->getLatitude_deg(),
709 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
710 //         delta_time_sec);
711
712     // OSGFIXME
713 //     sgEnviro.drawLightning();
714
715 //        double current_view_origin_airspeed_horiz_kt =
716 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
717 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
718 //                                * SGD_DEGREES_TO_RADIANS);
719
720     // OSGFIXME
721 //     if( is_internal )
722 //         shadows->endOfFrame();
723
724     // need to call the update visitor once
725     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
726     mUpdateVisitor->setViewData(current__view->getViewPosition(),
727                                 current__view->getViewOrientation());
728     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
729     mUpdateVisitor->setLight(direction, l->scene_ambient(),
730                              l->scene_diffuse(), l->scene_specular(),
731                              l->adj_fog_color(),
732                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
733     mUpdateVisitor->setVisibility(actual_visibility);
734     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
735     bool hotspots = fgGetBool("/sim/panel-hotspots");
736     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
737     cullMask |= simgear::GroundLightManager::instance()
738         ->getLightNodeMask(mUpdateVisitor.get());
739     if (hotspots)
740         cullMask |= simgear::PICK_BIT;
741     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
742 }
743
744
745
746 // options.cxx needs to see this for toggle_panel()
747 // Handle new window size or exposure
748 void
749 FGRenderer::resize( int width, int height ) {
750     int view_h;
751
752     if ( (!fgGetBool("/sim/virtual-cockpit"))
753          && fgPanelVisible() && idle_state == 1000 ) {
754         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
755                              globals->get_current_panel()->getYOffset()) / 768.0);
756     } else {
757         view_h = height;
758     }
759
760     static int lastwidth = 0;
761     static int lastheight = 0;
762     if (width != lastwidth)
763         fgSetInt("/sim/startup/xsize", lastwidth = width);
764     if (height != lastheight)
765         fgSetInt("/sim/startup/ysize", lastheight = height);
766
767     // for all views
768     FGViewMgr *viewmgr = globals->get_viewmgr();
769     if (viewmgr) {
770       for ( int i = 0; i < viewmgr->size(); ++i ) {
771         viewmgr->get_view(i)->
772           set_aspect_ratio((float)view_h / (float)width);
773       }
774     }
775 }
776
777 bool
778 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
779                  const osgGA::GUIEventAdapter* ea)
780 {
781     // wipe out the return ...
782     pickList.clear();
783     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
784     Intersections intersections;
785
786     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
787         return false;
788     for (Intersections::iterator hit = intersections.begin(),
789              e = intersections.end();
790          hit != e;
791          ++hit) {
792         const osg::NodePath& np = hit->nodePath;
793         osg::NodePath::const_reverse_iterator npi;
794         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
795             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
796             if (!ud)
797                 continue;
798             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
799                 SGPickCallback* pickCallback = ud->getPickCallback(i);
800                 if (!pickCallback)
801                     continue;
802                 SGSceneryPick sceneryPick;
803                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
804                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
805                 sceneryPick.callback = pickCallback;
806                 pickList.push_back(sceneryPick);
807             }
808         }
809     }
810     return !pickList.empty();
811 }
812
813 void
814 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
815 {
816     viewer = viewer_;
817 }
818
819 void
820 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
821 {
822     eventHandler = eventHandler_;
823 }
824
825 void
826 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
827 {
828     mRealRoot->addChild(camera);
829 }
830
831 bool
832 fgDumpSceneGraphToFile(const char* filename)
833 {
834     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
835 }
836
837 bool
838 fgDumpTerrainBranchToFile(const char* filename)
839 {
840     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
841                                  filename );
842 }
843
844 // For debugging
845 bool
846 fgDumpNodeToFile(osg::Node* node, const char* filename)
847 {
848     return osgDB::writeNodeFile(*node, filename);
849 }
850 // end of renderer.cxx
851