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