]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/scenery.cxx
MapWidget: silence compiler warning
[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/bvh/BVHNode.hxx>
51 #include <simgear/bvh/BVHLineSegmentVisitor.hxx>
52 #include <simgear/structure/commands.hxx>
53
54 #include <Viewer/renderer.hxx>
55 #include <Main/fg_props.hxx>
56 #include <GUI/MouseCursor.hxx>
57
58 #include "tilemgr.hxx"
59 #include "scenery.hxx"
60
61 using namespace flightgear;
62 using namespace simgear;
63
64 class FGGroundPickCallback : public SGPickCallback {
65 public:
66   FGGroundPickCallback() : SGPickCallback(PriorityScenery)
67   { }
68     
69   virtual bool buttonPressed( int button,
70                               const osgGA::GUIEventAdapter&,
71                               const Info& info )
72   {
73     // only on left mouse button
74     if (button != 0)
75       return false;
76
77     SGGeod geod = SGGeod::fromCart(info.wgs84);
78     SG_LOG( SG_TERRAIN, SG_INFO, "Got ground pick at " << geod );
79
80     SGPropertyNode *c = fgGetNode("/sim/input/click", true);
81     c->setDoubleValue("longitude-deg", geod.getLongitudeDeg());
82     c->setDoubleValue("latitude-deg", geod.getLatitudeDeg());
83     c->setDoubleValue("elevation-m", geod.getElevationM());
84     c->setDoubleValue("elevation-ft", geod.getElevationFt());
85     fgSetBool("/sim/signals/click", 1);
86
87     return true;
88   }
89 };
90
91 class FGSceneryIntersect : public osg::NodeVisitor {
92 public:
93     FGSceneryIntersect(const SGLineSegmentd& lineSegment,
94                        const osg::Node* skipNode) :
95         osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
96         _lineSegment(lineSegment),
97         _skipNode(skipNode),
98         _material(0),
99         _haveHit(false)
100     { }
101
102     bool getHaveHit() const
103     { return _haveHit; }
104     const SGLineSegmentd& getLineSegment() const
105     { return _lineSegment; }
106     const simgear::BVHMaterial* getMaterial() const
107     { return _material; }
108
109     virtual void apply(osg::Node& node)
110     {
111         if (&node == _skipNode)
112             return;
113         if (!testBoundingSphere(node.getBound()))
114             return;
115
116         addBoundingVolume(node);
117     }
118
119     virtual void apply(osg::Group& group)
120     {
121         if (&group == _skipNode)
122             return;
123         if (!testBoundingSphere(group.getBound()))
124             return;
125
126         traverse(group);
127         addBoundingVolume(group);
128     }
129
130     virtual void apply(osg::Transform& transform)
131     { handleTransform(transform); }
132     virtual void apply(osg::Camera& camera)
133     {
134         if (camera.getRenderOrder() != osg::Camera::NESTED_RENDER)
135             return;
136         handleTransform(camera);
137     }
138     virtual void apply(osg::CameraView& transform)
139     { handleTransform(transform); }
140     virtual void apply(osg::MatrixTransform& transform)
141     { handleTransform(transform); }
142     virtual void apply(osg::PositionAttitudeTransform& transform)
143     { handleTransform(transform); }
144
145 private:
146     void handleTransform(osg::Transform& transform)
147     {
148         if (&transform == _skipNode)
149             return;
150         // Hmm, may be this needs to be refined somehow ...
151         if (transform.getReferenceFrame() != osg::Transform::RELATIVE_RF)
152             return;
153
154         if (!testBoundingSphere(transform.getBound()))
155             return;
156
157         osg::Matrix inverseMatrix;
158         if (!transform.computeWorldToLocalMatrix(inverseMatrix, this))
159             return;
160         osg::Matrix matrix;
161         if (!transform.computeLocalToWorldMatrix(matrix, this))
162             return;
163
164         SGLineSegmentd lineSegment = _lineSegment;
165         bool haveHit = _haveHit;
166         const simgear::BVHMaterial* material = _material;
167
168         _haveHit = false;
169         _lineSegment = lineSegment.transform(SGMatrixd(inverseMatrix.ptr()));
170
171         addBoundingVolume(transform);
172         traverse(transform);
173
174         if (_haveHit) {
175             _lineSegment = _lineSegment.transform(SGMatrixd(matrix.ptr()));
176         } else {
177             _lineSegment = lineSegment;
178             _material = material;
179             _haveHit = haveHit;
180         }
181     }
182
183     simgear::BVHNode* getNodeBoundingVolume(osg::Node& node)
184     {
185         SGSceneUserData* userData = SGSceneUserData::getSceneUserData(&node);
186         if (!userData)
187             return 0;
188         return userData->getBVHNode();
189     }
190     void addBoundingVolume(osg::Node& node)
191     {
192         simgear::BVHNode* bvNode = getNodeBoundingVolume(node);
193         if (!bvNode)
194             return;
195
196         // Find ground intersection on the bvh nodes
197         simgear::BVHLineSegmentVisitor lineSegmentVisitor(_lineSegment,
198                                                           0/*startTime*/);
199         bvNode->accept(lineSegmentVisitor);
200         if (!lineSegmentVisitor.empty()) {
201             _lineSegment = lineSegmentVisitor.getLineSegment();
202             _material = lineSegmentVisitor.getMaterial();
203             _haveHit = true;
204         }
205     }
206
207     bool testBoundingSphere(const osg::BoundingSphere& bound) const
208     {
209         if (!bound.valid())
210             return false;
211
212         SGSphered sphere(toVec3d(toSG(bound._center)), bound._radius);
213         return intersects(_lineSegment, sphere);
214     }
215
216     SGLineSegmentd _lineSegment;
217     const osg::Node* _skipNode;
218
219     const simgear::BVHMaterial* _material;
220     bool _haveHit;
221 };
222
223 // Scenery Management system
224 FGScenery::FGScenery()
225 {
226     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing scenery subsystem" );
227     // keep reference to pager singleton, so it cannot be destroyed while FGScenery lives
228     _pager = FGScenery::getPagerSingleton();
229 }
230
231 FGScenery::~FGScenery() {
232 }
233
234
235 // Initialize the Scenery Management system
236 void FGScenery::init() {
237     // Scene graph root
238     scene_graph = new osg::Group;
239     scene_graph->setName( "FGScenery" );
240
241     // Terrain branch
242     terrain_branch = new osg::Group;
243     terrain_branch->setName( "Terrain" );
244     scene_graph->addChild( terrain_branch.get() );
245     SGSceneUserData* userData;
246     userData = SGSceneUserData::getOrCreateSceneUserData(terrain_branch.get());
247     userData->setPickCallback(new FGGroundPickCallback);
248
249     models_branch = new osg::Group;
250     models_branch->setName( "Models" );
251     scene_graph->addChild( models_branch.get() );
252
253     aircraft_branch = new osg::Group;
254     aircraft_branch->setName( "Aircraft" );
255     scene_graph->addChild( aircraft_branch.get() );
256
257 // choosing to make the interior branch a child of the main
258 // aircraft group, for the moment. This simplifes places which
259 // assume all aircraft elements are within this group - principally
260 // FGODGuage::set_aircraft_texture.
261     interior_branch = new osg::Group;
262     interior_branch->setName( "Interior" );
263     
264     osg::LOD* interiorLOD = new osg::LOD;
265     interiorLOD->addChild(interior_branch.get(), 0.0, 50.0);
266     aircraft_branch->addChild( interiorLOD );
267     
268     // Initials values needed by the draw-time object loader
269     sgUserDataInit( globals->get_props() );
270 }
271
272 void FGScenery::shutdown()
273 {
274     sgUserDataInit( NULL );
275     
276     scene_graph = NULL;
277     terrain_branch = NULL;
278     models_branch = NULL;
279     aircraft_branch = NULL;
280 }
281
282
283 void FGScenery::update(double dt)
284 {
285     SG_UNUSED(dt);
286     // nothing here, don't call again
287     suspend();
288 }
289
290
291 void FGScenery::bind() {
292 }
293
294
295 void FGScenery::unbind() {
296 }
297
298 bool
299 FGScenery::get_cart_elevation_m(const SGVec3d& pos, double max_altoff,
300                                 double& alt,
301                                 const simgear::BVHMaterial** material,
302                                 const osg::Node* butNotFrom)
303 {
304   SGGeod geod = SGGeod::fromCart(pos);
305   geod.setElevationM(geod.getElevationM() + max_altoff);
306   return get_elevation_m(geod, alt, material, butNotFrom);
307 }
308
309 bool
310 FGScenery::get_elevation_m(const SGGeod& geod, double& alt,
311                            const simgear::BVHMaterial** material,
312                            const osg::Node* butNotFrom)
313 {
314   SGVec3d start = SGVec3d::fromGeod(geod);
315
316   SGGeod geodEnd = geod;
317   geodEnd.setElevationM(SGMiscd::min(geod.getElevationM() - 10, -10000));
318   SGVec3d end = SGVec3d::fromGeod(geodEnd);
319
320   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
321   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
322   get_scene_graph()->accept(intersectVisitor);
323
324   if (!intersectVisitor.getHaveHit())
325       return false;
326
327   geodEnd = SGGeod::fromCart(intersectVisitor.getLineSegment().getEnd());
328   alt = geodEnd.getElevationM();
329   if (material)
330       *material = intersectVisitor.getMaterial();
331
332   return true;
333 }
334
335 bool
336 FGScenery::get_cart_ground_intersection(const SGVec3d& pos, const SGVec3d& dir,
337                                         SGVec3d& nearestHit,
338                                         const osg::Node* butNotFrom)
339 {
340   // We assume that starting positions in the center of the earth are invalid
341   if ( norm1(pos) < 1 )
342     return false;
343
344   // Make really sure the direction is normalized, is really cheap compared to
345   // computation of ground intersection.
346   SGVec3d start = pos;
347   SGVec3d end = start + 1e5*normalize(dir); // FIXME visibility ???
348
349   FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
350   intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
351   get_scene_graph()->accept(intersectVisitor);
352
353   if (!intersectVisitor.getHaveHit())
354       return false;
355
356   nearestHit = intersectVisitor.getLineSegment().getEnd();
357   return true;
358 }
359
360 bool FGScenery::scenery_available(const SGGeod& position, double range_m)
361 {
362   if(globals->get_tile_mgr()->schedule_scenery(position, range_m, 0.0))
363   {
364     double elev;
365     if (!get_elevation_m(SGGeod::fromGeodM(position, SG_MAX_ELEVATION_M), elev, 0, 0))
366       return false;
367     SGVec3f p = SGVec3f::fromGeod(SGGeod::fromGeodM(position, elev));
368     osg::FrameStamp* framestamp
369             = globals->get_renderer()->getViewer()->getFrameStamp();
370     simgear::CheckSceneryVisitor csnv(_pager, toOsg(p), range_m, framestamp);
371     // currently the PagedLODs will not be loaded by the DatabasePager
372     // while the splashscreen is there, so CheckSceneryVisitor force-loads
373     // missing objects in the main thread
374     get_scene_graph()->accept(csnv);
375     if(!csnv.isLoaded())
376         return false;
377     return true;
378   }
379   return false;
380 }
381
382 static osg::ref_ptr<SceneryPager> pager;
383
384 SceneryPager* FGScenery::getPagerSingleton()
385 {
386     if (!pager)
387         pager = new SceneryPager;
388     return pager.get();
389 }
390
391 void FGScenery::resetPagerSingleton()
392 {
393     pager = NULL;
394 }
395