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