]> 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 center = globals->get_scenery()->get_center();
637         SGVec3d position = current__view->getViewPosition();
638         SGQuatd attitude = current__view->getViewOrientation();
639         SGVec3d osgPosition = attitude.transform(center - position);
640         mCameraView->setPosition(osgPosition.osg());
641         mCameraView->setAttitude(inverse(attitude).osg());
642     }
643
644     if ( skyblend ) {
645         if ( fgGetBool("/sim/rendering/textures") ) {
646             SGVec4f clearColor(l->adj_fog_color());
647             sceneView->getCamera()->setClearColor(clearColor.osg());
648         }
649     } else {
650         SGVec4f clearColor(l->sky_color());
651         sceneView->getCamera()->setClearColor(clearColor.osg());
652     }
653
654     // update fog params if visibility has changed
655     double visibility_meters = fgGetDouble("/environment/visibility-m");
656     thesky->set_visibility(visibility_meters);
657
658     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
659                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
660                         / (double)fgGetInt("/sim/model-hz") );
661
662     // update the sky dome
663     if ( skyblend ) {
664
665         // The sun and moon distances are scaled down versions
666         // of the actual distance to get both the moon and the sun
667         // within the range of the far clip plane.
668         // Moon distance:    384,467 kilometers
669         // Sun distance: 150,000,000 kilometers
670
671         double sun_horiz_eff, moon_horiz_eff;
672         if (fgGetBool("/sim/rendering/horizon-effect")) {
673            sun_horiz_eff = 0.67+pow(0.5+cos(l->get_sun_angle())*2/2, 0.33)/3;
674            moon_horiz_eff = 0.67+pow(0.5+cos(l->get_moon_angle())*2/2, 0.33)/3;
675         } else {
676            sun_horiz_eff = moon_horiz_eff = 1.0;
677         }
678
679         static SGSkyState sstate;
680
681         sstate.view_pos  = current__view->get_view_pos();
682         sstate.zero_elev = current__view->get_zero_elev();
683         sstate.view_up   = current__view->get_world_up();
684         sstate.lon       = current__view->getLongitude_deg()
685                             * SGD_DEGREES_TO_RADIANS;
686         sstate.lat       = current__view->getLatitude_deg()
687                             * SGD_DEGREES_TO_RADIANS;
688         sstate.alt       = current__view->getAltitudeASL_ft()
689                             * SG_FEET_TO_METER;
690         sstate.spin      = l->get_sun_rotation();
691         sstate.gst       = globals->get_time_params()->getGst();
692         sstate.sun_ra    = globals->get_ephem()->getSunRightAscension();
693         sstate.sun_dec   = globals->get_ephem()->getSunDeclination();
694         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
695         sstate.moon_ra   = globals->get_ephem()->getMoonRightAscension();
696         sstate.moon_dec  = globals->get_ephem()->getMoonDeclination();
697         sstate.moon_dist = 40000.0 * moon_horiz_eff;
698         sstate.sun_angle = l->get_sun_angle();
699
700
701         /*
702          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
703          << l->sky_color()[0] << " "
704          << l->sky_color()[1] << " "
705          << l->sky_color()[2] << " "
706          << l->sky_color()[3] );
707         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
708          << l->fog_color()[0] << " "
709          << l->fog_color()[1] << " "
710          << l->fog_color()[2] << " "
711          << l->fog_color()[3] );
712         SG_LOG( SG_GENERAL, SG_BULK,
713                 "    sun_angle = " << l->sun_angle
714          << "    moon_angle = " << l->moon_angle );
715         */
716
717         static SGSkyColor scolor;
718
719         scolor.sky_color   = SGVec3f(l->sky_color().data());
720         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
721         scolor.cloud_color = SGVec3f(l->cloud_color().data());
722         scolor.sun_angle   = l->get_sun_angle();
723         scolor.moon_angle  = l->get_moon_angle();
724         scolor.nplanets    = globals->get_ephem()->getNumPlanets();
725         scolor.nstars      = globals->get_ephem()->getNumStars();
726         scolor.planet_data = globals->get_ephem()->getPlanets();
727         scolor.star_data   = globals->get_ephem()->getStars();
728
729         thesky->reposition( sstate, delta_time_sec );
730         thesky->repaint( scolor );
731
732         /*
733         SG_LOG( SG_GENERAL, SG_BULK,
734                 "thesky->reposition( view_pos = " << view_pos[0] << " "
735          << view_pos[1] << " " << view_pos[2] );
736         SG_LOG( SG_GENERAL, SG_BULK,
737                 "    zero_elev = " << zero_elev[0] << " "
738          << zero_elev[1] << " " << zero_elev[2]
739          << " lon = " << cur_fdm_state->get_Longitude()
740          << " lat = " << cur_fdm_state->get_Latitude() );
741         SG_LOG( SG_GENERAL, SG_BULK,
742                 "    sun_rot = " << l->get_sun_rotation
743          << " gst = " << SGTime::cur_time_params->getGst() );
744         SG_LOG( SG_GENERAL, SG_BULK,
745              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
746           << " sun dec = " << globals->get_ephem()->getSunDeclination()
747           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
748           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
749         */
750
751         //OSGFIXME
752 //         shadows->setupShadows(
753 //           current__view->getLongitude_deg(),
754 //           current__view->getLatitude_deg(),
755 //           globals->get_time_params()->getGst(),
756 //           globals->get_ephem()->getSunRightAscension(),
757 //           globals->get_ephem()->getSunDeclination(),
758 //           l->get_sun_angle());
759
760     }
761
762     if ( strcmp(fgGetString("/sim/rendering/fog"), "disabled") ) {
763         SGVec4f color(l->adj_fog_color());
764         mFog->setColor(color.osg());
765         mRunwayLightingFog->setColor(color.osg());
766         mTaxiLightingFog->setColor(color.osg());
767         mGroundLightingFog->setColor(color.osg());
768     }
769
770
771 //     sgEnviro.setLight(l->adj_fog_color());
772
773     // texture parameters
774     glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
775
776     double agl = current__view->getAltitudeASL_ft()*SG_FEET_TO_METER
777       - current__view->getSGLocation()->get_cur_elev_m();
778
779     float scene_nearplane, scene_farplane;
780     if ( agl > 10.0 ) {
781         scene_nearplane = 10.0f;
782         scene_farplane = 120000.0f;
783     } else {
784         scene_nearplane = groundlevel_nearplane->getDoubleValue();
785         scene_farplane = 120000.0f;
786     }
787     setNearFar( scene_nearplane, scene_farplane );
788
789 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
790 //         current__view->get_world_up(),
791 //         current__view->getLongitude_deg(),
792 //         current__view->getLatitude_deg(),
793 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
794 //         delta_time_sec);
795
796     // OSGFIXME
797 //     sgEnviro.drawLightning();
798
799 //        double current_view_origin_airspeed_horiz_kt =
800 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
801 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
802 //                                * SGD_DEGREES_TO_RADIANS);
803        // TODO:find the real view speed, not the AC one
804 //     sgEnviro.drawPrecipitation(
805 //         fgGetDouble("/environment/metar/rain-norm", 0.0),
806 //         fgGetDouble("/environment/metar/snow-norm", 0.0),
807 //         fgGetDouble("/environment/metar/hail-norm", 0.0),
808 //         current__view->getPitch_deg() + current__view->getPitchOffset_deg(),
809 //         current__view->getRoll_deg() + current__view->getRollOffset_deg(),
810 //         - current__view->getHeadingOffset_deg(),
811 //                current_view_origin_airspeed_horiz_kt
812 //                );
813
814     // OSGFIXME
815 //     if( is_internal )
816 //         shadows->endOfFrame();
817
818     // need to call the update visitor once
819     globals->get_aircraft_model()->select( true );
820     FGTileMgr::set_tile_filter( true );
821     mFrameStamp->setReferenceTime(globals->get_sim_time_sec());
822     mFrameStamp->setFrameNumber(1+mFrameStamp->getFrameNumber());
823     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
824     mUpdateVisitor->setViewData(current__view->getViewPosition(),
825                                 current__view->getViewOrientation());
826     mUpdateVisitor->setSceneryCenter(globals->get_scenery()->get_center());
827     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
828     mUpdateVisitor->setLight(direction, l->scene_ambient(),
829                              l->scene_diffuse(), l->scene_specular());
830     mUpdateVisitor->setVisibility(actual_visibility);
831
832     if (fgGetBool("/sim/panel-hotspots"))
833       sceneView->setCullMask(sceneView->getCullMask()|SG_NODEMASK_PICK_BIT);
834     else
835       sceneView->setCullMask(sceneView->getCullMask()&(~SG_NODEMASK_PICK_BIT));
836
837     sceneView->update();
838     sceneView->cull();
839     sceneView->draw();
840 }
841
842
843
844 // options.cxx needs to see this for toggle_panel()
845 // Handle new window size or exposure
846 void
847 FGRenderer::resize( int width, int height ) {
848     int view_h;
849
850     if ( (!fgGetBool("/sim/virtual-cockpit"))
851          && fgPanelVisible() && idle_state == 1000 ) {
852         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
853                              globals->get_current_panel()->getYOffset()) / 768.0);
854     } else {
855         view_h = height;
856     }
857
858     sceneView->getViewport()->setViewport(0, height - view_h, width, view_h);
859
860     static int lastwidth = 0;
861     static int lastheight = 0;
862     if (width != lastwidth)
863         fgSetInt("/sim/startup/xsize", lastwidth = width);
864     if (height != lastheight)
865         fgSetInt("/sim/startup/ysize", lastheight = height);
866
867     guiInitMouse(width, height);
868
869     // for all views
870     FGViewMgr *viewmgr = globals->get_viewmgr();
871     if (viewmgr) {
872       for ( int i = 0; i < viewmgr->size(); ++i ) {
873         viewmgr->get_view(i)->
874           set_aspect_ratio((float)view_h / (float)width);
875       }
876
877       setFOV( viewmgr->get_current_view()->get_h_fov(),
878               viewmgr->get_current_view()->get_v_fov() );
879     }
880 }
881
882
883 // These are wrapper functions around ssgSetNearFar() and ssgSetFOV()
884 // which will post process and rewrite the resulting frustum if we
885 // want to do asymmetric view frustums.
886
887 static void fgHackFrustum() {
888
889     // specify a percent of the configured view frustum to actually
890     // display.  This is a bit of a hack to achieve asymmetric view
891     // frustums.  For instance, if you want to display two monitors
892     // side by side, you could specify each with a double fov, a 0.5
893     // aspect ratio multiplier, and then the left side monitor would
894     // have a left_pct = 0.0, a right_pct = 0.5, a bottom_pct = 0.0,
895     // and a top_pct = 1.0.  The right side monitor would have a
896     // left_pct = 0.5 and a right_pct = 1.0.
897
898     static SGPropertyNode *left_pct
899         = fgGetNode("/sim/current-view/frustum-left-pct");
900     static SGPropertyNode *right_pct
901         = fgGetNode("/sim/current-view/frustum-right-pct");
902     static SGPropertyNode *bottom_pct
903         = fgGetNode("/sim/current-view/frustum-bottom-pct");
904     static SGPropertyNode *top_pct
905         = fgGetNode("/sim/current-view/frustum-top-pct");
906
907     double left, right;
908     double bottom, top;
909     double zNear, zFar;
910     sceneView->getProjectionMatrixAsFrustum(left, right, bottom, top, zNear, zFar);
911     // cout << " l = " << f->getLeft()
912     //      << " r = " << f->getRight()
913     //      << " b = " << f->getBot()
914     //      << " t = " << f->getTop()
915     //      << " n = " << f->getNear()
916     //      << " f = " << f->getFar()
917     //      << endl;
918
919     double width = right - left;
920     double height = top - bottom;
921
922     double l, r, t, b;
923
924     if ( left_pct != NULL ) {
925         l = left + width * left_pct->getDoubleValue();
926     } else {
927         l = left;
928     }
929
930     if ( right_pct != NULL ) {
931         r = left + width * right_pct->getDoubleValue();
932     } else {
933         r = right;
934     }
935
936     if ( bottom_pct != NULL ) {
937         b = bottom + height * bottom_pct->getDoubleValue();
938     } else {
939         b = bottom;
940     }
941
942     if ( top_pct != NULL ) {
943         t = bottom + height * top_pct->getDoubleValue();
944     } else {
945         t = top;
946     }
947
948     sceneView->setProjectionMatrixAsFrustum(l, r, b, t, zNear, zFar);
949 }
950
951
952 // we need some static storage space for these values.  However, we
953 // can't store it in a renderer class object because the functions
954 // that manipulate these are static.  They are static so they can
955 // interface to the display callback system.  There's probably a
956 // better way, there has to be a better way, but I'm not seeing it
957 // right now.
958 static float fov_width = 55.0;
959 static float fov_height = 42.0;
960 static float fov_near = 1.0;
961 static float fov_far = 1000.0;
962
963
964 /** FlightGear code should use this routine to set the FOV rather than
965  *  calling the ssg routine directly
966  */
967 void FGRenderer::setFOV( float w, float h ) {
968     fov_width = w;
969     fov_height = h;
970
971     sceneView->setProjectionMatrixAsPerspective(fov_height,
972                                                 fov_width/fov_height,
973                                                 fov_near, fov_far);
974     // fully specify the view frustum before hacking it (so we don't
975     // accumulate hacked effects
976     fgHackFrustum();
977 //     sgEnviro.setFOV( w, h );
978 }
979
980
981 /** FlightGear code should use this routine to set the Near/Far clip
982  *  planes rather than calling the ssg routine directly
983  */
984 void FGRenderer::setNearFar( float n, float f ) {
985 // OSGFIXME: we have currently too much z-buffer fights
986 n = 0.1;
987     fov_near = n;
988     fov_far = f;
989
990     sceneView->setProjectionMatrixAsPerspective(fov_height,
991                                                 fov_width/fov_height,
992                                                 fov_near, fov_far);
993
994     // fully specify the view frustum before hacking it (so we don't
995     // accumulate hacked effects
996     fgHackFrustum();
997 }
998
999 bool
1000 FGRenderer::pick( unsigned x, unsigned y,
1001                   std::vector<SGSceneryPick>& pickList )
1002 {
1003   // wipe out the return ...
1004   pickList.resize(0);
1005
1006   // we can get called early ...
1007   if (!sceneView.valid())
1008     return false;
1009
1010   osg::Node* sceneData = globals->get_scenery()->get_scene_graph();
1011   if (!sceneData)
1012     return false;
1013   osg::Viewport* viewport = sceneView->getViewport();
1014   if (!viewport)
1015     return false;
1016
1017   // good old scenery center
1018   SGVec3d center = globals->get_scenery()->get_center();
1019
1020   // don't know why, but the update has partly happened somehow,
1021   // so update the scenery part of the viewer
1022   FGViewer *current_view = globals->get_current_view();
1023   // Force update of center dependent values ...
1024   current_view->set_dirty();
1025   SGVec3d position = current_view->getViewPosition();
1026   SGQuatd attitude = current_view->getViewOrientation();
1027   SGVec3d osgPosition = attitude.transform(center - position);
1028   mCameraView->setPosition(osgPosition.osg());
1029   mCameraView->setAttitude(inverse(attitude).osg());
1030
1031   osg::Matrix projection(sceneView->getProjectionMatrix());
1032   osg::Matrix modelview(sceneView->getViewMatrix());
1033
1034   osg::NodePathList nodePath = sceneData->getParentalNodePaths();
1035   // modify the view matrix so that it accounts for this nodePath's
1036   // accumulated transform
1037   if (!nodePath.empty())
1038     modelview.preMult(computeLocalToWorld(nodePath.front()));
1039
1040   // swap the y values ...
1041   y = viewport->height() - y;
1042   // set up the pick visitor
1043   osgUtil::PickVisitor pickVisitor(viewport, projection, modelview, x, y);
1044   sceneData->accept(pickVisitor);
1045   if (!pickVisitor.hits())
1046     return false;
1047
1048   // collect all interaction callbacks on the pick ray.
1049   // They get stored in the pickCallbacks list where they are sorted back
1050   // to front and croasest to finest wrt the scenery node they are attached to
1051   osgUtil::PickVisitor::LineSegmentHitListMap::const_iterator mi;
1052   for (mi = pickVisitor.getSegHitList().begin();
1053        mi != pickVisitor.getSegHitList().end();
1054        ++mi) {
1055     osgUtil::IntersectVisitor::HitList::const_iterator hi;
1056     for (hi = mi->second.begin(); hi != mi->second.end(); ++hi) {
1057       // ok, go back the nodes and ask for intersection callbacks,
1058       // execute them in top down order
1059       const osg::NodePath& np = hi->getNodePath();
1060       osg::NodePath::const_reverse_iterator npi;
1061       for (npi = np.rbegin(); npi != np.rend(); ++npi) {
1062         SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
1063         if (!ud)
1064           continue;
1065         for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
1066           SGPickCallback* pickCallback = ud->getPickCallback(i);
1067           if (!pickCallback)
1068             continue;
1069           SGSceneryPick sceneryPick;
1070           /// note that this is done totally in doubles instead of
1071           /// just using getWorldIntersectionPoint
1072           osg::Vec3d localPt = hi->getLocalIntersectPoint();
1073           sceneryPick.info.local = SGVec3d(localPt);
1074           if (hi->getMatrix())
1075             sceneryPick.info.wgs84 = SGVec3d(localPt*(*hi->getMatrix()));
1076           else
1077             sceneryPick.info.wgs84 = SGVec3d(localPt);
1078           sceneryPick.info.wgs84 += globals->get_scenery()->get_center();
1079           sceneryPick.callback = pickCallback;
1080           pickList.push_back(sceneryPick);
1081         }
1082       }
1083     }
1084   }
1085
1086   return !pickList.empty();
1087 }
1088
1089 // end of renderer.cxx
1090