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.
21 #include <simgear/compiler.h>
28 #include <osg/Geometry>
31 #include <osg/MatrixTransform>
33 #include <osg/NodeCallback>
36 #include <osgDB/FileNameUtils>
37 #include <osgDB/ReaderWriter>
38 #include <osgDB/ReadFile>
39 #include <osgDB/Registry>
41 #include <simgear/bucket/newbucket.hxx>
42 #include <simgear/debug/logstream.hxx>
43 #include <simgear/math/polar3d.hxx>
44 #include <simgear/math/sg_geodesy.hxx>
45 #include <simgear/math/sg_random.h>
46 #include <simgear/math/SGMath.hxx>
47 #include <simgear/misc/sgstream.hxx>
48 #include <simgear/scene/material/mat.hxx>
49 #include <simgear/scene/material/matlib.hxx>
50 #include <simgear/scene/model/ModelRegistry.hxx>
51 #include <simgear/scene/tgdb/apt_signs.hxx>
52 #include <simgear/scene/tgdb/obj.hxx>
53 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
54 #include <simgear/scene/model/placementtrans.hxx>
55 #include <simgear/scene/util/SGUpdateVisitor.hxx>
57 #include "ReaderWriterSTG.hxx"
58 #include "TileEntry.hxx"
61 using namespace simgear;
63 ModelLoadHelper *TileEntry::_modelLoader=0;
66 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
67 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
70 // FIXME: investigate what huge update flood is clamped away here ...
71 class FGTileUpdateCallback : public osg::NodeCallback {
73 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
75 assert(dynamic_cast<SGUpdateVisitor*>(nv));
76 SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
78 osg::Vec3 center = node->getBound().center();
79 double distance = dist(updateVisitor->getGlobalEyePos(),
80 SGVec3d(center[0], center[1], center[2]));
81 if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
90 // Update the timestamp on a tile whenever it is in view.
92 class TileCullCallback : public osg::NodeCallback
95 TileCullCallback() : _timeStamp(0) {}
96 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
97 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
101 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
102 double getTimeStamp() const { return _timeStamp; }
103 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
109 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
111 if (nv->getFrameStamp())
112 _timeStamp = nv->getFrameStamp()->getReferenceTime();
116 double TileEntry::get_timestamp() const
119 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
125 void TileEntry::set_timestamp(double time_ms)
129 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
131 cb->setTimeStamp(time_ms);
136 TileEntry::TileEntry ( const SGBucket& b )
138 _node( new osg::LOD ),
139 is_inner_ring(false),
141 tileFileName(b.gen_index_str())
143 _node->setUpdateCallback(new FGTileUpdateCallback);
144 _node->setCullCallback(new TileCullCallback);
145 tileFileName += ".stg";
146 _node->setName(tileFileName);
147 // Give a default LOD range so that traversals that traverse
148 // active children (like the groundcache lookup) will work before
149 // tile manager has had a chance to update this node.
150 _node->setRange(0, 0.0, 10000.0);
155 TileEntry::~TileEntry ()
159 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
160 double lon, double elev, double hdg)
162 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
163 obj_pos = geod.makeZUpFrame();
164 // hdg is not a compass heading, but a counter-clockwise rotation
166 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
171 // Free "n" leaf elements of an ssg tree. returns the number of
172 // elements freed. An empty branch node is considered a leaf. This
173 // is intended to spread the load of freeing a complex tile out over
175 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
176 int num_deletes = b->getNumChildren();
178 b->removeChildren(0, b->getNumChildren());
184 // Clean up the memory used by this tile and delete the arrays used by
185 // ssg as well as the whole ssg branch
186 bool TileEntry::free_tile() {
187 int delete_size = 100;
188 SG_LOG( SG_TERRAIN, SG_DEBUG,
189 "FREEING TILE = (" << tile_bucket << ")" );
191 SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
193 if ( !(free_tracker & NODES) ) {
194 free_tracker |= NODES;
195 } else if ( !(free_tracker & VEC_PTRS) ) {
196 free_tracker |= VEC_PTRS;
197 } else if ( !(free_tracker & TERRA_NODE) ) {
198 // delete the terrain branch (this should already have been
199 // disconnected from the scene graph)
200 SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
201 if ( fgPartialFreeSSGtree( _node.get(), delete_size ) == 0 ) {
203 free_tracker |= TERRA_NODE;
205 } else if ( !(free_tracker & LIGHTMAPS) ) {
206 free_tracker |= LIGHTMAPS;
211 SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
213 // if we fall down to here, we still have work todo, return false
218 // Update the ssg transform node for this tile so it can be
219 // properly drawn relative to our (0,0,0) point
220 void TileEntry::prep_ssg_node(float vis) {
223 // visibility can change from frame to frame so we update the
224 // range selector cutoff's each time.
225 float bounding_radius = _node->getChild(0)->getBound().radius();
226 _node->setRange( 0, 0, vis + bounding_radius );
229 bool TileEntry::obj_load( const string& path,
230 osg::Group *geometry, bool is_base, const osgDB::ReaderWriter::Options*options)
232 osg::Node* node = osgDB::readNodeFile(path, options);
234 geometry->addChild(node);
249 // storage class for deferred object processing in TileEntry::load()
251 Object(object_type t, const string& token, const SGPath& p, istream& in)
256 in >> lon >> lat >> elev >> hdg;
260 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name);
262 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " " << name << " lon=" <<
263 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
268 double lon, lat, elev, hdg;
271 // Work in progress... load the tile based entirely by name cuz that's
272 // what we'll want to do with the database pager.
275 TileEntry::loadTileByName(const string& index_str,
276 const osgDB::ReaderWriter::Options* options)
280 std::istringstream idxStream(index_str);
281 idxStream >> tileIndex;
283 SGBucket tile_bucket(tileIndex);
284 const string basePath = tile_bucket.gen_base_path();
286 bool found_tile_base = false;
289 vector<const Object*> objects;
291 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
293 osgDB::FilePathList path_list=options->getDatabasePathList();
295 // scan and parse all files and store information
296 for (unsigned int i = 0; i < path_list.size(); i++) {
297 // If we found a terrain tile in Terrain/, we have to process the
298 // Objects/ dir in the same group, too, before we can stop scanning.
299 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
302 if (path_list[i].empty()) {
309 bool has_base = false;
311 SGPath tile_path = path_list[i];
312 tile_path.append(basePath);
314 SGPath basename = tile_path;
315 basename.append( index_str );
317 SG_LOG( SG_TERRAIN, SG_INFO, " Trying " << basename.str() );
320 // Check for master .stg (scene terra gear) file
321 SGPath stg_name = basename;
322 stg_name.concat( ".stg" );
324 sg_gzifstream in( stg_name.str() );
328 while ( ! in.eof() ) {
332 if ( token.empty() || token[0] == '#' ) {
336 // Load only once (first found)
337 if ( token == "OBJECT_BASE" ) {
339 in >> name >> ::skipws;
340 SG_LOG( SG_TERRAIN, SG_INFO, " " << token << " " << name );
342 if (!found_tile_base) {
343 found_tile_base = true;
346 object_base = tile_path;
347 object_base.append(name);
350 SG_LOG(SG_TERRAIN, SG_INFO, " (skipped)");
352 // Load only if base is not in another file
353 } else if ( token == "OBJECT" ) {
354 if (!found_tile_base || has_base)
355 objects.push_back(new Object(OBJECT, token, tile_path, in));
358 in >> name >> ::skipeol;
359 SG_LOG(SG_TERRAIN, SG_INFO, " " << token << " "
360 << name << " (skipped)");
364 } else if ( token == "OBJECT_STATIC" ) {
365 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
367 } else if ( token == "OBJECT_SHARED" ) {
368 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
370 } else if ( token == "OBJECT_SIGN" ) {
371 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
373 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
374 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
377 SG_LOG( SG_TERRAIN, SG_DEBUG,
378 "Unknown token '" << token << "' in " << stg_name.str() );
384 SGReaderWriterBTGOptions *opt = new SGReaderWriterBTGOptions(*dynamic_cast<const SGReaderWriterBTGOptions *>(options));
386 // obj_load() will generate ground lighting for us ...
387 osg::Group* new_tile = new osg::Group;
389 if (found_tile_base) {
390 // load tile if found ...
391 opt->setCalcLights(true);
392 obj_load( object_base.str(), new_tile, true, options);
395 // ... or generate an ocean tile on the fly
396 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
397 if ( !SGGenTile( path_list[0], tile_bucket,
398 opt->getMatlib(), new_tile ) ) {
399 SG_LOG( SG_TERRAIN, SG_ALERT,
400 "Warning: failed to generate ocean tile!" );
405 // now that we have a valid center, process all the objects
406 for (unsigned int j = 0; j < objects.size(); j++) {
407 const Object *obj = objects[j];
409 if (obj->type == OBJECT) {
410 SGPath custom_path = obj->path;
411 custom_path.append( obj->name );
412 opt->setCalcLights(true);
413 obj_load( custom_path.str(), new_tile, false, options);
415 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
416 // object loading is deferred to main render thread,
417 // but lets figure out the paths right now.
419 if ( obj->type == OBJECT_STATIC ) {
420 custom_path = obj->path;
422 // custom_path = globals->get_fg_root();
424 custom_path.append( obj->name );
427 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
429 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
430 obj_trans->setMatrix( obj_pos );
432 // wire as much of the scene graph together as we can
433 new_tile->addChild( obj_trans );
435 osg::Node* model = 0;
437 model = _modelLoader->loadTileModel(custom_path.str(),
438 obj->type == OBJECT_SHARED);
440 obj_trans->addChild(model);
441 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
442 // load the object itself
443 SGPath custom_path = obj->path;
444 custom_path.append( obj->name );
447 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
449 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
450 obj_trans->setMatrix( obj_pos );
452 osg::Node *custom_obj = 0;
453 if (obj->type == OBJECT_SIGN)
454 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
456 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
458 // wire the pieces together
459 if ( custom_obj != NULL ) {
460 obj_trans -> addChild( custom_obj );
462 new_tile->addChild( obj_trans );
471 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
473 terrain_branch->addChild( _node.get() );
475 SG_LOG( SG_TERRAIN, SG_DEBUG,
476 "connected a tile into scene graph. _node = "
478 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
479 << _node->getNumParents() );
484 TileEntry::removeFromSceneGraph()
486 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
489 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
491 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
494 // find the nodes branch parent
495 if ( _node->getNumParents() > 0 ) {
496 // find the first parent (should only be one)
497 osg::Group *parent = _node->getParent( 0 ) ;
499 parent->removeChild( _node.get() );