]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Merge branch 'next' of gitorious.org:fg/flightgear 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 <algorithm>
33 #include <iostream>
34 #include <map>
35 #include <vector>
36 #include <typeinfo>
37
38 #include <osg/ref_ptr>
39 #include <osg/AlphaFunc>
40 #include <osg/BlendFunc>
41 #include <osg/Camera>
42 #include <osg/CullFace>
43 #include <osg/CullStack>
44 #include <osg/Depth>
45 #include <osg/Fog>
46 #include <osg/Group>
47 #include <osg/Hint>
48 #include <osg/Light>
49 #include <osg/LightModel>
50 #include <osg/LightSource>
51 #include <osg/Material>
52 #include <osg/Math>
53 #include <osg/NodeCallback>
54 #include <osg/Notify>
55 #include <osg/PolygonMode>
56 #include <osg/PolygonOffset>
57 #include <osg/Program>
58 #include <osg/Version>
59 #include <osg/TexEnv>
60
61 #include <osgUtil/LineSegmentIntersector>
62
63 #include <osg/io_utils>
64 #include <osgDB/WriteFile>
65
66 #include <simgear/math/SGMath.hxx>
67 #include <simgear/scene/material/matlib.hxx>
68 #include <simgear/scene/model/animation.hxx>
69 #include <simgear/scene/model/placement.hxx>
70 #include <simgear/scene/sky/sky.hxx>
71 #include <simgear/scene/util/SGUpdateVisitor.hxx>
72 #include <simgear/scene/util/RenderConstants.hxx>
73 #include <simgear/scene/util/SGSceneUserData.hxx>
74 #include <simgear/scene/tgdb/GroundLightManager.hxx>
75 #include <simgear/scene/tgdb/pt_lights.hxx>
76 #include <simgear/structure/OSGUtils.hxx>
77 #include <simgear/props/props.hxx>
78 #include <simgear/timing/sg_time.hxx>
79 #include <simgear/ephemeris/ephemeris.hxx>
80 #include <simgear/math/sg_random.h>
81 #ifdef FG_JPEG_SERVER
82 #include <simgear/screen/jpgfactory.hxx>
83 #endif
84
85 #include <Time/light.hxx>
86 #include <Time/light.hxx>
87 #include <Cockpit/panel.hxx>
88 #include <Model/panelnode.hxx>
89 #include <Model/modelmgr.hxx>
90 #include <Model/acmodel.hxx>
91 #include <Scenery/scenery.hxx>
92 #include <Scenery/redout.hxx>
93 #include <GUI/new_gui.hxx>
94 #include <Instrumentation/HUD/HUD.hxx>
95 #include <Environment/precipitation_mgr.hxx>
96
97 #include "splash.hxx"
98 #include "renderer.hxx"
99 #include "main.hxx"
100 #include "CameraGroup.hxx"
101 #include "FGEventHandler.hxx"
102 #include <Main/viewer.hxx>
103 #include <Main/viewmgr.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   SGPropertyNode_ptr 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     setDataVariance(Object::DYNAMIC);
142
143     osg::StateSet* stateSet = getOrCreateStateSet();
144     stateSet->setRenderBinDetails(1001, "RenderBin");
145     // speed optimization?
146     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
147     // We can do translucent menus, so why not. :-)
148     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
149     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
150     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
151
152     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
153
154     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
155     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
156   }
157   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
158   { drawImplementation(*renderInfo.getState()); }
159   void drawImplementation(osg::State& state) const
160   {
161     state.setActiveTextureUnit(0);
162     state.setClientActiveTextureUnit(0);
163
164     state.disableAllVertexArrays();
165
166     glPushAttrib(GL_ALL_ATTRIB_BITS);
167     glPushClientAttrib(~0u);
168
169     puDisplay();
170
171     glPopClientAttrib();
172     glPopAttrib();
173   }
174
175   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
176   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
177   
178 private:
179 };
180
181 class SGHUDAndPanelDrawable : public osg::Drawable {
182 public:
183   SGHUDAndPanelDrawable()
184   {
185     // Dynamic stuff, do not store geometry
186     setUseDisplayList(false);
187     setDataVariance(Object::DYNAMIC);
188
189     osg::StateSet* stateSet = getOrCreateStateSet();
190     stateSet->setRenderBinDetails(1000, "RenderBin");
191
192     // speed optimization?
193     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
194     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
195     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
196     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
197     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
198
199     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
200   }
201   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
202   { drawImplementation(*renderInfo.getState()); }
203   void drawImplementation(osg::State& state) const
204   {
205     state.setActiveTextureUnit(0);
206     state.setClientActiveTextureUnit(0);
207     state.disableAllVertexArrays();
208
209     glPushAttrib(GL_ALL_ATTRIB_BITS);
210     glPushClientAttrib(~0u);
211
212     HUD *hud = static_cast<HUD*>(globals->get_subsystem("hud"));
213     hud->draw(state);
214
215     // update the panel subsystem
216     if ( globals->get_current_panel() != NULL )
217         globals->get_current_panel()->update(state);
218     // We don't need a state here - can be safely removed when we can pick
219     // correctly
220     fgUpdate3DPanels();
221
222     glPopClientAttrib();
223     glPopAttrib();
224
225   }
226
227   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
228   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
229   
230 private:
231 };
232
233 class FGLightSourceUpdateCallback : public osg::NodeCallback {
234 public:
235   
236   /**
237    * @param isSun true if the light is the actual sun i.e., for
238    * illuminating the moon.
239    */
240   FGLightSourceUpdateCallback(bool isSun = false) : _isSun(isSun) {}
241   FGLightSourceUpdateCallback(const FGLightSourceUpdateCallback& nc,
242                               const CopyOp& op)
243     : NodeCallback(nc, op), _isSun(nc._isSun)
244   {}
245   META_Object(flightgear,FGLightSourceUpdateCallback);
246   
247   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
248   {
249     assert(dynamic_cast<osg::LightSource*>(node));
250     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
251     osg::Light* light = lightSource->getLight();
252     
253     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
254     if (_isSun) {
255       light->setAmbient(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
256       light->setDiffuse(Vec4(1.0f, 1.0f, 1.0f, 1.0f));
257       light->setSpecular(Vec4(0.0f, 0.0f, 0.0f, 0.0f));
258     } else {
259       light->setAmbient(toOsg(l->scene_ambient()));
260       light->setDiffuse(toOsg(l->scene_diffuse()));
261       light->setSpecular(toOsg(l->scene_specular()));
262     }
263     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
264     light->setPosition(position);
265
266     traverse(node, nv);
267   }
268 private:
269   const bool _isSun;
270 };
271
272 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
273 public:
274   FGWireFrameModeUpdateCallback() :
275     mWireframe(fgGetNode("/sim/rendering/wireframe", true))
276   { }
277   virtual void operator()(osg::StateAttribute* stateAttribute,
278                           osg::NodeVisitor*)
279   {
280     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
281     osg::PolygonMode* polygonMode;
282     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
283
284     if (mWireframe->getBoolValue())
285       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
286                            osg::PolygonMode::LINE);
287     else
288       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
289                            osg::PolygonMode::FILL);
290   }
291 private:
292   SGPropertyNode_ptr mWireframe;
293 };
294
295 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
296 public:
297   FGLightModelUpdateCallback() :
298     mHighlights(fgGetNode("/sim/rendering/specular-highlight", true))
299   { }
300   virtual void operator()(osg::StateAttribute* stateAttribute,
301                           osg::NodeVisitor*)
302   {
303     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
304     osg::LightModel* lightModel;
305     lightModel = static_cast<osg::LightModel*>(stateAttribute);
306
307 #if 0
308     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
309     lightModel->setAmbientIntensity(toOsg(l->scene_ambient());
310 #else
311     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
312 #endif
313     lightModel->setTwoSided(true);
314     lightModel->setLocalViewer(false);
315
316     if (mHighlights->getBoolValue()) {
317       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
318     } else {
319       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
320     }
321   }
322 private:
323   SGPropertyNode_ptr mHighlights;
324 };
325
326 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
327 public:
328   FGFogEnableUpdateCallback() :
329     mFogEnabled(fgGetNode("/sim/rendering/fog", true))
330   { }
331   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
332   {
333     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
334       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
335     } else {
336       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
337     }
338   }
339 private:
340   SGPropertyNode_ptr mFogEnabled;
341 };
342
343 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
344 public:
345   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
346   {
347     assert(dynamic_cast<SGUpdateVisitor*>(nv));
348     assert(dynamic_cast<osg::Fog*>(sa));
349     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
350     osg::Fog* fog = static_cast<osg::Fog*>(sa);
351     fog->setMode(osg::Fog::EXP2);
352     fog->setColor(toOsg(updateVisitor->getFogColor()));
353     fog->setDensity(updateVisitor->getFogExp2Density());
354   }
355 };
356
357 // update callback for the switch node guarding that splash
358 class FGScenerySwitchCallback : public osg::NodeCallback {
359 public:
360   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
361   {
362     assert(dynamic_cast<osg::Switch*>(node));
363     osg::Switch* sw = static_cast<osg::Switch*>(node);
364
365     bool enabled = scenery_enabled;
366     sw->setValue(0, enabled);
367     if (!enabled)
368       return;
369     traverse(node, nv);
370   }
371
372   static bool scenery_enabled;
373 };
374
375 bool FGScenerySwitchCallback::scenery_enabled = false;
376
377 // Sky structures
378 SGSky *thesky;
379
380 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
381 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
382
383 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
384
385 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
386
387 FGRenderer::FGRenderer()
388 {
389 #ifdef FG_JPEG_SERVER
390    jpgRenderFrame = FGRenderer::update;
391 #endif
392    eventHandler = new FGEventHandler;
393    _splash_screen_active = true;
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     fgSetDouble("/sim/startup/splash-alpha", 1.0);
417 }
418
419 void
420 FGRenderer::init( void )
421 {
422     _scenery_loaded   = fgGetNode("/sim/sceneryloaded", true);
423     _scenery_override = fgGetNode("/sim/sceneryloaded-override", true);
424     _panel_hotspots   = fgGetNode("/sim/panel-hotspots", true);
425     _virtual_cockpit  = fgGetNode("/sim/virtual-cockpit", true);
426
427     _sim_delta_sec = fgGetNode("/sim/time/delta-sec", true);
428
429     _xsize         = fgGetNode("/sim/startup/xsize", true);
430     _ysize         = fgGetNode("/sim/startup/ysize", true);
431
432     _skyblend             = fgGetNode("/sim/rendering/skyblend", true);
433     _point_sprites        = fgGetNode("/sim/rendering/point-sprites", true);
434     _enhanced_lighting    = fgGetNode("/sim/rendering/enhanced-lighting", true);
435     _distance_attenuation = fgGetNode("/sim/rendering/distance-attenuation", true);
436     _horizon_effect       = fgGetNode("/sim/rendering/horizon-effect", true);
437     _textures             = fgGetNode("/sim/rendering/textures", true);
438
439     _altitude_ft = fgGetNode("/position/altitude-ft", true);
440
441     _cloud_status = fgGetNode("/environment/clouds/status", true);
442     _visibility_m = fgGetNode("/environment/visibility-m", true);
443
444     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
445     osg::initNotifyLevel();
446
447     // The number of polygon-offset "units" to place between layers.  In
448     // principle, one is supposed to be enough.  In practice, I find that
449     // my hardware/driver requires many more.
450     osg::PolygonOffset::setUnitsMultiplier(1);
451     osg::PolygonOffset::setFactorMultiplier(1);
452
453     // Go full screen if requested ...
454     if ( fgGetBool("/sim/startup/fullscreen") )
455         fgOSFullScreen();
456
457     viewer->getCamera()
458         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
459     
460     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
461
462     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
463     
464     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
465     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
466
467     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
468     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
469     stateSet->setAttribute(new osg::BlendFunc);
470     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
471
472     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
473     
474     // this will be set below
475     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
476
477     osg::Material* material = new osg::Material;
478     stateSet->setAttribute(material);
479     
480     stateSet->setTextureAttribute(0, new osg::TexEnv);
481     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
482
483     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
484     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
485     stateSet->setAttribute(hint);
486     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
487     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
488     stateSet->setAttribute(hint);
489     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
490     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
491     stateSet->setAttribute(hint);
492     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
493     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
494     stateSet->setAttribute(hint);
495     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
496     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
497     stateSet->setAttribute(hint);
498
499     osg::Group* sceneGroup = new osg::Group;
500     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
501     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
502
503     //sceneGroup->addChild(thesky->getCloudRoot());
504
505     stateSet = sceneGroup->getOrCreateStateSet();
506     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
507
508     // need to update the light on every frame
509     // OSG LightSource objects are rather confusing. OSG only supports
510     // the 10 lights specified by OpenGL itself; if more than one
511     // LightSource in the scene graph have the same light number, it's
512     // indeterminate which values will be used to render geometry that
513     // has that light number enabled. Also, adding children to a
514     // LightSource is just a shortcut for setting up a state set that
515     // has the corresponding OpenGL light enabled: a LightSource will
516     // affect geometry anywhere in the scene graph that has its light
517     // number enabled in a state set. 
518     LightSource* lightSource = new LightSource;
519     lightSource->getLight()->setDataVariance(Object::DYNAMIC);
520     // relative because of CameraView being just a clever transform node
521     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
522     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
523     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
524     mRealRoot->addChild(lightSource);
525     // we need a white diffuse light for the phase of the moon
526     osg::LightSource* sunLight = new osg::LightSource;
527     sunLight->getLight()->setDataVariance(Object::DYNAMIC);
528     sunLight->getLight()->setLightNum(1);
529     sunLight->setUpdateCallback(new FGLightSourceUpdateCallback(true));
530     sunLight->setReferenceFrame(osg::LightSource::RELATIVE_RF);
531     sunLight->setLocalStateSetModes(osg::StateAttribute::ON);
532     // Hang a StateSet above the sky subgraph in order to turn off
533     // light 0
534     Group* skyGroup = new Group;
535     StateSet* skySS = skyGroup->getOrCreateStateSet();
536     skySS->setMode(GL_LIGHT0, StateAttribute::OFF);
537     skyGroup->addChild(thesky->getPreRoot());
538     sunLight->addChild(skyGroup);
539     mRoot->addChild(sceneGroup);
540     mRoot->addChild(sunLight);
541     // Clouds are added to the scene graph later
542     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
543     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
544     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
545     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
546
547     // enable disable specular highlights.
548     // is the place where we might plug in an other fragment shader ...
549     osg::LightModel* lightModel = new osg::LightModel;
550     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
551     stateSet->setAttribute(lightModel);
552
553     // switch to enable wireframe
554     osg::PolygonMode* polygonMode = new osg::PolygonMode;
555     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
556     stateSet->setAttributeAndModes(polygonMode);
557
558     // scene fog handling
559     osg::Fog* fog = new osg::Fog;
560     fog->setUpdateCallback(new FGFogUpdateCallback);
561     stateSet->setAttributeAndModes(fog);
562     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
563
564     // plug in the GUI
565     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
566     if (guiCamera) {
567         osg::Geode* geode = new osg::Geode;
568         geode->addDrawable(new SGPuDrawable);
569         geode->addDrawable(new SGHUDAndPanelDrawable);
570         guiCamera->addChild(geode);
571     }
572     osg::Switch* sw = new osg::Switch;
573     sw->setUpdateCallback(new FGScenerySwitchCallback);
574     sw->addChild(mRoot.get());
575     mRealRoot->addChild(sw);
576     // The clouds are attached directly to the scene graph root
577     // because, in theory, they don't want the same default state set
578     // as the rest of the scene. This may not be true in practice.
579     mRealRoot->addChild(thesky->getCloudRoot());
580     mRealRoot->addChild(FGCreateRedoutNode());
581     // Attach empty program to the scene root so that shader programs
582     // don't leak into state sets (effects) that shouldn't have one.
583     stateSet = mRealRoot->getOrCreateStateSet();
584     stateSet->setAttributeAndModes(new osg::Program, osg::StateAttribute::ON);
585 }
586
587 void
588 FGRenderer::update()
589 {
590     globals->get_renderer()->update(true);
591 }
592
593 // Update all Visuals (redraws anything graphics related)
594 void
595 FGRenderer::update( bool refresh_camera_settings ) {
596     if ((!_scenery_loaded.get())||
597          !(_scenery_loaded->getBoolValue() || 
598            _scenery_override->getBoolValue()))
599     {
600         // alas, first "update" is being called before "init"...
601         fgSetDouble("/sim/startup/splash-alpha", 1.0);
602         _splash_screen_active = true;
603         return;
604     }
605     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
606
607     if (_splash_screen_active)
608     {
609         // Fade out the splash screen
610         const double fade_time = 0.8;
611         const double fade_steps_per_sec = 20;
612         double delay_time = SGMiscd::min(fade_time/fade_steps_per_sec,
613                                          (SGTimeStamp::now() - _splash_time).toSecs());
614         _splash_time = SGTimeStamp::now();
615         double sAlpha = fgGetDouble("/sim/startup/splash-alpha", 1.0);
616         sAlpha -= SGMiscd::max(0.0,delay_time/fade_time);
617         FGScenerySwitchCallback::scenery_enabled = (sAlpha<1.0);
618         _splash_screen_active = (sAlpha > 0.0);
619         fgSetDouble("/sim/startup/splash-alpha", sAlpha);
620     }
621
622     bool skyblend = _skyblend->getBoolValue();
623     bool use_point_sprites = _point_sprites->getBoolValue();
624     bool enhanced_lighting = _enhanced_lighting->getBoolValue();
625     bool distance_attenuation = _distance_attenuation->getBoolValue();
626
627     // OSGFIXME
628     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
629                                   distance_attenuation );
630
631     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
632
633     // update fog params
634     double actual_visibility;
635     if (_cloud_status->getBoolValue()) {
636         actual_visibility = thesky->get_visibility();
637     } else {
638         actual_visibility = _visibility_m->getDoubleValue();
639     }
640
641     // idle_state is now 1000 meaning we've finished all our
642     // initializations and are running the main loop, so this will
643     // now work without seg faulting the system.
644
645     FGViewer *current__view = globals->get_current_view();
646     // Force update of center dependent values ...
647     current__view->set_dirty();
648
649     if ( refresh_camera_settings ) {
650         // update view port
651         resize( _xsize->getIntValue(),
652                 _ysize->getIntValue() );
653     }
654     osg::Camera *camera = viewer->getCamera();
655
656     if ( skyblend ) {
657         
658         if ( _textures->getBoolValue() ) {
659             SGVec4f clearColor(l->adj_fog_color());
660             camera->setClearColor(toOsg(clearColor));
661         }
662     } else {
663         SGVec4f clearColor(l->sky_color());
664         camera->setClearColor(toOsg(clearColor));
665     }
666
667     // update fog params if visibility has changed
668     double visibility_meters = _visibility_m->getDoubleValue();
669     thesky->set_visibility(visibility_meters);
670
671     double altitude_m = _altitude_ft->getDoubleValue() * SG_FEET_TO_METER;
672     thesky->modify_vis( altitude_m, 0.0 /* time factor, now unused */);
673
674     // update the sky dome
675     if ( skyblend ) {
676
677         // The sun and moon distances are scaled down versions
678         // of the actual distance to get both the moon and the sun
679         // within the range of the far clip plane.
680         // Moon distance:    384,467 kilometers
681         // Sun distance: 150,000,000 kilometers
682
683         double sun_horiz_eff, moon_horiz_eff;
684         if (_horizon_effect->getBoolValue()) {
685             sun_horiz_eff
686                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
687                                              0.0),
688                              0.33) / 3.0;
689             moon_horiz_eff
690                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
691                                              0.0),
692                              0.33)/3.0;
693         } else {
694            sun_horiz_eff = moon_horiz_eff = 1.0;
695         }
696
697         SGSkyState sstate;
698         sstate.pos       = current__view->getViewPosition();
699         sstate.pos_geod  = current__view->getPosition();
700         sstate.ori       = current__view->getViewOrientation();
701         sstate.spin      = l->get_sun_rotation();
702         sstate.gst       = globals->get_time_params()->getGst();
703         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
704         sstate.moon_dist = 40000.0 * moon_horiz_eff;
705         sstate.sun_angle = l->get_sun_angle();
706
707         SGSkyColor scolor;
708         scolor.sky_color   = SGVec3f(l->sky_color().data());
709         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
710         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
711         scolor.cloud_color = SGVec3f(l->cloud_color().data());
712         scolor.sun_angle   = l->get_sun_angle();
713         scolor.moon_angle  = l->get_moon_angle();
714   
715         double delta_time_sec = _sim_delta_sec->getDoubleValue();
716         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
717         thesky->repaint( scolor, *globals->get_ephem() );
718
719             //OSGFIXME
720 //         shadows->setupShadows(
721 //           current__view->getLongitude_deg(),
722 //           current__view->getLatitude_deg(),
723 //           globals->get_time_params()->getGst(),
724 //           globals->get_ephem()->getSunRightAscension(),
725 //           globals->get_ephem()->getSunDeclination(),
726 //           l->get_sun_angle());
727
728     }
729
730 //     sgEnviro.setLight(l->adj_fog_color());
731 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
732 //         current__view->get_world_up(),
733 //         current__view->getLongitude_deg(),
734 //         current__view->getLatitude_deg(),
735 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
736 //         delta_time_sec);
737
738     // OSGFIXME
739 //     sgEnviro.drawLightning();
740
741 //        double current_view_origin_airspeed_horiz_kt =
742 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
743 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
744 //                                * SGD_DEGREES_TO_RADIANS);
745
746     // OSGFIXME
747 //     if( is_internal )
748 //         shadows->endOfFrame();
749
750     // need to call the update visitor once
751     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
752     mUpdateVisitor->setViewData(current__view->getViewPosition(),
753                                 current__view->getViewOrientation());
754     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
755     mUpdateVisitor->setLight(direction, l->scene_ambient(),
756                              l->scene_diffuse(), l->scene_specular(),
757                              l->adj_fog_color(),
758                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
759     mUpdateVisitor->setVisibility(actual_visibility);
760     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
761     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
762     cullMask |= simgear::GroundLightManager::instance()
763         ->getLightNodeMask(mUpdateVisitor.get());
764     if (_panel_hotspots->getBoolValue())
765         cullMask |= simgear::PICK_BIT;
766     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
767 }
768
769
770
771 // options.cxx needs to see this for toggle_panel()
772 // Handle new window size or exposure
773 void
774 FGRenderer::resize( int width, int height ) {
775     int view_h;
776
777     if ( (!_virtual_cockpit->getBoolValue())
778          && fgPanelVisible() && idle_state == 1000 ) {
779         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
780                              globals->get_current_panel()->getYOffset()) / 768.0);
781     } else {
782         view_h = height;
783     }
784
785     static int lastwidth = 0;
786     static int lastheight = 0;
787     if (width != lastwidth)
788         _xsize->setIntValue(lastwidth = width);
789     if (height != lastheight)
790         _ysize->setIntValue(lastheight = height);
791
792     // for all views
793     FGViewMgr *viewmgr = globals->get_viewmgr();
794     if (viewmgr) {
795       for ( int i = 0; i < viewmgr->size(); ++i ) {
796         viewmgr->get_view(i)->
797           set_aspect_ratio((float)view_h / (float)width);
798       }
799     }
800 }
801
802 bool
803 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
804                  const osgGA::GUIEventAdapter* ea)
805 {
806     // wipe out the return ...
807     pickList.clear();
808     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
809     Intersections intersections;
810
811     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
812         return false;
813     for (Intersections::iterator hit = intersections.begin(),
814              e = intersections.end();
815          hit != e;
816          ++hit) {
817         const osg::NodePath& np = hit->nodePath;
818         osg::NodePath::const_reverse_iterator npi;
819         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
820             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
821             if (!ud)
822                 continue;
823             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
824                 SGPickCallback* pickCallback = ud->getPickCallback(i);
825                 if (!pickCallback)
826                     continue;
827                 SGSceneryPick sceneryPick;
828                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
829                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
830                 sceneryPick.callback = pickCallback;
831                 pickList.push_back(sceneryPick);
832             }
833         }
834     }
835     return !pickList.empty();
836 }
837
838 void
839 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
840 {
841     viewer = viewer_;
842 }
843
844 void
845 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
846 {
847     eventHandler = eventHandler_;
848 }
849
850 void
851 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
852 {
853     mRealRoot->addChild(camera);
854 }
855
856 bool
857 fgDumpSceneGraphToFile(const char* filename)
858 {
859     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
860 }
861
862 bool
863 fgDumpTerrainBranchToFile(const char* filename)
864 {
865     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
866                                  filename );
867 }
868
869 // For debugging
870 bool
871 fgDumpNodeToFile(osg::Node* node, const char* filename)
872 {
873     return osgDB::writeNodeFile(*node, filename);
874 }
875
876 namespace flightgear
877 {
878 using namespace osg;
879
880 class VisibleSceneInfoVistor : public NodeVisitor, CullStack
881 {
882 public:
883     VisibleSceneInfoVistor()
884         : NodeVisitor(CULL_VISITOR, TRAVERSE_ACTIVE_CHILDREN)
885     {
886         setCullingMode(CullSettings::SMALL_FEATURE_CULLING
887                        | CullSettings::VIEW_FRUSTUM_CULLING);
888         setComputeNearFarMode(CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
889     }
890
891     VisibleSceneInfoVistor(const VisibleSceneInfoVistor& rhs)
892     {
893     }
894
895     META_NodeVisitor("flightgear","VisibleSceneInfoVistor")
896
897     typedef std::map<const std::string,int> InfoMap;
898
899     void getNodeInfo(Node* node)
900     {
901         const char* typeName = typeid(*node).name();
902         classInfo[typeName]++;
903         const std::string& nodeName = node->getName();
904         if (!nodeName.empty())
905             nodeInfo[nodeName]++;
906     }
907
908     void dumpInfo()
909     {
910         using namespace std;
911         typedef vector<InfoMap::iterator> FreqVector;
912         cout << "class info:\n";
913         FreqVector classes;
914         for (InfoMap::iterator itr = classInfo.begin(), end = classInfo.end();
915              itr != end;
916              ++itr)
917             classes.push_back(itr);
918         sort(classes.begin(), classes.end(), freqComp);
919         for (FreqVector::iterator itr = classes.begin(), end = classes.end();
920              itr != end;
921              ++itr) {
922             cout << (*itr)->first << " " << (*itr)->second << "\n";
923         }
924         cout << "\nnode info:\n";
925         FreqVector nodes;
926         for (InfoMap::iterator itr = nodeInfo.begin(), end = nodeInfo.end();
927              itr != end;
928              ++itr)
929             nodes.push_back(itr);
930
931         sort (nodes.begin(), nodes.end(), freqComp);
932         for (FreqVector::iterator itr = nodes.begin(), end = nodes.end();
933              itr != end;
934              ++itr) {
935             cout << (*itr)->first << " " << (*itr)->second << "\n";
936         }
937         cout << endl;
938     }
939     
940     void doTraversal(Camera* camera, Node* root, Viewport* viewport)
941     {
942         ref_ptr<RefMatrix> projection
943             = createOrReuseMatrix(camera->getProjectionMatrix());
944         ref_ptr<RefMatrix> mv = createOrReuseMatrix(camera->getViewMatrix());
945         if (!viewport)
946             viewport = camera->getViewport();
947         if (viewport)
948             pushViewport(viewport);
949         pushProjectionMatrix(projection.get());
950         pushModelViewMatrix(mv.get(), Transform::ABSOLUTE_RF);
951         root->accept(*this);
952         popModelViewMatrix();
953         popProjectionMatrix();
954         if (viewport)
955             popViewport();
956         dumpInfo();
957     }
958
959     void apply(Node& node)
960     {
961         if (isCulled(node))
962             return;
963         pushCurrentMask();
964         getNodeInfo(&node);
965         traverse(node);
966         popCurrentMask();
967     }
968     void apply(Group& node)
969     {
970         if (isCulled(node))
971             return;
972         pushCurrentMask();
973         getNodeInfo(&node);
974         traverse(node);
975         popCurrentMask();
976     }
977
978     void apply(Transform& node)
979     {
980         if (isCulled(node))
981             return;
982         pushCurrentMask();
983         ref_ptr<RefMatrix> matrix = createOrReuseMatrix(*getModelViewMatrix());
984         node.computeLocalToWorldMatrix(*matrix,this);
985         pushModelViewMatrix(matrix.get(), node.getReferenceFrame());
986         getNodeInfo(&node);
987         traverse(node);
988         popModelViewMatrix();
989         popCurrentMask();
990     }
991
992     void apply(Camera& camera)
993     {
994         // Save current cull settings
995         CullSettings saved_cull_settings(*this);
996
997         // set cull settings from this Camera
998         setCullSettings(camera);
999         // inherit the settings from above
1000         inheritCullSettings(saved_cull_settings, camera.getInheritanceMask());
1001
1002         // set the cull mask.
1003         unsigned int savedTraversalMask = getTraversalMask();
1004         bool mustSetCullMask = (camera.getInheritanceMask()
1005                                 & osg::CullSettings::CULL_MASK) == 0;
1006         if (mustSetCullMask)
1007             setTraversalMask(camera.getCullMask());
1008
1009         osg::RefMatrix* projection = 0;
1010         osg::RefMatrix* modelview = 0;
1011
1012         if (camera.getReferenceFrame()==osg::Transform::RELATIVE_RF) {
1013             if (camera.getTransformOrder()==osg::Camera::POST_MULTIPLY) {
1014                 projection = createOrReuseMatrix(*getProjectionMatrix()
1015                                                  *camera.getProjectionMatrix());
1016                 modelview = createOrReuseMatrix(*getModelViewMatrix()
1017                                                 * camera.getViewMatrix());
1018             }
1019             else {              // pre multiply 
1020                 projection = createOrReuseMatrix(camera.getProjectionMatrix()
1021                                                  * (*getProjectionMatrix()));
1022                 modelview = createOrReuseMatrix(camera.getViewMatrix()
1023                                                 * (*getModelViewMatrix()));
1024             }
1025         } else {
1026             // an absolute reference frame
1027             projection = createOrReuseMatrix(camera.getProjectionMatrix());
1028             modelview = createOrReuseMatrix(camera.getViewMatrix());
1029         }
1030         if (camera.getViewport())
1031             pushViewport(camera.getViewport());
1032
1033         pushProjectionMatrix(projection);
1034         pushModelViewMatrix(modelview, camera.getReferenceFrame());    
1035
1036         traverse(camera);
1037     
1038         // restore the previous model view matrix.
1039         popModelViewMatrix();
1040
1041         // restore the previous model view matrix.
1042         popProjectionMatrix();
1043
1044         if (camera.getViewport()) popViewport();
1045
1046         // restore the previous traversal mask settings
1047         if (mustSetCullMask)
1048             setTraversalMask(savedTraversalMask);
1049
1050         // restore the previous cull settings
1051         setCullSettings(saved_cull_settings);
1052     }
1053
1054 protected:
1055     // sort in reverse
1056     static bool freqComp(const InfoMap::iterator& lhs, const InfoMap::iterator& rhs)
1057     {
1058         return lhs->second > rhs->second;
1059     }
1060     InfoMap classInfo;
1061     InfoMap nodeInfo;
1062 };
1063
1064 bool printVisibleSceneInfo(FGRenderer* renderer)
1065 {
1066     osgViewer::Viewer* viewer = renderer->getViewer();
1067     VisibleSceneInfoVistor vsv;
1068     Viewport* vp = 0;
1069     if (!viewer->getCamera()->getViewport() && viewer->getNumSlaves() > 0) {
1070         const View::Slave& slave = viewer->getSlave(0);
1071         vp = slave._camera->getViewport();
1072     }
1073     vsv.doTraversal(viewer->getCamera(), viewer->getSceneData(), vp);
1074     return true;
1075 }
1076 }
1077 // end of renderer.cxx
1078