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