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