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