]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
Fix line endings
[simgear.git] / simgear / scene / tgdb / TileEntry.cxx
1 // tileentry.cxx -- routines to handle a scenery tile
2 //
3 // Written by Curtis Olson, started May 1998.
4 //
5 // Copyright (C) 1998 - 2001  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 #ifdef HAVE_CONFIG_H
22 #  include <simgear_config.h>
23 #endif
24
25 #include <simgear/compiler.h>
26
27 #include <string>
28 #include <sstream>
29 #include <istream>
30
31 #include <osg/LOD>
32 #include <osg/MatrixTransform>
33 #include <osg/Math>
34 #include <osg/NodeCallback>
35
36 #include <osgDB/FileNameUtils>
37 #include <osgDB/ReaderWriter>
38 #include <osgDB/ReadFile>
39 #include <osgDB/Registry>
40
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>
53
54 #include "ReaderWriterSTG.hxx"
55 #include "TileEntry.hxx"
56
57 using std::string;
58 using namespace simgear;
59
60 ModelLoadHelper *TileEntry::_modelLoader=0;
61
62 namespace {
63 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
64 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
65 }
66
67 #ifdef USE_CULLCALLBACK_TS
68 namespace
69 {
70 // Update the timestamp on a tile whenever it is in view.
71
72 class TileCullCallback : public osg::NodeCallback
73 {
74 public:
75     TileCullCallback() : _timeStamp(0) {}
76     TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
77         NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
78     {
79     }
80
81     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
82     double getTimeStamp() const { return _timeStamp; }
83     void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
84 protected:
85     double _timeStamp;
86 };
87 }
88
89 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
90 {
91     if (nv->getFrameStamp())
92         _timeStamp = nv->getFrameStamp()->getReferenceTime();
93     traverse(node, nv);
94 }
95 #endif
96
97 double TileEntry::get_timestamp() const
98 {
99 #ifdef USE_CULLCALLBACK_TS
100     if (_node.valid()) {
101         return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
102             ->getTimeStamp();
103     } else
104         return DBL_MAX;
105 #else
106     return timestamp;
107 #endif
108 }
109
110 void TileEntry::set_timestamp(double time_ms)
111 {
112 #ifdef USE_CULLCALLBACK_TS
113     if (_node.valid()) {
114         TileCullCallback* cb
115             = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
116         if (cb)
117             cb->setTimeStamp(time_ms);
118     }
119 #else
120     timestamp = time_ms;
121 #endif
122 }
123
124 // Constructor
125 TileEntry::TileEntry ( const SGBucket& b )
126     : tile_bucket( b ),
127       tileFileName(b.gen_index_str()),
128       _node( new osg::LOD ),
129       is_inner_ring(false)
130       ,is_cache_locked(false)
131 #ifndef USE_CULLCALLBACK_TS
132       ,timestamp(0.0)
133 #endif
134 {
135 #ifdef USE_CULLCALLBACK_TS
136     _node->setCullCallback(new TileCullCallback);
137 #endif
138     tileFileName += ".stg";
139     _node->setName(tileFileName);
140     // Give a default LOD range so that traversals that traverse
141     // active children (like the groundcache lookup) will work before
142     // tile manager has had a chance to update this node.
143     _node->setRange(0, 0.0, 10000.0);
144 }
145
146
147 // Destructor
148 TileEntry::~TileEntry ()
149 {
150 }
151
152 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
153                             double lon, double elev, double hdg)
154 {
155     SGGeod geod = SGGeod::fromDegM(lon, lat, elev);
156     obj_pos = geod.makeZUpFrame();
157     // hdg is not a compass heading, but a counter-clockwise rotation
158     // around the Z axis
159     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
160                                         0.0, 0.0, 1.0));
161 }
162
163
164 // Update the ssg transform node for this tile so it can be
165 // properly drawn relative to our (0,0,0) point
166 void TileEntry::prep_ssg_node(float vis) {
167     if (!is_loaded())
168         return;
169     // visibility can change from frame to frame so we update the
170     // range selector cutoff's each time.
171     float bounding_radius = _node->getChild(0)->getBound().radius();
172     _node->setRange( 0, 0, vis + bounding_radius );
173 }
174
175 bool TileEntry::obj_load(const string& path, osg::Group *geometry, bool is_base,
176                          const osgDB::ReaderWriter::Options* options)
177 {
178     osg::Node* node = osgDB::readNodeFile(path, options);
179     if (node)
180       geometry->addChild(node);
181
182     return node != 0;
183 }
184
185
186 typedef enum {
187     OBJECT,
188     OBJECT_SHARED,
189     OBJECT_STATIC,
190     OBJECT_SIGN,
191     OBJECT_RUNWAY_SIGN
192 } object_type;
193
194
195 // storage class for deferred object processing in TileEntry::load()
196 struct Object {
197     Object(object_type t, const string& token, const SGPath& p,
198            std::istream& in)
199         : type(t), path(p)
200     {
201         in >> name;
202         if (type != OBJECT)
203             in >> lon >> lat >> elev >> hdg;
204         in >> ::skipeol;
205
206         if (type == OBJECT)
207             SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  " << name);
208         else
209             SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  " << name << "  lon=" <<
210                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
211     }
212     object_type type;
213     string name;
214     SGPath path;
215     double lon, lat, elev, hdg;
216 };
217
218 // Work in progress... load the tile based entirely by name cuz that's
219 // what we'll want to do with the database pager.
220
221 osg::Node*
222 TileEntry::loadTileByFileName(const string& fileName,
223                               const osgDB::ReaderWriter::Options* options)
224 {
225     std::string index_str = osgDB::getNameLessExtension(fileName);
226     index_str = osgDB::getSimpleFileName(index_str);
227
228     long tileIndex;
229     {
230         std::istringstream idxStream(index_str);
231         idxStream >> tileIndex;
232     }
233     SGBucket tile_bucket(tileIndex);
234     const string basePath = tile_bucket.gen_base_path();
235
236     bool found_tile_base = false;
237
238     SGPath object_base;
239     vector<const Object*> objects;
240
241     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
242
243     osgDB::FilePathList path_list=options->getDatabasePathList();
244     // Make sure we find the original filename here...
245     std::string filePath = osgDB::getFilePath(fileName);
246     if (!filePath.empty())
247         path_list.push_front(filePath);
248
249     // scan and parse all files and store information
250     for (unsigned int i = 0; i < path_list.size(); i++) {
251         // If we found a terrain tile in Terrain/, we have to process the
252         // Objects/ dir in the same group, too, before we can stop scanning.
253         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
254         // as marker.
255
256         if (path_list[i].empty()) {
257             if (found_tile_base)
258                 break;
259             else
260                 continue;
261         }
262
263         bool has_base = false;
264
265         SGPath tile_path = path_list[i];
266         tile_path.append(basePath);
267
268         SGPath basename = tile_path;
269         basename.append( index_str );
270
271         SG_LOG( SG_TERRAIN, SG_DEBUG, "  Trying " << basename.str() );
272
273
274         // Check for master .stg (scene terra gear) file
275         SGPath stg_name = basename;
276         stg_name.concat( ".stg" );
277
278         sg_gzifstream in( stg_name.str() );
279         if ( !in.is_open() )
280             continue;
281
282         while ( ! in.eof() ) {
283             string token;
284             in >> token;
285
286             if ( token.empty() || token[0] == '#' ) {
287                in >> ::skipeol;
288                continue;
289             }
290                             // Load only once (first found)
291             if ( token == "OBJECT_BASE" ) {
292                 string name;
293                 in >> name >> ::skipws;
294                 SG_LOG( SG_TERRAIN, SG_BULK, "    " << token << " " << name );
295
296                 if (!found_tile_base) {
297                     found_tile_base = true;
298                     has_base = true;
299
300                     object_base = tile_path;
301                     object_base.append(name);
302
303                 } else
304                     SG_LOG(SG_TERRAIN, SG_BULK, "    (skipped)");
305
306                             // Load only if base is not in another file
307             } else if ( token == "OBJECT" ) {
308                 if (!found_tile_base || has_base)
309                     objects.push_back(new Object(OBJECT, token, tile_path, in));
310                 else {
311                     string name;
312                     in >> name >> ::skipeol;
313                     SG_LOG(SG_TERRAIN, SG_BULK, "    " << token << "  "
314                             << name << "  (skipped)");
315                 }
316
317                             // Always OK to load
318             } else if ( token == "OBJECT_STATIC" ) {
319                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
320
321             } else if ( token == "OBJECT_SHARED" ) {
322                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
323
324             } else if ( token == "OBJECT_SIGN" ) {
325                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
326
327             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
328                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
329
330             } else {
331                 SG_LOG( SG_TERRAIN, SG_DEBUG,
332                         "Unknown token '" << token << "' in " << stg_name.str() );
333                 in >> ::skipws;
334             }
335         }
336     }
337
338     const SGReaderWriterBTGOptions* btgOpt;
339     btgOpt = dynamic_cast<const SGReaderWriterBTGOptions *>(options);
340     osg::ref_ptr<SGReaderWriterBTGOptions> opt;
341     if (btgOpt)
342         opt = new SGReaderWriterBTGOptions(*btgOpt);
343     else
344         opt = new SGReaderWriterBTGOptions;
345
346     // obj_load() will generate ground lighting for us ...
347     osg::Group* new_tile = new osg::Group;
348
349     if (found_tile_base) {
350         // load tile if found ...
351         opt->setCalcLights(true);
352         obj_load( object_base.str(), new_tile, true, opt.get());
353
354     } else {
355         // ... or generate an ocean tile on the fly
356         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
357         if ( !SGGenTile( path_list[0], tile_bucket,
358                         opt->getMatlib(), new_tile ) ) {
359             SG_LOG( SG_TERRAIN, SG_ALERT,
360                     "Warning: failed to generate ocean tile!" );
361         }
362     }
363
364
365     // now that we have a valid center, process all the objects
366     for (unsigned int j = 0; j < objects.size(); j++) {
367         const Object *obj = objects[j];
368
369         if (obj->type == OBJECT) {
370             SGPath custom_path = obj->path;
371             custom_path.append( obj->name );
372             opt->setCalcLights(true);
373             obj_load( custom_path.str(), new_tile, false, opt.get());
374
375         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
376             // object loading is deferred to main render thread,
377             // but lets figure out the paths right now.
378             SGPath custom_path;
379             if ( obj->type == OBJECT_STATIC ) {
380                 custom_path = obj->path;
381             } else {
382                 // custom_path = globals->get_fg_root();
383             }
384             custom_path.append( obj->name );
385
386             osg::Matrix obj_pos;
387             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
388
389             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
390             obj_trans->setDataVariance(osg::Object::STATIC);
391             obj_trans->setMatrix( obj_pos );
392
393             // wire as much of the scene graph together as we can
394             new_tile->addChild( obj_trans );
395
396             osg::Node* model = 0;
397             if(_modelLoader)
398                 model = _modelLoader->loadTileModel(custom_path.str(),
399                                                     obj->type == OBJECT_SHARED);
400             if (model)
401                 obj_trans->addChild(model);
402         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
403             // load the object itself
404             SGPath custom_path = obj->path;
405             custom_path.append( obj->name );
406
407             osg::Matrix obj_pos;
408             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
409
410             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
411             obj_trans->setDataVariance(osg::Object::STATIC);
412             obj_trans->setMatrix( obj_pos );
413
414             osg::Node *custom_obj = 0;
415             if (obj->type == OBJECT_SIGN)
416                 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
417             else
418                 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
419
420             // wire the pieces together
421             if ( custom_obj != NULL ) {
422                 obj_trans -> addChild( custom_obj );
423             }
424             new_tile->addChild( obj_trans );
425
426         }
427         delete obj;
428     }
429     return new_tile;
430 }
431
432 void
433 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
434 {
435     terrain_branch->addChild( _node.get() );
436
437     SG_LOG( SG_TERRAIN, SG_DEBUG,
438             "connected a tile into scene graph.  _node = "
439             << _node.get() );
440     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
441             << _node->getNumParents() );
442 }
443
444
445 void
446 TileEntry::removeFromSceneGraph()
447 {
448     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
449
450     if (! is_loaded()) {
451         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
452     } else {
453         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
454     }
455
456     // find the nodes branch parent
457     if ( _node->getNumParents() > 0 ) {
458         // find the first parent (should only be one)
459         osg::Group *parent = _node->getParent( 0 ) ;
460         if( parent ) {
461             parent->removeChild( _node.get() );
462         }
463     }
464 }
465