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