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>
32 #include <osg/MatrixTransform>
34 #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/sg_geodesy.hxx>
44 #include <simgear/math/sg_random.h>
45 #include <simgear/math/SGMath.hxx>
46 #include <simgear/misc/sgstream.hxx>
47 #include <simgear/scene/material/mat.hxx>
48 #include <simgear/scene/material/matlib.hxx>
49 #include <simgear/scene/model/ModelRegistry.hxx>
50 #include <simgear/scene/tgdb/apt_signs.hxx>
51 #include <simgear/scene/tgdb/obj.hxx>
52 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
54 #include "ReaderWriterSTG.hxx"
55 #include "TileEntry.hxx"
58 using namespace simgear;
60 ModelLoadHelper *TileEntry::_modelLoader=0;
63 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
64 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
69 // Update the timestamp on a tile whenever it is in view.
71 class TileCullCallback : public osg::NodeCallback
74 TileCullCallback() : _timeStamp(0) {}
75 TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
76 NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
80 virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
81 double getTimeStamp() const { return _timeStamp; }
82 void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
88 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
90 if (nv->getFrameStamp())
91 _timeStamp = nv->getFrameStamp()->getReferenceTime();
95 double TileEntry::get_timestamp() const
98 return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
104 void TileEntry::set_timestamp(double time_ms)
108 = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
110 cb->setTimeStamp(time_ms);
115 TileEntry::TileEntry ( const SGBucket& b )
117 tileFileName(b.gen_index_str()),
118 _node( new osg::LOD ),
121 _node->setCullCallback(new TileCullCallback);
122 tileFileName += ".stg";
123 _node->setName(tileFileName);
124 // Give a default LOD range so that traversals that traverse
125 // active children (like the groundcache lookup) will work before
126 // tile manager has had a chance to update this node.
127 _node->setRange(0, 0.0, 10000.0);
132 TileEntry::~TileEntry ()
136 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
137 double lon, double elev, double hdg)
139 SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
140 obj_pos = geod.makeZUpFrame();
141 // hdg is not a compass heading, but a counter-clockwise rotation
143 obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
148 // Update the ssg transform node for this tile so it can be
149 // properly drawn relative to our (0,0,0) point
150 void TileEntry::prep_ssg_node(float vis) {
153 // visibility can change from frame to frame so we update the
154 // range selector cutoff's each time.
155 float bounding_radius = _node->getChild(0)->getBound().radius();
156 _node->setRange( 0, 0, vis + bounding_radius );
159 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
160 const osgDB::ReaderWriter::Options* options)
162 osg::Node* node = osgDB::readNodeFile(path, options);
164 geometry->addChild(node);
179 // storage class for deferred object processing in TileEntry::load()
181 Object(object_type t, const string& token, const SGPath& p,
187 in >> lon >> lat >> elev >> hdg;
191 SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name);
193 SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " " << name << " lon=" <<
194 lon << " lat=" << lat << " elev=" << elev << " hdg=" << hdg);
199 double lon, lat, elev, hdg;
202 // Work in progress... load the tile based entirely by name cuz that's
203 // what we'll want to do with the database pager.
206 TileEntry::loadTileByFileName(const string& fileName,
207 const osgDB::ReaderWriter::Options* options)
209 std::string index_str = osgDB::getNameLessExtension(fileName);
210 index_str = osgDB::getSimpleFileName(index_str);
214 std::istringstream idxStream(index_str);
215 idxStream >> tileIndex;
217 SGBucket tile_bucket(tileIndex);
218 const string basePath = tile_bucket.gen_base_path();
220 bool found_tile_base = false;
223 vector<const Object*> objects;
225 SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
227 osgDB::FilePathList path_list=options->getDatabasePathList();
228 // Make sure we find the original filename here...
229 std::string filePath = osgDB::getFilePath(fileName);
230 if (!filePath.empty())
231 path_list.push_front(filePath);
233 // scan and parse all files and store information
234 for (unsigned int i = 0; i < path_list.size(); i++) {
235 // If we found a terrain tile in Terrain/, we have to process the
236 // Objects/ dir in the same group, too, before we can stop scanning.
237 // FGGlobals::set_fg_scenery() inserts an empty string to path_list
240 if (path_list[i].empty()) {
247 bool has_base = false;
249 SGPath tile_path = path_list[i];
250 tile_path.append(basePath);
252 SGPath basename = tile_path;
253 basename.append( index_str );
255 SG_LOG( SG_TERRAIN, SG_DEBUG, " Trying " << basename.str() );
258 // Check for master .stg (scene terra gear) file
259 SGPath stg_name = basename;
260 stg_name.concat( ".stg" );
262 sg_gzifstream in( stg_name.str() );
266 while ( ! in.eof() ) {
270 if ( token.empty() || token[0] == '#' ) {
274 // Load only once (first found)
275 if ( token == "OBJECT_BASE" ) {
277 in >> name >> ::skipws;
278 SG_LOG( SG_TERRAIN, SG_BULK, " " << token << " " << name );
280 if (!found_tile_base) {
281 found_tile_base = true;
284 object_base = tile_path;
285 object_base.append(name);
288 SG_LOG(SG_TERRAIN, SG_BULK, " (skipped)");
290 // Load only if base is not in another file
291 } else if ( token == "OBJECT" ) {
292 if (!found_tile_base || has_base)
293 objects.push_back(new Object(OBJECT, token, tile_path, in));
296 in >> name >> ::skipeol;
297 SG_LOG(SG_TERRAIN, SG_BULK, " " << token << " "
298 << name << " (skipped)");
302 } else if ( token == "OBJECT_STATIC" ) {
303 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
305 } else if ( token == "OBJECT_SHARED" ) {
306 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
308 } else if ( token == "OBJECT_SIGN" ) {
309 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
311 } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
312 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
315 SG_LOG( SG_TERRAIN, SG_DEBUG,
316 "Unknown token '" << token << "' in " << stg_name.str() );
322 const SGReaderWriterBTGOptions* btgOpt;
323 btgOpt = dynamic_cast<const SGReaderWriterBTGOptions *>(options);
324 osg::ref_ptr<SGReaderWriterBTGOptions> opt;
326 opt = new SGReaderWriterBTGOptions(*btgOpt);
328 opt = new SGReaderWriterBTGOptions;
330 // obj_load() will generate ground lighting for us ...
331 osg::Group* new_tile = new osg::Group;
333 if (found_tile_base) {
334 // load tile if found ...
335 opt->setCalcLights(true);
336 obj_load( object_base.str(), new_tile, true, opt);
339 // ... or generate an ocean tile on the fly
340 SG_LOG(SG_TERRAIN, SG_INFO, " Generating ocean tile");
341 if ( !SGGenTile( path_list[0], tile_bucket,
342 opt->getMatlib(), new_tile ) ) {
343 SG_LOG( SG_TERRAIN, SG_ALERT,
344 "Warning: failed to generate ocean tile!" );
349 // now that we have a valid center, process all the objects
350 for (unsigned int j = 0; j < objects.size(); j++) {
351 const Object *obj = objects[j];
353 if (obj->type == OBJECT) {
354 SGPath custom_path = obj->path;
355 custom_path.append( obj->name );
356 opt->setCalcLights(true);
357 obj_load( custom_path.str(), new_tile, false, opt);
359 } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
360 // object loading is deferred to main render thread,
361 // but lets figure out the paths right now.
363 if ( obj->type == OBJECT_STATIC ) {
364 custom_path = obj->path;
366 // custom_path = globals->get_fg_root();
368 custom_path.append( obj->name );
371 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
373 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
374 obj_trans->setDataVariance(osg::Object::STATIC);
375 obj_trans->setMatrix( obj_pos );
377 // wire as much of the scene graph together as we can
378 new_tile->addChild( obj_trans );
380 osg::Node* model = 0;
382 model = _modelLoader->loadTileModel(custom_path.str(),
383 obj->type == OBJECT_SHARED);
385 obj_trans->addChild(model);
386 } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
387 // load the object itself
388 SGPath custom_path = obj->path;
389 custom_path.append( obj->name );
392 WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
394 osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
395 obj_trans->setDataVariance(osg::Object::STATIC);
396 obj_trans->setMatrix( obj_pos );
398 osg::Node *custom_obj = 0;
399 if (obj->type == OBJECT_SIGN)
400 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
402 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
404 // wire the pieces together
405 if ( custom_obj != NULL ) {
406 obj_trans -> addChild( custom_obj );
408 new_tile->addChild( obj_trans );
417 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
419 terrain_branch->addChild( _node.get() );
421 SG_LOG( SG_TERRAIN, SG_DEBUG,
422 "connected a tile into scene graph. _node = "
424 SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
425 << _node->getNumParents() );
430 TileEntry::removeFromSceneGraph()
432 SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
435 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
437 SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile! _node = " << _node.get() );
440 // find the nodes branch parent
441 if ( _node->getNumParents() > 0 ) {
442 // find the first parent (should only be one)
443 osg::Group *parent = _node->getParent( 0 ) ;
445 parent->removeChild( _node.get() );