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