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