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