]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Fix to LaRCsim interpolation code
[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 #ifdef HAVE_CONFIG_H
23 #  include <config.h>
24 #endif
25
26 #ifdef HAVE_WINDOWS_H
27 #  include <windows.h>
28 #endif
29
30 #include <simgear/compiler.h>
31
32 #include <osg/ref_ptr>
33 #include <osg/AlphaFunc>
34 #include <osg/BlendFunc>
35 #include <osg/Camera>
36 #include <osg/CullFace>
37 #include <osg/Depth>
38 #include <osg/Fog>
39 #include <osg/Group>
40 #include <osg/Hint>
41 #include <osg/Light>
42 #include <osg/LightModel>
43 #include <osg/LightSource>
44 #include <osg/Material>
45 #include <osg/Math>
46 #include <osg/NodeCallback>
47 #include <osg/Notify>
48 #include <osg/PolygonMode>
49 #include <osg/PolygonOffset>
50 #include <osg/Version>
51 #include <osg/TexEnv>
52
53 #include <osgUtil/LineSegmentIntersector>
54
55 #include <osg/io_utils>
56 #include <osgDB/WriteFile>
57
58 #include <simgear/math/SGMath.hxx>
59 #include <simgear/screen/extensions.hxx>
60 #include <simgear/scene/material/matlib.hxx>
61 #include <simgear/scene/model/animation.hxx>
62 #include <simgear/scene/model/placement.hxx>
63 #include <simgear/scene/sky/sky.hxx>
64 #include <simgear/scene/util/SGUpdateVisitor.hxx>
65 #include <simgear/scene/util/RenderConstants.hxx>
66 #include <simgear/scene/util/SGSceneUserData.hxx>
67 #include <simgear/scene/tgdb/GroundLightManager.hxx>
68 #include <simgear/scene/tgdb/pt_lights.hxx>
69 #include <simgear/props/props.hxx>
70 #include <simgear/timing/sg_time.hxx>
71 #include <simgear/ephemeris/ephemeris.hxx>
72 #include <simgear/math/sg_random.h>
73 #ifdef FG_JPEG_SERVER
74 #include <simgear/screen/jpgfactory.hxx>
75 #endif
76
77 #include <simgear/environment/visual_enviro.hxx>
78
79 #include <Time/light.hxx>
80 #include <Time/light.hxx>
81 #include <Aircraft/aircraft.hxx>
82 #include <Cockpit/panel.hxx>
83 #include <Cockpit/cockpit.hxx>
84 #include <Cockpit/hud.hxx>
85 #include <Model/panelnode.hxx>
86 #include <Model/modelmgr.hxx>
87 #include <Model/acmodel.hxx>
88 #include <Scenery/scenery.hxx>
89 #include <Scenery/redout.hxx>
90 #include <Scenery/tilemgr.hxx>
91 #include <GUI/new_gui.hxx>
92 #include <Instrumentation/instrument_mgr.hxx>
93 #include <Instrumentation/HUD/HUD.hxx>
94 #include <Environment/precipitation_mgr.hxx>
95
96 #include <Include/general.hxx>
97 #include "splash.hxx"
98 #include "renderer.hxx"
99 #include "main.hxx"
100 #include "CameraGroup.hxx"
101 #include "FGEventHandler.hxx"
102
103 using namespace osg;
104 using namespace simgear;
105 using namespace flightgear;
106
107 class FGHintUpdateCallback : public osg::StateAttribute::Callback {
108 public:
109   FGHintUpdateCallback(const char* configNode) :
110     mConfigNode(fgGetNode(configNode, true))
111   { }
112   virtual void operator()(osg::StateAttribute* stateAttribute,
113                           osg::NodeVisitor*)
114   {
115     assert(dynamic_cast<osg::Hint*>(stateAttribute));
116     osg::Hint* hint = static_cast<osg::Hint*>(stateAttribute);
117
118     const char* value = mConfigNode->getStringValue();
119     if (!value)
120       hint->setMode(GL_DONT_CARE);
121     else if (0 == strcmp(value, "nicest"))
122       hint->setMode(GL_NICEST);
123     else if (0 == strcmp(value, "fastest"))
124       hint->setMode(GL_FASTEST);
125     else
126       hint->setMode(GL_DONT_CARE);
127   }
128 private:
129   SGSharedPtr<SGPropertyNode> mConfigNode;
130 };
131
132
133 class SGPuDrawable : public osg::Drawable {
134 public:
135   SGPuDrawable()
136   {
137     // Dynamic stuff, do not store geometry
138     setUseDisplayList(false);
139
140     osg::StateSet* stateSet = getOrCreateStateSet();
141     stateSet->setRenderBinDetails(1001, "RenderBin");
142     // speed optimization?
143     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
144     // We can do translucent menus, so why not. :-)
145     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
146     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
147     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
148
149     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
150
151     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
152     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
153   }
154   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
155   { drawImplementation(*renderInfo.getState()); }
156   void drawImplementation(osg::State& state) const
157   {
158     state.setActiveTextureUnit(0);
159     state.setClientActiveTextureUnit(0);
160
161     state.disableAllVertexArrays();
162
163     glPushAttrib(GL_ALL_ATTRIB_BITS);
164     glPushClientAttrib(~0u);
165
166     puDisplay();
167
168     glPopClientAttrib();
169     glPopAttrib();
170   }
171
172   virtual osg::Object* cloneType() const { return new SGPuDrawable; }
173   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGPuDrawable; }
174   
175 private:
176 };
177
178 class SGHUDAndPanelDrawable : public osg::Drawable {
179 public:
180   SGHUDAndPanelDrawable()
181   {
182     // Dynamic stuff, do not store geometry
183     setUseDisplayList(false);
184
185     osg::StateSet* stateSet = getOrCreateStateSet();
186     stateSet->setRenderBinDetails(1000, "RenderBin");
187
188     // speed optimization?
189     stateSet->setMode(GL_CULL_FACE, osg::StateAttribute::OFF);
190     stateSet->setAttribute(new osg::BlendFunc(osg::BlendFunc::SRC_ALPHA, osg::BlendFunc::ONE_MINUS_SRC_ALPHA));
191     stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
192     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
193     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
194
195     stateSet->setTextureAttribute(0, new osg::TexEnv(osg::TexEnv::MODULATE));
196   }
197   virtual void drawImplementation(osg::RenderInfo& renderInfo) const
198   { drawImplementation(*renderInfo.getState()); }
199   void drawImplementation(osg::State& state) const
200   {
201     state.setActiveTextureUnit(0);
202     state.setClientActiveTextureUnit(0);
203     state.disableAllVertexArrays();
204
205     glPushAttrib(GL_ALL_ATTRIB_BITS);
206     glPushClientAttrib(~0u);
207
208     fgCockpitUpdate(&state);
209
210     FGInstrumentMgr *instr = static_cast<FGInstrumentMgr*>(globals->get_subsystem("instrumentation"));
211     HUD *hud = static_cast<HUD*>(instr->get_subsystem("hud"));
212     hud->draw(state);
213
214     // update the panel subsystem
215     if ( globals->get_current_panel() != NULL )
216         globals->get_current_panel()->update(state);
217     // We don't need a state here - can be safely removed when we can pick
218     // correctly
219     fgUpdate3DPanels();
220
221     glPopClientAttrib();
222     glPopAttrib();
223
224   }
225
226   virtual osg::Object* cloneType() const { return new SGHUDAndPanelDrawable; }
227   virtual osg::Object* clone(const osg::CopyOp&) const { return new SGHUDAndPanelDrawable; }
228   
229 private:
230 };
231
232 class FGLightSourceUpdateCallback : public osg::NodeCallback {
233 public:
234   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
235   {
236     assert(dynamic_cast<osg::LightSource*>(node));
237     osg::LightSource* lightSource = static_cast<osg::LightSource*>(node);
238     osg::Light* light = lightSource->getLight();
239     
240     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
241     light->setAmbient(l->scene_ambient().osg());
242     light->setDiffuse(l->scene_diffuse().osg());
243     light->setSpecular(l->scene_specular().osg());
244     SGVec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
245     light->setPosition(position.osg());
246     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
247     light->setDirection(direction.osg());
248     light->setSpotExponent(0);
249     light->setSpotCutoff(180);
250     light->setConstantAttenuation(1);
251     light->setLinearAttenuation(0);
252     light->setQuadraticAttenuation(0);
253
254     traverse(node, nv);
255   }
256 };
257
258 class FGWireFrameModeUpdateCallback : public osg::StateAttribute::Callback {
259 public:
260   FGWireFrameModeUpdateCallback() :
261     mWireframe(fgGetNode("/sim/rendering/wireframe"))
262   { }
263   virtual void operator()(osg::StateAttribute* stateAttribute,
264                           osg::NodeVisitor*)
265   {
266     assert(dynamic_cast<osg::PolygonMode*>(stateAttribute));
267     osg::PolygonMode* polygonMode;
268     polygonMode = static_cast<osg::PolygonMode*>(stateAttribute);
269
270     if (mWireframe->getBoolValue())
271       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
272                            osg::PolygonMode::LINE);
273     else
274       polygonMode->setMode(osg::PolygonMode::FRONT_AND_BACK,
275                            osg::PolygonMode::FILL);
276   }
277 private:
278   SGSharedPtr<SGPropertyNode> mWireframe;
279 };
280
281 class FGLightModelUpdateCallback : public osg::StateAttribute::Callback {
282 public:
283   FGLightModelUpdateCallback() :
284     mHighlights(fgGetNode("/sim/rendering/specular-highlight"))
285   { }
286   virtual void operator()(osg::StateAttribute* stateAttribute,
287                           osg::NodeVisitor*)
288   {
289     assert(dynamic_cast<osg::LightModel*>(stateAttribute));
290     osg::LightModel* lightModel;
291     lightModel = static_cast<osg::LightModel*>(stateAttribute);
292
293 #if 0
294     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
295     lightModel->setAmbientIntensity(l->scene_ambient().osg());
296 #else
297     lightModel->setAmbientIntensity(osg::Vec4(0, 0, 0, 1));
298 #endif
299     lightModel->setTwoSided(true);
300     lightModel->setLocalViewer(false);
301
302     if (mHighlights->getBoolValue()) {
303       lightModel->setColorControl(osg::LightModel::SEPARATE_SPECULAR_COLOR);
304     } else {
305       lightModel->setColorControl(osg::LightModel::SINGLE_COLOR);
306     }
307   }
308 private:
309   SGSharedPtr<SGPropertyNode> mHighlights;
310 };
311
312 class FGFogEnableUpdateCallback : public osg::StateSet::Callback {
313 public:
314   FGFogEnableUpdateCallback() :
315     mFogEnabled(fgGetNode("/sim/rendering/fog"))
316   { }
317   virtual void operator()(osg::StateSet* stateSet, osg::NodeVisitor*)
318   {
319     if (strcmp(mFogEnabled->getStringValue(), "disabled") == 0) {
320       stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
321     } else {
322       stateSet->setMode(GL_FOG, osg::StateAttribute::ON);
323     }
324   }
325 private:
326   SGSharedPtr<SGPropertyNode> mFogEnabled;
327 };
328
329 class FGFogUpdateCallback : public osg::StateAttribute::Callback {
330 public:
331   virtual void operator () (osg::StateAttribute* sa, osg::NodeVisitor* nv)
332   {
333     assert(dynamic_cast<SGUpdateVisitor*>(nv));
334     assert(dynamic_cast<osg::Fog*>(sa));
335     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
336     osg::Fog* fog = static_cast<osg::Fog*>(sa);
337     fog->setMode(osg::Fog::EXP2);
338     fog->setColor(updateVisitor->getFogColor().osg());
339     fog->setDensity(updateVisitor->getFogExp2Density());
340   }
341 };
342
343 // update callback for the switch node guarding that splash
344 class FGScenerySwitchCallback : public osg::NodeCallback {
345 public:
346   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
347   {
348     assert(dynamic_cast<osg::Switch*>(node));
349     osg::Switch* sw = static_cast<osg::Switch*>(node);
350
351     double t = globals->get_sim_time_sec();
352     bool enabled = 0 < t;
353     sw->setValue(0, enabled);
354     if (!enabled)
355       return;
356     traverse(node, nv);
357   }
358 };
359
360 // Sky structures
361 SGSky *thesky;
362
363 static osg::ref_ptr<osg::FrameStamp> mFrameStamp = new osg::FrameStamp;
364 static osg::ref_ptr<SGUpdateVisitor> mUpdateVisitor= new SGUpdateVisitor;
365
366 static osg::ref_ptr<osg::Group> mRealRoot = new osg::Group;
367
368 static osg::ref_ptr<osg::Group> mRoot = new osg::Group;
369
370 FGRenderer::FGRenderer()
371 {
372 #ifdef FG_JPEG_SERVER
373    jpgRenderFrame = FGRenderer::update;
374 #endif
375    eventHandler = new FGEventHandler;
376 }
377
378 FGRenderer::~FGRenderer()
379 {
380 #ifdef FG_JPEG_SERVER
381    jpgRenderFrame = NULL;
382 #endif
383 }
384
385 // Initialize various GL/view parameters
386 // XXX This should be called "preinit" or something, as it initializes
387 // critical parts of the scene graph in addition to the splash screen.
388 void
389 FGRenderer::splashinit( void ) {
390     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
391     mRealRoot = dynamic_cast<osg::Group*>(viewer->getSceneData());
392     mRealRoot->addChild(fgCreateSplashNode());
393     mFrameStamp = viewer->getFrameStamp();
394     // Scene doesn't seem to pass the frame stamp to the update
395     // visitor automatically.
396     mUpdateVisitor->setFrameStamp(mFrameStamp.get());
397     viewer->setUpdateVisitor(mUpdateVisitor.get());
398 }
399
400 void
401 FGRenderer::init( void )
402 {
403     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
404     osg::initNotifyLevel();
405
406     // The number of polygon-offset "units" to place between layers.  In
407     // principle, one is supposed to be enough.  In practice, I find that
408     // my hardware/driver requires many more.
409     osg::PolygonOffset::setUnitsMultiplier(1);
410     osg::PolygonOffset::setFactorMultiplier(1);
411
412     // Go full screen if requested ...
413     if ( fgGetBool("/sim/startup/fullscreen") )
414         fgOSFullScreen();
415
416     viewer->getCamera()
417         ->setComputeNearFarMode(osg::CullSettings::DO_NOT_COMPUTE_NEAR_FAR);
418     
419     osg::StateSet* stateSet = mRoot->getOrCreateStateSet();
420
421     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
422     
423     stateSet->setAttribute(new osg::Depth(osg::Depth::LESS));
424     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::OFF);
425
426     stateSet->setAttribute(new osg::AlphaFunc(osg::AlphaFunc::GREATER, 0.01));
427     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::OFF);
428     stateSet->setAttribute(new osg::BlendFunc);
429     stateSet->setMode(GL_BLEND, osg::StateAttribute::OFF);
430
431     stateSet->setMode(GL_FOG, osg::StateAttribute::OFF);
432     
433     // this will be set below
434     stateSet->setMode(GL_NORMALIZE, osg::StateAttribute::OFF);
435
436     osg::Material* material = new osg::Material;
437     stateSet->setAttribute(material);
438     
439     stateSet->setTextureAttribute(0, new osg::TexEnv);
440     stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::OFF);
441
442     osg::Hint* hint = new osg::Hint(GL_FOG_HINT, GL_DONT_CARE);
443     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/fog"));
444     stateSet->setAttribute(hint);
445     hint = new osg::Hint(GL_POLYGON_SMOOTH_HINT, GL_DONT_CARE);
446     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/polygon-smooth"));
447     stateSet->setAttribute(hint);
448     hint = new osg::Hint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
449     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/line-smooth"));
450     stateSet->setAttribute(hint);
451     hint = new osg::Hint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
452     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/point-smooth"));
453     stateSet->setAttribute(hint);
454     hint = new osg::Hint(GL_PERSPECTIVE_CORRECTION_HINT, GL_DONT_CARE);
455     hint->setUpdateCallback(new FGHintUpdateCallback("/sim/rendering/perspective-correction"));
456     stateSet->setAttribute(hint);
457
458     osg::Group* sceneGroup = new osg::Group;
459     sceneGroup->addChild(globals->get_scenery()->get_scene_graph());
460     sceneGroup->setNodeMask(~simgear::BACKGROUND_BIT);
461
462     //sceneGroup->addChild(thesky->getCloudRoot());
463
464     stateSet = sceneGroup->getOrCreateStateSet();
465     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
466
467     // need to update the light on every frame
468     osg::LightSource* lightSource = new osg::LightSource;
469     lightSource->setUpdateCallback(new FGLightSourceUpdateCallback);
470     // relative because of CameraView being just a clever transform node
471     lightSource->setReferenceFrame(osg::LightSource::RELATIVE_RF);
472     lightSource->setLocalStateSetModes(osg::StateAttribute::ON);
473     
474     lightSource->addChild(sceneGroup);
475     lightSource->addChild(thesky->getPreRoot());
476     mRoot->addChild(lightSource);
477
478     stateSet = globals->get_scenery()->get_scene_graph()->getOrCreateStateSet();
479     stateSet->setMode(GL_ALPHA_TEST, osg::StateAttribute::ON);
480     stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
481     stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
482
483     // enable disable specular highlights.
484     // is the place where we might plug in an other fragment shader ...
485     osg::LightModel* lightModel = new osg::LightModel;
486     lightModel->setUpdateCallback(new FGLightModelUpdateCallback);
487     stateSet->setAttribute(lightModel);
488
489     // switch to enable wireframe
490     osg::PolygonMode* polygonMode = new osg::PolygonMode;
491     polygonMode->setUpdateCallback(new FGWireFrameModeUpdateCallback);
492     stateSet->setAttributeAndModes(polygonMode);
493
494     // scene fog handling
495     osg::Fog* fog = new osg::Fog;
496     fog->setUpdateCallback(new FGFogUpdateCallback);
497     stateSet->setAttributeAndModes(fog);
498     stateSet->setUpdateCallback(new FGFogEnableUpdateCallback);
499
500     // plug in the GUI
501     osg::Camera* guiCamera = getGUICamera(CameraGroup::getDefault());
502     if (guiCamera) {
503         osg::Geode* geode = new osg::Geode;
504         geode->addDrawable(new SGPuDrawable);
505         geode->addDrawable(new SGHUDAndPanelDrawable);
506         guiCamera->addChild(geode);
507     }
508     osg::Switch* sw = new osg::Switch;
509     sw->setUpdateCallback(new FGScenerySwitchCallback);
510     sw->addChild(mRoot.get());
511     mRealRoot->addChild(sw);
512     mRealRoot->addChild(thesky->getCloudRoot());
513     mRealRoot->addChild(FGCreateRedoutNode());
514 }
515
516
517 // Update all Visuals (redraws anything graphics related)
518 void
519 FGRenderer::update( bool refresh_camera_settings ) {
520     bool scenery_loaded = fgGetBool("sim/sceneryloaded")
521                           || fgGetBool("sim/sceneryloaded-override");
522     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
523     if ( idle_state < 1000 || !scenery_loaded ) {
524         fgSetDouble("/sim/startup/splash-alpha", 1.0);
525
526         // Keep resetting sim time while the sim is initializing
527         // the splash screen is now in the scenegraph
528         globals->set_sim_time_sec( 0.0 );
529         return;
530     }
531
532     // Fade out the splash screen over the first three seconds.
533     double sAlpha = SGMiscd::max(0, (2.5 - globals->get_sim_time_sec()) / 2.5);
534     fgSetDouble("/sim/startup/splash-alpha", sAlpha);
535
536     bool skyblend = fgGetBool("/sim/rendering/skyblend");
537     bool use_point_sprites = fgGetBool("/sim/rendering/point-sprites");
538     bool enhanced_lighting = fgGetBool("/sim/rendering/enhanced-lighting");
539     bool distance_attenuation
540         = fgGetBool("/sim/rendering/distance-attenuation");
541     // OSGFIXME
542     SGConfigureDirectionalLights( use_point_sprites, enhanced_lighting,
543                                   distance_attenuation );
544
545     static const SGPropertyNode *groundlevel_nearplane
546         = fgGetNode("/sim/current-view/ground-level-nearplane-m");
547
548     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
549
550     // update fog params
551     double actual_visibility;
552     if (fgGetBool("/environment/clouds/status")) {
553         actual_visibility = thesky->get_visibility();
554     } else {
555         actual_visibility = fgGetDouble("/environment/visibility-m");
556     }
557
558     // idle_state is now 1000 meaning we've finished all our
559     // initializations and are running the main loop, so this will
560     // now work without seg faulting the system.
561
562     FGViewer *current__view = globals->get_current_view();
563     // Force update of center dependent values ...
564     current__view->set_dirty();
565
566     if ( refresh_camera_settings ) {
567         // update view port
568         resize( fgGetInt("/sim/startup/xsize"),
569                 fgGetInt("/sim/startup/ysize") );
570     }
571     osg::Camera *camera = viewer->getCamera();
572
573     if ( skyblend ) {
574         
575         if ( fgGetBool("/sim/rendering/textures") ) {
576             SGVec4f clearColor(l->adj_fog_color());
577             camera->setClearColor(clearColor.osg());
578         }
579     } else {
580         SGVec4f clearColor(l->sky_color());
581         camera->setClearColor(clearColor.osg());
582     }
583
584     // update fog params if visibility has changed
585     double visibility_meters = fgGetDouble("/environment/visibility-m");
586     thesky->set_visibility(visibility_meters);
587
588     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
589                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
590                         / (double)fgGetInt("/sim/model-hz") );
591
592     // update the sky dome
593     if ( skyblend ) {
594
595         // The sun and moon distances are scaled down versions
596         // of the actual distance to get both the moon and the sun
597         // within the range of the far clip plane.
598         // Moon distance:    384,467 kilometers
599         // Sun distance: 150,000,000 kilometers
600
601         double sun_horiz_eff, moon_horiz_eff;
602         if (fgGetBool("/sim/rendering/horizon-effect")) {
603             sun_horiz_eff
604                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
605                                              0.0),
606                              0.33) / 3.0;
607             moon_horiz_eff
608                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
609                                              0.0),
610                              0.33)/3.0;
611         } else {
612            sun_horiz_eff = moon_horiz_eff = 1.0;
613         }
614
615         SGSkyState sstate;
616
617         SGVec3d viewPos = current__view->getViewPosition();
618         sstate.view_pos  = toVec3f(viewPos);
619         SGGeod geodViewPos = SGGeod::fromCart(viewPos);
620         SGGeod geodZeroViewPos = SGGeod::fromGeodM(geodViewPos, 0);
621         sstate.zero_elev = toVec3f(SGVec3d::fromGeod(geodZeroViewPos));
622         SGQuatd hlOr = SGQuatd::fromLonLat(geodViewPos);
623         sstate.view_up   = toVec3f(hlOr.backTransform(-SGVec3d::e3()));
624         sstate.lon       = geodViewPos.getLongitudeRad();
625         sstate.lat       = geodViewPos.getLatitudeRad();
626         sstate.alt       = geodViewPos.getElevationM();
627         sstate.spin      = l->get_sun_rotation();
628         sstate.gst       = globals->get_time_params()->getGst();
629         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
630         sstate.moon_dist = 40000.0 * moon_horiz_eff;
631         sstate.sun_angle = l->get_sun_angle();
632
633
634         /*
635          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
636          << l->sky_color()[0] << " "
637          << l->sky_color()[1] << " "
638          << l->sky_color()[2] << " "
639          << l->sky_color()[3] );
640         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
641          << l->fog_color()[0] << " "
642          << l->fog_color()[1] << " "
643          << l->fog_color()[2] << " "
644          << l->fog_color()[3] );
645         SG_LOG( SG_GENERAL, SG_BULK,
646                 "    sun_angle = " << l->sun_angle
647          << "    moon_angle = " << l->moon_angle );
648         */
649
650         SGSkyColor scolor;
651
652         scolor.sky_color   = SGVec3f(l->sky_color().data());
653         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
654         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
655         scolor.cloud_color = SGVec3f(l->cloud_color().data());
656         scolor.sun_angle   = l->get_sun_angle();
657         scolor.moon_angle  = l->get_moon_angle();
658
659         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
660         thesky->repaint( scolor, *globals->get_ephem() );
661
662         /*
663         SG_LOG( SG_GENERAL, SG_BULK,
664                 "thesky->reposition( view_pos = " << view_pos[0] << " "
665          << view_pos[1] << " " << view_pos[2] );
666         SG_LOG( SG_GENERAL, SG_BULK,
667                 "    zero_elev = " << zero_elev[0] << " "
668          << zero_elev[1] << " " << zero_elev[2]
669          << " lon = " << cur_fdm_state->get_Longitude()
670          << " lat = " << cur_fdm_state->get_Latitude() );
671         SG_LOG( SG_GENERAL, SG_BULK,
672                 "    sun_rot = " << l->get_sun_rotation
673          << " gst = " << SGTime::cur_time_params->getGst() );
674         SG_LOG( SG_GENERAL, SG_BULK,
675              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
676           << " sun dec = " << globals->get_ephem()->getSunDeclination()
677           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
678           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
679         */
680
681         //OSGFIXME
682 //         shadows->setupShadows(
683 //           current__view->getLongitude_deg(),
684 //           current__view->getLatitude_deg(),
685 //           globals->get_time_params()->getGst(),
686 //           globals->get_ephem()->getSunRightAscension(),
687 //           globals->get_ephem()->getSunDeclination(),
688 //           l->get_sun_angle());
689
690     }
691
692 //     sgEnviro.setLight(l->adj_fog_color());
693 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
694 //         current__view->get_world_up(),
695 //         current__view->getLongitude_deg(),
696 //         current__view->getLatitude_deg(),
697 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
698 //         delta_time_sec);
699
700     // OSGFIXME
701 //     sgEnviro.drawLightning();
702
703 //        double current_view_origin_airspeed_horiz_kt =
704 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
705 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
706 //                                * SGD_DEGREES_TO_RADIANS);
707
708     // OSGFIXME
709 //     if( is_internal )
710 //         shadows->endOfFrame();
711
712     // need to call the update visitor once
713     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
714     mUpdateVisitor->setViewData(current__view->getViewPosition(),
715                                 current__view->getViewOrientation());
716     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
717     mUpdateVisitor->setLight(direction, l->scene_ambient(),
718                              l->scene_diffuse(), l->scene_specular(),
719                              l->adj_fog_color(),
720                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
721     mUpdateVisitor->setVisibility(actual_visibility);
722     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
723     bool hotspots = fgGetBool("/sim/panel-hotspots");
724     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
725     cullMask |= simgear::GroundLightManager::instance()
726         ->getLightNodeMask(mUpdateVisitor.get());
727     if (hotspots)
728         cullMask |= simgear::PICK_BIT;
729     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
730 }
731
732
733
734 // options.cxx needs to see this for toggle_panel()
735 // Handle new window size or exposure
736 void
737 FGRenderer::resize( int width, int height ) {
738     int view_h;
739
740     if ( (!fgGetBool("/sim/virtual-cockpit"))
741          && fgPanelVisible() && idle_state == 1000 ) {
742         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
743                              globals->get_current_panel()->getYOffset()) / 768.0);
744     } else {
745         view_h = height;
746     }
747
748     static int lastwidth = 0;
749     static int lastheight = 0;
750     if (width != lastwidth)
751         fgSetInt("/sim/startup/xsize", lastwidth = width);
752     if (height != lastheight)
753         fgSetInt("/sim/startup/ysize", lastheight = height);
754
755     // for all views
756     FGViewMgr *viewmgr = globals->get_viewmgr();
757     if (viewmgr) {
758       for ( int i = 0; i < viewmgr->size(); ++i ) {
759         viewmgr->get_view(i)->
760           set_aspect_ratio((float)view_h / (float)width);
761       }
762     }
763 }
764
765 bool
766 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
767                  const osgGA::GUIEventAdapter* ea)
768 {
769     osgViewer::Viewer* viewer = globals->get_renderer()->getViewer();
770     // wipe out the return ...
771     pickList.clear();
772     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
773     Intersections intersections;
774
775     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
776         return false;
777     for (Intersections::iterator hit = intersections.begin(),
778              e = intersections.end();
779          hit != e;
780          ++hit) {
781         const osg::NodePath& np = hit->nodePath;
782         osg::NodePath::const_reverse_iterator npi;
783         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
784             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
785             if (!ud)
786                 continue;
787             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
788                 SGPickCallback* pickCallback = ud->getPickCallback(i);
789                 if (!pickCallback)
790                     continue;
791                 SGSceneryPick sceneryPick;
792                 sceneryPick.info.local = SGVec3d(hit->getLocalIntersectPoint());
793                 sceneryPick.info.wgs84 = SGVec3d(hit->getWorldIntersectPoint());
794                 sceneryPick.callback = pickCallback;
795                 pickList.push_back(sceneryPick);
796             }
797         }
798     }
799     return !pickList.empty();
800 }
801
802 void
803 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
804 {
805     viewer = viewer_;
806 }
807
808 void
809 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
810 {
811     eventHandler = eventHandler_;
812 }
813
814 void
815 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
816 {
817     mRealRoot->addChild(camera);
818 }
819
820 bool
821 fgDumpSceneGraphToFile(const char* filename)
822 {
823     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
824 }
825
826 bool
827 fgDumpTerrainBranchToFile(const char* filename)
828 {
829     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
830                                  filename );
831 }
832
833 // For debugging
834 bool
835 fgDumpNodeToFile(osg::Node* node, const char* filename)
836 {
837     return osgDB::writeNodeFile(*node, filename);
838 }
839 // end of renderer.cxx
840