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