1 // scenery.cxx -- data structures and routines for managing scenery.
3 // Written by Curtis Olson, started May 1997.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
32 #include <osg/Transform>
33 #include <osg/MatrixTransform>
34 #include <osg/PositionAttitudeTransform>
35 #include <osg/CameraView>
38 #include <osgViewer/Viewer>
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>
52 #include <simgear/bvh/BVHNode.hxx>
53 #include <simgear/bvh/BVHLineSegmentVisitor.hxx>
54 #include <simgear/structure/commands.hxx>
56 #include <Viewer/renderer.hxx>
57 #include <Main/fg_props.hxx>
58 #include <GUI/MouseCursor.hxx>
60 #include "tilemgr.hxx"
61 #include "scenery.hxx"
63 using namespace flightgear;
64 using namespace simgear;
66 class FGGroundPickCallback : public SGPickCallback {
68 FGGroundPickCallback() : SGPickCallback(PriorityScenery)
71 virtual bool buttonPressed( int button,
72 const osgGA::GUIEventAdapter&,
75 // only on left mouse button
79 SGGeod geod = SGGeod::fromCart(info.wgs84);
80 SG_LOG( SG_TERRAIN, SG_INFO, "Got ground pick at " << geod );
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);
93 class FGSceneryIntersect : public osg::NodeVisitor {
95 FGSceneryIntersect(const SGLineSegmentd& lineSegment,
96 const osg::Node* skipNode) :
97 osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ACTIVE_CHILDREN),
98 _lineSegment(lineSegment),
104 bool getHaveHit() const
106 const SGLineSegmentd& getLineSegment() const
107 { return _lineSegment; }
108 const simgear::BVHMaterial* getMaterial() const
109 { return _material; }
111 virtual void apply(osg::Node& node)
113 if (&node == _skipNode)
115 if (!testBoundingSphere(node.getBound()))
118 addBoundingVolume(node);
121 virtual void apply(osg::Group& group)
123 if (&group == _skipNode)
125 if (!testBoundingSphere(group.getBound()))
129 addBoundingVolume(group);
132 virtual void apply(osg::Transform& transform)
133 { handleTransform(transform); }
134 virtual void apply(osg::Camera& camera)
136 if (camera.getRenderOrder() != osg::Camera::NESTED_RENDER)
138 handleTransform(camera);
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); }
148 void handleTransform(osg::Transform& transform)
150 if (&transform == _skipNode)
152 // Hmm, may be this needs to be refined somehow ...
153 if (transform.getReferenceFrame() != osg::Transform::RELATIVE_RF)
156 if (!testBoundingSphere(transform.getBound()))
159 osg::Matrix inverseMatrix;
160 if (!transform.computeWorldToLocalMatrix(inverseMatrix, this))
163 if (!transform.computeLocalToWorldMatrix(matrix, this))
166 SGLineSegmentd lineSegment = _lineSegment;
167 bool haveHit = _haveHit;
168 const simgear::BVHMaterial* material = _material;
171 _lineSegment = lineSegment.transform(SGMatrixd(inverseMatrix.ptr()));
173 addBoundingVolume(transform);
177 _lineSegment = _lineSegment.transform(SGMatrixd(matrix.ptr()));
179 _lineSegment = lineSegment;
180 _material = material;
185 simgear::BVHNode* getNodeBoundingVolume(osg::Node& node)
187 SGSceneUserData* userData = SGSceneUserData::getSceneUserData(&node);
190 return userData->getBVHNode();
192 void addBoundingVolume(osg::Node& node)
194 simgear::BVHNode* bvNode = getNodeBoundingVolume(node);
198 // Find ground intersection on the bvh nodes
199 simgear::BVHLineSegmentVisitor lineSegmentVisitor(_lineSegment,
201 bvNode->accept(lineSegmentVisitor);
202 if (!lineSegmentVisitor.empty()) {
203 _lineSegment = lineSegmentVisitor.getLineSegment();
204 _material = lineSegmentVisitor.getMaterial();
209 bool testBoundingSphere(const osg::BoundingSphere& bound) const
214 SGSphered sphere(toVec3d(toSG(bound._center)), bound._radius);
215 return intersects(_lineSegment, sphere);
218 SGLineSegmentd _lineSegment;
219 const osg::Node* _skipNode;
221 const simgear::BVHMaterial* _material;
225 class FGScenery::ScenerySwitchListener : public SGPropertyChangeListener
228 ScenerySwitchListener(FGScenery* scenery) :
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);
237 // legacy compatability option
238 fgGetNode("/sim/rendering/draw-otw")->addChangeListener(this);
240 // badly named property, this is what is set by --enable/disable-clouds
241 fgGetNode("/environment/clouds/status")->addChangeListener(this);
244 ~ScenerySwitchListener()
246 SGPropertyNode_ptr maskNode = fgGetNode("/sim/rendering/draw-mask");
247 for (int i=0; i < maskNode->nChildren(); ++i) {
248 maskNode->getChild(i)->removeChangeListener(this);
251 fgGetNode("/sim/rendering/draw-otw")->removeChangeListener(this);
252 fgGetNode("/environment/clouds/status")->removeChangeListener(this);
255 virtual void valueChanged (SGPropertyNode * node)
257 bool b = node->getBoolValue();
258 std::string name(node->getNameString());
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);
281 ////////////////////////////////////////////////////////////////////////////
283 // Scenery Management system
284 FGScenery::FGScenery() :
287 // keep reference to pager singleton, so it cannot be destroyed while FGScenery lives
288 _pager = FGScenery::getPagerSingleton();
290 // Initialise the state of the scene graph.
294 FGScenery::~FGScenery()
300 // Initialize the Scenery Management system
301 void FGScenery::init() {
307 scene_graph = new osg::Switch;
308 scene_graph->setName( "FGScenery" );
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);
318 models_branch = new osg::Group;
319 models_branch->setName( "Models" );
320 scene_graph->addChild( models_branch.get() );
322 aircraft_branch = new osg::Group;
323 aircraft_branch->setName( "Aircraft" );
324 scene_graph->addChild( aircraft_branch.get() );
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" );
333 osg::LOD* interiorLOD = new osg::LOD;
334 interiorLOD->addChild(interior_branch.get(), 0.0, 50.0);
335 aircraft_branch->addChild( interiorLOD );
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));
343 // Set up the precipitation system.
344 precipitation_branch = new osg::Group;
345 precipitation_branch->setName("Precipitation");
346 scene_graph->addChild(precipitation_branch.get());
348 _listener = new ScenerySwitchListener(this);
350 // Toggle the setup flag.
354 void FGScenery::shutdown()
357 terrain_branch = NULL;
358 models_branch = NULL;
359 aircraft_branch = NULL;
360 particles_branch = NULL;
361 precipitation_branch = NULL;
363 // Toggle the setup flag.
368 void FGScenery::update(double dt)
371 // nothing here, don't call again
376 void FGScenery::bind() {
380 void FGScenery::unbind() {
384 FGScenery::get_cart_elevation_m(const SGVec3d& pos, double max_altoff,
386 const simgear::BVHMaterial** material,
387 const osg::Node* butNotFrom)
389 SGGeod geod = SGGeod::fromCart(pos);
390 geod.setElevationM(geod.getElevationM() + max_altoff);
391 return get_elevation_m(geod, alt, material, butNotFrom);
395 FGScenery::get_elevation_m(const SGGeod& geod, double& alt,
396 const simgear::BVHMaterial** material,
397 const osg::Node* butNotFrom)
399 SGVec3d start = SGVec3d::fromGeod(geod);
401 SGGeod geodEnd = geod;
402 geodEnd.setElevationM(SGMiscd::min(geod.getElevationM() - 10, -10000));
403 SGVec3d end = SGVec3d::fromGeod(geodEnd);
405 FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
406 intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
407 get_scene_graph()->accept(intersectVisitor);
409 if (!intersectVisitor.getHaveHit())
412 geodEnd = SGGeod::fromCart(intersectVisitor.getLineSegment().getEnd());
413 alt = geodEnd.getElevationM();
415 *material = intersectVisitor.getMaterial();
421 FGScenery::get_cart_ground_intersection(const SGVec3d& pos, const SGVec3d& dir,
423 const osg::Node* butNotFrom)
425 // We assume that starting positions in the center of the earth are invalid
426 if ( norm1(pos) < 1 )
429 // Make really sure the direction is normalized, is really cheap compared to
430 // computation of ground intersection.
432 SGVec3d end = start + 1e5*normalize(dir); // FIXME visibility ???
434 FGSceneryIntersect intersectVisitor(SGLineSegmentd(start, end), butNotFrom);
435 intersectVisitor.setTraversalMask(SG_NODEMASK_TERRAIN_BIT);
436 get_scene_graph()->accept(intersectVisitor);
438 if (!intersectVisitor.getHaveHit())
441 nearestHit = intersectVisitor.getLineSegment().getEnd();
445 bool FGScenery::scenery_available(const SGGeod& position, double range_m)
447 if(globals->get_tile_mgr()->schedule_scenery(position, range_m, 0.0))
450 if (!get_elevation_m(SGGeod::fromGeodM(position, SG_MAX_ELEVATION_M), elev, 0, 0))
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");
466 SG_LOG(SG_TERRAIN, SG_DEBUG, "FGScenery::scenery_available: waiting on tile manager");
471 static osg::ref_ptr<SceneryPager> pager;
473 SceneryPager* FGScenery::getPagerSingleton()
476 pager = new SceneryPager;
480 void FGScenery::resetPagerSingleton()