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