]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/scenery.cxx
b64c16d5ce92492304e179582069daa8b3e95420
[flightgear.git] / src / Scenery / scenery.cxx
1 // scenery.cxx -- data structures and routines for managing scenery.
2 //
3 // Written by Curtis Olson, started May 1997.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <string.h>
30
31 #include <osg/Camera>
32 #include <osg/Transform>
33 #include <osg/MatrixTransform>
34 #include <osg/PositionAttitudeTransform>
35 #include <osg/CameraView>
36 #include <osg/LOD>
37
38 #include <osgViewer/Viewer>
39
40 #include <simgear/constants.h>
41 #include <simgear/sg_inlines.h>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/scene/tgdb/userdata.hxx>
44 #include <simgear/scene/material/matlib.hxx>
45 #include <simgear/scene/material/mat.hxx>
46 #include <simgear/scene/util/SGNodeMasks.hxx>
47 #include <simgear/scene/util/OsgMath.hxx>
48 #include <simgear/scene/util/SGSceneUserData.hxx>
49 #include <simgear/scene/model/CheckSceneryVisitor.hxx>
50 #include <simgear/scene/sky/sky.hxx>
51
52 #include <simgear/bvh/BVHNode.hxx>
53 #include <simgear/bvh/BVHLineSegmentVisitor.hxx>
54 #include <simgear/structure/commands.hxx>
55
56 #include <Viewer/renderer.hxx>
57 #include <Main/fg_props.hxx>
58 #include <GUI/MouseCursor.hxx>
59
60 #include "tilemgr.hxx"
61 #include "scenery.hxx"
62
63 using namespace flightgear;
64 using namespace simgear;
65
66 class FGGroundPickCallback : public SGPickCallback {
67 public:
68   FGGroundPickCallback() : SGPickCallback(PriorityScenery)
69   { }
70     
71   virtual bool buttonPressed( int button,
72                               const osgGA::GUIEventAdapter&,
73                               const Info& info )
74   {
75     // only on left mouse button
76     if (button != 0)
77       return false;
78
79     SGGeod geod = SGGeod::fromCart(info.wgs84);
80     SG_LOG( SG_TERRAIN, SG_INFO, "Got ground pick at " << geod );
81
82     SGPropertyNode *c = fgGetNode("/sim/input/click", true);
83     c->setDoubleValue("longitude-deg", geod.getLongitudeDeg());
84     c->setDoubleValue("latitude-deg", geod.getLatitudeDeg());
85     c->setDoubleValue("elevation-m", geod.getElevationM());
86     c->setDoubleValue("elevation-ft", geod.getElevationFt());
87     fgSetBool("/sim/signals/click", 1);
88
89     return true;
90   }
91 };
92
93 class FGSceneryIntersect : public osg::NodeVisitor {
94 public:
95     FGSceneryIntersect(const SGLineSegmentd& lineSegment,
96                        const osg::Node* skipNode) :
97         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
98         _lineSegment(lineSegment),
99         _skipNode(skipNode),
100         _material(0),
101         _haveHit(false)
102     { }
103
104     bool getHaveHit() const
105     { return _haveHit; }
106     const SGLineSegmentd& getLineSegment() const
107     { return _lineSegment; }
108     const simgear::BVHMaterial* getMaterial() const
109     { return _material; }
110
111     virtual void apply(osg::Node& node)
112     {
113         if (&node == _skipNode)
114             return;
115         if (!testBoundingSphere(node.getBound()))
116             return;
117
118         addBoundingVolume(node);
119     }
120
121     virtual void apply(osg::Group& group)
122     {
123         if (&group == _skipNode)
124             return;
125         if (!testBoundingSphere(group.getBound()))
126             return;
127
128         traverse(group);
129         addBoundingVolume(group);
130     }
131
132     virtual void apply(osg::Transform& transform)
133     { handleTransform(transform); }
134     virtual void apply(osg::Camera& camera)
135     {
136         if (camera.getRenderOrder() != osg::Camera::NESTED_RENDER)
137             return;
138         handleTransform(camera);
139     }
140     virtual void apply(osg::CameraView& transform)
141     { handleTransform(transform); }
142     virtual void apply(osg::MatrixTransform& transform)
143     { handleTransform(transform); }
144     virtual void apply(osg::PositionAttitudeTransform& transform)
145     { handleTransform(transform); }
146
147 private:
148     void handleTransform(osg::Transform& transform)
149     {
150         if (&transform == _skipNode)
151             return;
152         // Hmm, may be this needs to be refined somehow ...
153         if (transform.getReferenceFrame() != osg::Transform::RELATIVE_RF)
154             return;
155
156         if (!testBoundingSphere(transform.getBound()))
157             return;
158
159         osg::Matrix inverseMatrix;
160         if (!transform.computeWorldToLocalMatrix(inverseMatrix, this))
161             return;
162         osg::Matrix matrix;
163         if (!transform.computeLocalToWorldMatrix(matrix, this))
164             return;
165
166         SGLineSegmentd lineSegment = _lineSegment;
167         bool haveHit = _haveHit;
168         const simgear::BVHMaterial* material = _material;
169
170         _haveHit = false;
171         _lineSegment = lineSegment.transform(SGMatrixd(inverseMatrix.ptr()));
172
173         addBoundingVolume(transform);
174         traverse(transform);
175
176         if (_haveHit) {
177             _lineSegment = _lineSegment.transform(SGMatrixd(matrix.ptr()));
178         } else {
179             _lineSegment = lineSegment;
180             _material = material;
181             _haveHit = haveHit;
182         }
183     }
184
185     simgear::BVHNode* getNodeBoundingVolume(osg::Node& node)
186     {
187         SGSceneUserData* userData = SGSceneUserData::getSceneUserData(&node);
188         if (!userData)
189             return 0;
190         return userData->getBVHNode();
191     }
192     void addBoundingVolume(osg::Node& node)
193     {
194         simgear::BVHNode* bvNode = getNodeBoundingVolume(node);
195         if (!bvNode)
196             return;
197
198         // Find ground intersection on the bvh nodes
199         simgear::BVHLineSegmentVisitor lineSegmentVisitor(_lineSegment,
200                                                           0/*startTime*/);
201         bvNode->accept(lineSegmentVisitor);
202         if (!lineSegmentVisitor.empty()) {
203             _lineSegment = lineSegmentVisitor.getLineSegment();
204             _material = lineSegmentVisitor.getMaterial();
205             _haveHit = true;
206         }
207     }
208
209     bool testBoundingSphere(const osg::BoundingSphere& bound) const
210     {
211         if (!bound.valid())
212             return false;
213
214         SGSphered sphere(toVec3d(toSG(bound._center)), bound._radius);
215         return intersects(_lineSegment, sphere);
216     }
217
218     SGLineSegmentd _lineSegment;
219     const osg::Node* _skipNode;
220
221     const simgear::BVHMaterial* _material;
222     bool _haveHit;
223 };
224
225 class FGScenery::ScenerySwitchListener : public SGPropertyChangeListener
226 {
227 public:
228   ScenerySwitchListener(FGScenery* scenery) :
229     _scenery(scenery)
230   {
231     SGPropertyNode_ptr maskNode = fgGetNode("/sim/rendering/draw-mask", true);
232     maskNode->getChild("terrain", 0, true)->addChangeListener(this, true);
233     maskNode->getChild("models", 0, true)->addChangeListener(this, true);
234     maskNode->getChild("aircraft", 0, true)->addChangeListener(this, true);
235     maskNode->getChild("clouds", 0, true)->addChangeListener(this, true);
236     
237     // legacy compatability option
238     fgGetNode("/sim/rendering/draw-otw")->addChangeListener(this);
239     
240     // badly named property, this is what is set by --enable/disable-clouds
241     fgGetNode("/environment/clouds/status")->addChangeListener(this);
242   }
243   
244   ~ScenerySwitchListener()
245   {
246     SGPropertyNode_ptr maskNode = fgGetNode("/sim/rendering/draw-mask");
247     for (int i=0; i < maskNode->nChildren(); ++i) {
248       maskNode->getChild(i)->removeChangeListener(this);
249     }
250     
251     fgGetNode("/sim/rendering/draw-otw")->removeChangeListener(this);
252     fgGetNode("/environment/clouds/status")->removeChangeListener(this);
253   }
254   
255   virtual void valueChanged (SGPropertyNode * node)
256   {
257     bool b = node->getBoolValue();
258     std::string name(node->getNameString());
259   
260     if (name == "terrain") {
261       _scenery->scene_graph->setChildValue(_scenery->terrain_branch, b);
262     } else if (name == "models") {
263       _scenery->scene_graph->setChildValue(_scenery->models_branch, b);
264     } else if (name == "aircraft") {
265       _scenery->scene_graph->setChildValue(_scenery->aircraft_branch, b);
266     } else if (name == "clouds") {
267       // clouds live elsewhere in the scene, but we handle them here
268       globals->get_renderer()->getSky()->set_clouds_enabled(b);
269     } else if (name == "draw-otw") {
270       // legacy setting but let's keep it working
271       fgGetNode("/sim/rendering/draw-mask")->setBoolValue("terrain", b);
272       fgGetNode("/sim/rendering/draw-mask")->setBoolValue("models", b);
273     } else if (name == "status") {
274       fgGetNode("/sim/rendering/draw-mask")->setBoolValue("clouds", b);
275     }
276   }
277 private:
278   FGScenery* _scenery;
279 };
280
281 ////////////////////////////////////////////////////////////////////////////
282
283 // Scenery Management system
284 FGScenery::FGScenery() :
285     _listener(NULL)
286 {
287     // keep reference to pager singleton, so it cannot be destroyed while FGScenery lives
288     _pager = FGScenery::getPagerSingleton();
289
290     // Initialise the state of the scene graph.
291     _inited = false;
292 }
293
294 FGScenery::~FGScenery()
295 {
296     delete _listener;
297 }
298
299
300 // Initialize the Scenery Management system
301 void FGScenery::init() {
302     // Already set up.
303     if (_inited)
304         return;
305
306     // Scene graph root
307     scene_graph = new osg::Switch;
308     scene_graph->setName( "FGScenery" );
309
310     // Terrain branch
311     terrain_branch = new osg::Group;
312     terrain_branch->setName( "Terrain" );
313     scene_graph->addChild( terrain_branch.get() );
314     SGSceneUserData* userData;
315     userData = SGSceneUserData::getOrCreateSceneUserData(terrain_branch.get());
316     userData->setPickCallback(new FGGroundPickCallback);
317
318     models_branch = new osg::Group;
319     models_branch->setName( "Models" );
320     scene_graph->addChild( models_branch.get() );
321
322     aircraft_branch = new osg::Group;
323     aircraft_branch->setName( "Aircraft" );
324     scene_graph->addChild( aircraft_branch.get() );
325
326 // choosing to make the interior branch a child of the main
327 // aircraft group, for the moment. This simplifes places which
328 // assume all aircraft elements are within this group - principally
329 // FGODGuage::set_aircraft_texture.
330     interior_branch = new osg::Group;
331     interior_branch->setName( "Interior" );
332     
333     osg::LOD* interiorLOD = new osg::LOD;
334     interiorLOD->addChild(interior_branch.get(), 0.0, 50.0);
335     aircraft_branch->addChild( interiorLOD );
336     
337     // Set up the particle system as a directly accessible branch of the scene graph.
338     particles_branch = simgear::Particles::getCommonRoot();
339     particles_branch->setName("Particles");
340     scene_graph->addChild(particles_branch.get());
341     simgear::GlobalParticleCallback::setSwitch(fgGetNode("/sim/rendering/particles", true));
342   
343     // Set up the precipitation system.
344     precipitation_branch = new osg::Group;
345     precipitation_branch->setName("Precipitation");
346     scene_graph->addChild(precipitation_branch.get());
347
348     _listener = new ScenerySwitchListener(this);
349
350     // Toggle the setup flag.
351     _inited = true;
352 }
353
354 void FGScenery::shutdown()
355 {
356     scene_graph = NULL;
357     terrain_branch = NULL;
358     models_branch = NULL;
359     aircraft_branch = NULL;
360     particles_branch = NULL;
361     precipitation_branch = NULL;
362
363     // Toggle the setup flag.
364     _inited = false;
365 }
366
367
368 void FGScenery::update(double dt)
369 {
370     SG_UNUSED(dt);
371     // nothing here, don't call again
372     suspend();
373 }
374
375
376 void FGScenery::bind() {
377 }
378
379
380 void FGScenery::unbind() {
381 }
382
383 bool
384 FGScenery::get_cart_elevation_m(const SGVec3d& pos, double max_altoff,
385                                 double& alt,
386                                 const simgear::BVHMaterial** material,
387                                 const osg::Node* butNotFrom)
388 {
389   SGGeod geod = SGGeod::fromCart(pos);
390   geod.setElevationM(geod.getElevationM() + max_altoff);
391   return get_elevation_m(geod, alt, material, butNotFrom);
392 }
393
394 bool
395 FGScenery::get_elevation_m(const SGGeod& geod, double& alt,
396                            const simgear::BVHMaterial** material,
397                            const osg::Node* butNotFrom)
398 {
399   SGVec3d start = SGVec3d::fromGeod(geod);
400
401   SGGeod geodEnd = geod;
402   geodEnd.setElevationM(SGMiscd::min(geod.getElevationM() - 10, -10000));
403   SGVec3d end = SGVec3d::fromGeod(geodEnd);
404
405   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
406   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
407   get_scene_graph()->accept(intersectVisitor);
408
409   if (!intersectVisitor.getHaveHit())
410       return false;
411
412   geodEnd = SGGeod::fromCart(intersectVisitor.getLineSegment().getEnd());
413   alt = geodEnd.getElevationM();
414   if (material)
415       *material = intersectVisitor.getMaterial();
416
417   return true;
418 }
419
420 bool
421 FGScenery::get_cart_ground_intersection(const SGVec3d& pos, const SGVec3d& dir,
422                                         SGVec3d& nearestHit,
423                                         const osg::Node* butNotFrom)
424 {
425   // We assume that starting positions in the center of the earth are invalid
426   if ( norm1(pos) < 1 )
427     return false;
428
429   // Make really sure the direction is normalized, is really cheap compared to
430   // computation of ground intersection.
431   SGVec3d start = pos;
432   SGVec3d end = start + 1e5*normalize(dir); // FIXME visibility ???
433
434   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
435   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
436   get_scene_graph()->accept(intersectVisitor);
437
438   if (!intersectVisitor.getHaveHit())
439       return false;
440
441   nearestHit = intersectVisitor.getLineSegment().getEnd();
442   return true;
443 }
444
445 bool FGScenery::scenery_available(const SGGeod& position, double range_m)
446 {
447   if(globals->get_tile_mgr()->schedule_scenery(position, range_m, 0.0))
448   {
449     double elev;
450     if (!get_elevation_m(SGGeod::fromGeodM(position, SG_MAX_ELEVATION_M), elev, 0, 0))
451       return false;
452     SGVec3f p = SGVec3f::fromGeod(SGGeod::fromGeodM(position, elev));
453     osg::FrameStamp* framestamp
454             = globals->get_renderer()->getViewer()->getFrameStamp();
455     simgear::CheckSceneryVisitor csnv(_pager, toOsg(p), range_m, framestamp);
456     // currently the PagedLODs will not be loaded by the DatabasePager
457     // while the splashscreen is there, so CheckSceneryVisitor force-loads
458     // missing objects in the main thread
459     get_scene_graph()->accept(csnv);
460     if(!csnv.isLoaded()) {
461         SG_LOG(SG_TERRAIN, SG_DEBUG, "FGScenery::scenery_available: waiting on CheckSceneryVisitor");
462         return false;
463     }
464     return true;
465   } else {
466     SG_LOG(SG_TERRAIN, SG_DEBUG, "FGScenery::scenery_available: waiting on tile manager");
467   }
468   return false;
469 }
470
471 static osg::ref_ptr<SceneryPager> pager;
472
473 SceneryPager* FGScenery::getPagerSingleton()
474 {
475     if (!pager)
476         pager = new SceneryPager;
477     return pager.get();
478 }
479
480 void FGScenery::resetPagerSingleton()
481 {
482     pager = NULL;
483 }
484