1 // tileentry.cxx -- routines to handle a scenery tile
3 // Written by Curtis Olson, started May 1998.
5 // Copyright (C) 1998 - 2001 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.
22 # include <simgear_config.h>
25 #include <simgear/compiler.h>
33 #include <osg/Geometry>
36 #include <osg/MatrixTransform>
38 #include <osg/NodeCallback>
41 #include <osgDB/FileNameUtils>
42 #include <osgDB/ReaderWriter>
43 #include <osgDB/ReadFile>
44 #include <osgDB/Registry>
46 #include <simgear/bucket/newbucket.hxx>
47 #include <simgear/debug/logstream.hxx>
48 #include <simgear/math/sg_geodesy.hxx>
49 #include <simgear/math/sg_random.h>
50 #include <simgear/math/SGMath.hxx>
51 #include <simgear/misc/sgstream.hxx>
52 #include <simgear/scene/material/mat.hxx>
53 #include <simgear/scene/material/matlib.hxx>
54 #include <simgear/scene/model/ModelRegistry.hxx>
55 #include <simgear/scene/tgdb/apt_signs.hxx>
56 #include <simgear/scene/tgdb/obj.hxx>
57 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
58 #include <simgear/scene/model/placementtrans.hxx>
59 #include <simgear/scene/util/SGUpdateVisitor.hxx>
61 #include "ReaderWriterSTG.hxx"
62 #include "TileEntry.hxx"
65 using namespace simgear;
67 ModelLoadHelper *TileEntry::_modelLoader=0;
70 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
71 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
74 // FIXME: investigate what huge update flood is clamped away here ...
75 class FGTileUpdateCallback : public osg::NodeCallback {
77 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
79 assert(dynamic_cast<SGUpdateVisitor*>(nv));
80 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
82 osg::Vec3 center = node->getBound().center();
83 double distance = dist(updateVisitor->getGlobalEyePos(),
84 SGVec3d(center[0], center[1], center[2]));
85 if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
94 // Update the timestamp on a tile whenever it is in view.
96 class TileCullCallback : public osg::NodeCallback
99 TileCullCallback() : _timeStamp(0) {}
100 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
101 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
105 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
106 double getTimeStamp() const { return _timeStamp; }
107 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
113 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
115 if (nv->getFrameStamp())
116 _timeStamp = nv->getFrameStamp()->getReferenceTime();
120 double TileEntry::get_timestamp() const
123 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
129 void TileEntry::set_timestamp(double time_ms)
133 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
135 cb->setTimeStamp(time_ms);
140 TileEntry::TileEntry ( const SGBucket& b )
142 _node( new osg::LOD ),
143 is_inner_ring(false),
145 tileFileName(b.gen_index_str())
147 _node->setUpdateCallback(new FGTileUpdateCallback);
148 _node->setCullCallback(new TileCullCallback);
149 tileFileName += ".stg";
150 _node->setName(tileFileName);
151 // Give a default LOD range so that traversals that traverse
152 // active children (like the groundcache lookup) will work before
153 // tile manager has had a chance to update this node.
154 _node->setRange(0, 0.0, 10000.0);
159 TileEntry::~TileEntry ()
163 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
164 double lon, double elev, double hdg)
166 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
167 obj_pos = geod.makeZUpFrame();
168 // hdg is not a compass heading, but a counter-clockwise rotation
170 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
175 // Free "n" leaf elements of an ssg tree. returns the number of
176 // elements freed. An empty branch node is considered a leaf. This
177 // is intended to spread the load of freeing a complex tile out over
179 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
180 int num_deletes = b->getNumChildren();
182 b->removeChildren(0, b->getNumChildren());
188 // Clean up the memory used by this tile and delete the arrays used by
189 // ssg as well as the whole ssg branch
190 bool TileEntry::free_tile() {
191 int delete_size = 100;
192 SG_LOG( SG_TERRAIN, SG_DEBUG,
193 "FREEING TILE = (" << tile_bucket << ")" );
195 SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
197 if ( !(free_tracker & NODES) ) {
198 free_tracker |= NODES;
199 } else if ( !(free_tracker & VEC_PTRS) ) {
200 free_tracker |= VEC_PTRS;
201 } else if ( !(free_tracker & TERRA_NODE) ) {
202 // delete the terrain branch (this should already have been
203 // disconnected from the scene graph)
204 SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
205 if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
207 free_tracker |= TERRA_NODE;
209 } else if ( !(free_tracker & LIGHTMAPS) ) {
210 free_tracker |= LIGHTMAPS;
215 SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
217 // if we fall down to here, we still have work todo, return false
222 // Update the ssg transform node for this tile so it can be
223 // properly drawn relative to our (0,0,0) point
224 void TileEntry::prep_ssg_node(float vis) {
227 // visibility can change from frame to frame so we update the
228 // range selector cutoff's each time.
229 float bounding_radius = _node->getChild(0)->getBound().radius();
230 _node->setRange( 0, 0, vis + bounding_radius );
233 bool TileEntry::obj_load( const string& path,
234 osg::Group *geometry, bool is_base, const osgDB::ReaderWriter::Options*options)
236 osg::Node* node = osgDB::readNodeFile(path, options);
238 geometry->addChild(node);
253 // storage class for deferred object processing in TileEntry::load()
255 Object(object_type t, const string& token, const SGPath& p,
261 in >> lon >> lat >> elev >> hdg;
265 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
267 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
268 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
273 double lon, lat, elev, hdg;
276 // Work in progress... load the tile based entirely by name cuz that's
277 // what we'll want to do with the database pager.
280 TileEntry::loadTileByName(const string& index_str,
281 const osgDB::ReaderWriter::Options* options)
285 std::istringstream idxStream(index_str);
286 idxStream >> tileIndex;
288 SGBucket tile_bucket(tileIndex);
289 const string basePath = tile_bucket.gen_base_path();
291 bool found_tile_base = false;
294 vector<const Object*> objects;
296 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
298 osgDB::FilePathList path_list=options->getDatabasePathList();
300 // scan and parse all files and store information
301 for (unsigned int i = 0; i < path_list.size(); i++) {
302 // If we found a terrain tile in Terrain/, we have to process the
303 // Objects/ dir in the same group, too, before we can stop scanning.
304 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
307 if (path_list[i].empty()) {
314 bool has_base = false;
316 SGPath tile_path = path_list[i];
317 tile_path.append(basePath);
319 SGPath basename = tile_path;
320 basename.append( index_str );
322 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
325 // Check for master .stg (scene terra gear) file
326 SGPath stg_name = basename;
327 stg_name.concat( ".stg" );
329 sg_gzifstream in( stg_name.str() );
333 while ( ! in.eof() ) {
337 if ( token.empty() || token[0] == '#' ) {
341 // Load only once (first found)
342 if ( token == "OBJECT_BASE" ) {
344 in >> name >> ::skipws;
345 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
347 if (!found_tile_base) {
348 found_tile_base = true;
351 object_base = tile_path;
352 object_base.append(name);
355 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
357 // Load only if base is not in another file
358 } else if ( token == "OBJECT" ) {
359 if (!found_tile_base || has_base)
360 objects.push_back(new Object(OBJECT, token, tile_path, in));
363 in >> name >> ::skipeol;
364 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
365 << name << " (skipped)");
369 } else if ( token == "OBJECT_STATIC" ) {
370 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
372 } else if ( token == "OBJECT_SHARED" ) {
373 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
375 } else if ( token == "OBJECT_SIGN" ) {
376 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
378 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
379 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
382 SG_LOG( SG_TERRAIN, SG_DEBUG,
383 "Unknown token '" << token << "' in " << stg_name.str() );
389 SGReaderWriterBTGOptions *opt = new SGReaderWriterBTGOptions(*dynamic_cast<const SGReaderWriterBTGOptions *>(options));
391 // obj_load() will generate ground lighting for us ...
392 osg::Group* new_tile = new osg::Group;
394 if (found_tile_base) {
395 // load tile if found ...
396 opt->setCalcLights(true);
397 obj_load( object_base.str(), new_tile, true, options);
400 // ... or generate an ocean tile on the fly
401 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
402 if ( !SGGenTile( path_list[0], tile_bucket,
403 opt->getMatlib(), new_tile ) ) {
404 SG_LOG( SG_TERRAIN, SG_ALERT,
405 "Warning: failed to generate ocean tile!" );
410 // now that we have a valid center, process all the objects
411 for (unsigned int j = 0; j < objects.size(); j++) {
412 const Object *obj = objects[j];
414 if (obj->type == OBJECT) {
415 SGPath custom_path = obj->path;
416 custom_path.append( obj->name );
417 opt->setCalcLights(true);
418 obj_load( custom_path.str(), new_tile, false, options);
420 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
421 // object loading is deferred to main render thread,
422 // but lets figure out the paths right now.
424 if ( obj->type == OBJECT_STATIC ) {
425 custom_path = obj->path;
427 // custom_path = globals->get_fg_root();
429 custom_path.append( obj->name );
432 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
434 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
435 obj_trans->setMatrix( obj_pos );
437 // wire as much of the scene graph together as we can
438 new_tile->addChild( obj_trans );
440 osg::Node* model = 0;
442 model = _modelLoader->loadTileModel(custom_path.str(),
443 obj->type == OBJECT_SHARED);
445 obj_trans->addChild(model);
446 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
447 // load the object itself
448 SGPath custom_path = obj->path;
449 custom_path.append( obj->name );
452 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
454 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
455 obj_trans->setMatrix( obj_pos );
457 osg::Node *custom_obj = 0;
458 if (obj->type == OBJECT_SIGN)
459 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
461 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
463 // wire the pieces together
464 if ( custom_obj != NULL ) {
465 obj_trans -> addChild( custom_obj );
467 new_tile->addChild( obj_trans );
476 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
478 terrain_branch->addChild( _node.get() );
480 SG_LOG( SG_TERRAIN, SG_DEBUG,
481 "connected a tile into scene graph. _node = "
483 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
484 << _node->getNumParents() );
489 TileEntry::removeFromSceneGraph()
491 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
494 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
496 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
499 // find the nodes branch parent
500 if ( _node->getNumParents() > 0 ) {
501 // find the first parent (should only be one)
502 osg::Group *parent = _node->getParent( 0 ) ;
504 parent->removeChild( _node.get() );