]> git.mxchange.org Git - flightgear.git/blob - src/Main/renderer.cxx
Merge branch 'tat/configure' into next
[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(toOsg(l->scene_ambient()));
242     light->setDiffuse(toOsg(l->scene_diffuse()));
243     light->setSpecular(toOsg(l->scene_specular()));
244     osg::Vec4f position(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2], 0);
245     light->setPosition(position);
246     osg::Vec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
247     light->setDirection(direction);
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(toOsg(l->scene_ambient());
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(toOsg(updateVisitor->getFogColor()));
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     FGLight *l = static_cast<FGLight*>(globals->get_subsystem("lighting"));
546
547     // update fog params
548     double actual_visibility;
549     if (fgGetBool("/environment/clouds/status")) {
550         actual_visibility = thesky->get_visibility();
551     } else {
552         actual_visibility = fgGetDouble("/environment/visibility-m");
553     }
554
555     // idle_state is now 1000 meaning we've finished all our
556     // initializations and are running the main loop, so this will
557     // now work without seg faulting the system.
558
559     FGViewer *current__view = globals->get_current_view();
560     // Force update of center dependent values ...
561     current__view->set_dirty();
562
563     if ( refresh_camera_settings ) {
564         // update view port
565         resize( fgGetInt("/sim/startup/xsize"),
566                 fgGetInt("/sim/startup/ysize") );
567     }
568     osg::Camera *camera = viewer->getCamera();
569
570     if ( skyblend ) {
571         
572         if ( fgGetBool("/sim/rendering/textures") ) {
573             SGVec4f clearColor(l->adj_fog_color());
574             camera->setClearColor(toOsg(clearColor));
575         }
576     } else {
577         SGVec4f clearColor(l->sky_color());
578         camera->setClearColor(toOsg(clearColor));
579     }
580
581     // update fog params if visibility has changed
582     double visibility_meters = fgGetDouble("/environment/visibility-m");
583     thesky->set_visibility(visibility_meters);
584
585     thesky->modify_vis( cur_fdm_state->get_Altitude() * SG_FEET_TO_METER,
586                         ( global_multi_loop * fgGetInt("/sim/speed-up") )
587                         / (double)fgGetInt("/sim/model-hz") );
588
589     // update the sky dome
590     if ( skyblend ) {
591
592         // The sun and moon distances are scaled down versions
593         // of the actual distance to get both the moon and the sun
594         // within the range of the far clip plane.
595         // Moon distance:    384,467 kilometers
596         // Sun distance: 150,000,000 kilometers
597
598         double sun_horiz_eff, moon_horiz_eff;
599         if (fgGetBool("/sim/rendering/horizon-effect")) {
600             sun_horiz_eff
601                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_sun_angle()),
602                                              0.0),
603                              0.33) / 3.0;
604             moon_horiz_eff
605                 = 0.67 + pow(osg::clampAbove(0.5 + cos(l->get_moon_angle()),
606                                              0.0),
607                              0.33)/3.0;
608         } else {
609            sun_horiz_eff = moon_horiz_eff = 1.0;
610         }
611
612         SGSkyState sstate;
613
614         SGVec3d viewPos = current__view->getViewPosition();
615         sstate.view_pos  = toVec3f(viewPos);
616         SGGeod geodViewPos = SGGeod::fromCart(viewPos);
617         SGGeod geodZeroViewPos = SGGeod::fromGeodM(geodViewPos, 0);
618         sstate.zero_elev = toVec3f(SGVec3d::fromGeod(geodZeroViewPos));
619         SGQuatd hlOr = SGQuatd::fromLonLat(geodViewPos);
620         sstate.view_up   = toVec3f(hlOr.backTransform(-SGVec3d::e3()));
621         sstate.lon       = geodViewPos.getLongitudeRad();
622         sstate.lat       = geodViewPos.getLatitudeRad();
623         sstate.alt       = geodViewPos.getElevationM();
624         sstate.spin      = l->get_sun_rotation();
625         sstate.gst       = globals->get_time_params()->getGst();
626         sstate.sun_dist  = 50000.0 * sun_horiz_eff;
627         sstate.moon_dist = 40000.0 * moon_horiz_eff;
628         sstate.sun_angle = l->get_sun_angle();
629
630
631         /*
632          SG_LOG( SG_GENERAL, SG_BULK, "thesky->repaint() sky_color = "
633          << l->sky_color()[0] << " "
634          << l->sky_color()[1] << " "
635          << l->sky_color()[2] << " "
636          << l->sky_color()[3] );
637         SG_LOG( SG_GENERAL, SG_BULK, "    fog = "
638          << l->fog_color()[0] << " "
639          << l->fog_color()[1] << " "
640          << l->fog_color()[2] << " "
641          << l->fog_color()[3] );
642         SG_LOG( SG_GENERAL, SG_BULK,
643                 "    sun_angle = " << l->sun_angle
644          << "    moon_angle = " << l->moon_angle );
645         */
646
647         SGSkyColor scolor;
648
649         scolor.sky_color   = SGVec3f(l->sky_color().data());
650         scolor.adj_sky_color = SGVec3f(l->adj_sky_color().data());
651         scolor.fog_color   = SGVec3f(l->adj_fog_color().data());
652         scolor.cloud_color = SGVec3f(l->cloud_color().data());
653         scolor.sun_angle   = l->get_sun_angle();
654         scolor.moon_angle  = l->get_moon_angle();
655
656         thesky->reposition( sstate, *globals->get_ephem(), delta_time_sec );
657         thesky->repaint( scolor, *globals->get_ephem() );
658
659         /*
660         SG_LOG( SG_GENERAL, SG_BULK,
661                 "thesky->reposition( view_pos = " << view_pos[0] << " "
662          << view_pos[1] << " " << view_pos[2] );
663         SG_LOG( SG_GENERAL, SG_BULK,
664                 "    zero_elev = " << zero_elev[0] << " "
665          << zero_elev[1] << " " << zero_elev[2]
666          << " lon = " << cur_fdm_state->get_Longitude()
667          << " lat = " << cur_fdm_state->get_Latitude() );
668         SG_LOG( SG_GENERAL, SG_BULK,
669                 "    sun_rot = " << l->get_sun_rotation
670          << " gst = " << SGTime::cur_time_params->getGst() );
671         SG_LOG( SG_GENERAL, SG_BULK,
672              "    sun ra = " << globals->get_ephem()->getSunRightAscension()
673           << " sun dec = " << globals->get_ephem()->getSunDeclination()
674           << " moon ra = " << globals->get_ephem()->getMoonRightAscension()
675           << " moon dec = " << globals->get_ephem()->getMoonDeclination() );
676         */
677
678         //OSGFIXME
679 //         shadows->setupShadows(
680 //           current__view->getLongitude_deg(),
681 //           current__view->getLatitude_deg(),
682 //           globals->get_time_params()->getGst(),
683 //           globals->get_ephem()->getSunRightAscension(),
684 //           globals->get_ephem()->getSunDeclination(),
685 //           l->get_sun_angle());
686
687     }
688
689 //     sgEnviro.setLight(l->adj_fog_color());
690 //     sgEnviro.startOfFrame(current__view->get_view_pos(), 
691 //         current__view->get_world_up(),
692 //         current__view->getLongitude_deg(),
693 //         current__view->getLatitude_deg(),
694 //         current__view->getAltitudeASL_ft() * SG_FEET_TO_METER,
695 //         delta_time_sec);
696
697     // OSGFIXME
698 //     sgEnviro.drawLightning();
699
700 //        double current_view_origin_airspeed_horiz_kt =
701 //         fgGetDouble("/velocities/airspeed-kt", 0.0)
702 //                        * cos( fgGetDouble("/orientation/pitch-deg", 0.0)
703 //                                * SGD_DEGREES_TO_RADIANS);
704
705     // OSGFIXME
706 //     if( is_internal )
707 //         shadows->endOfFrame();
708
709     // need to call the update visitor once
710     mFrameStamp->setCalendarTime(*globals->get_time_params()->getGmt());
711     mUpdateVisitor->setViewData(current__view->getViewPosition(),
712                                 current__view->getViewOrientation());
713     SGVec3f direction(l->sun_vec()[0], l->sun_vec()[1], l->sun_vec()[2]);
714     mUpdateVisitor->setLight(direction, l->scene_ambient(),
715                              l->scene_diffuse(), l->scene_specular(),
716                              l->adj_fog_color(),
717                              l->get_sun_angle()*SGD_RADIANS_TO_DEGREES);
718     mUpdateVisitor->setVisibility(actual_visibility);
719     simgear::GroundLightManager::instance()->update(mUpdateVisitor.get());
720     bool hotspots = fgGetBool("/sim/panel-hotspots");
721     osg::Node::NodeMask cullMask = ~simgear::LIGHTS_BITS & ~simgear::PICK_BIT;
722     cullMask |= simgear::GroundLightManager::instance()
723         ->getLightNodeMask(mUpdateVisitor.get());
724     if (hotspots)
725         cullMask |= simgear::PICK_BIT;
726     CameraGroup::getDefault()->setCameraCullMasks(cullMask);
727 }
728
729
730
731 // options.cxx needs to see this for toggle_panel()
732 // Handle new window size or exposure
733 void
734 FGRenderer::resize( int width, int height ) {
735     int view_h;
736
737     if ( (!fgGetBool("/sim/virtual-cockpit"))
738          && fgPanelVisible() && idle_state == 1000 ) {
739         view_h = (int)(height * (globals->get_current_panel()->getViewHeight() -
740                              globals->get_current_panel()->getYOffset()) / 768.0);
741     } else {
742         view_h = height;
743     }
744
745     static int lastwidth = 0;
746     static int lastheight = 0;
747     if (width != lastwidth)
748         fgSetInt("/sim/startup/xsize", lastwidth = width);
749     if (height != lastheight)
750         fgSetInt("/sim/startup/ysize", lastheight = height);
751
752     // for all views
753     FGViewMgr *viewmgr = globals->get_viewmgr();
754     if (viewmgr) {
755       for ( int i = 0; i < viewmgr->size(); ++i ) {
756         viewmgr->get_view(i)->
757           set_aspect_ratio((float)view_h / (float)width);
758       }
759     }
760 }
761
762 bool
763 FGRenderer::pick(std::vector<SGSceneryPick>& pickList,
764                  const osgGA::GUIEventAdapter* ea)
765 {
766     // wipe out the return ...
767     pickList.clear();
768     typedef osgUtil::LineSegmentIntersector::Intersections Intersections;
769     Intersections intersections;
770
771     if (!computeIntersections(CameraGroup::getDefault(), ea, intersections))
772         return false;
773     for (Intersections::iterator hit = intersections.begin(),
774              e = intersections.end();
775          hit != e;
776          ++hit) {
777         const osg::NodePath& np = hit->nodePath;
778         osg::NodePath::const_reverse_iterator npi;
779         for (npi = np.rbegin(); npi != np.rend(); ++npi) {
780             SGSceneUserData* ud = SGSceneUserData::getSceneUserData(*npi);
781             if (!ud)
782                 continue;
783             for (unsigned i = 0; i < ud->getNumPickCallbacks(); ++i) {
784                 SGPickCallback* pickCallback = ud->getPickCallback(i);
785                 if (!pickCallback)
786                     continue;
787                 SGSceneryPick sceneryPick;
788                 sceneryPick.info.local = toSG(hit->getLocalIntersectPoint());
789                 sceneryPick.info.wgs84 = toSG(hit->getWorldIntersectPoint());
790                 sceneryPick.callback = pickCallback;
791                 pickList.push_back(sceneryPick);
792             }
793         }
794     }
795     return !pickList.empty();
796 }
797
798 void
799 FGRenderer::setViewer(osgViewer::Viewer* viewer_)
800 {
801     viewer = viewer_;
802 }
803
804 void
805 FGRenderer::setEventHandler(FGEventHandler* eventHandler_)
806 {
807     eventHandler = eventHandler_;
808 }
809
810 void
811 FGRenderer::addCamera(osg::Camera* camera, bool useSceneData)
812 {
813     mRealRoot->addChild(camera);
814 }
815
816 bool
817 fgDumpSceneGraphToFile(const char* filename)
818 {
819     return osgDB::writeNodeFile(*mRealRoot.get(), filename);
820 }
821
822 bool
823 fgDumpTerrainBranchToFile(const char* filename)
824 {
825     return osgDB::writeNodeFile( *globals->get_scenery()->get_terrain_branch(),
826                                  filename );
827 }
828
829 // For debugging
830 bool
831 fgDumpNodeToFile(osg::Node* node, const char* filename)
832 {
833     return osgDB::writeNodeFile(*node, filename);
834 }
835 // end of renderer.cxx
836