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