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