]> git.mxchange.org Git - simgear.git/blob - simgear/scene/tgdb/TileEntry.cxx
sg: move most scenery-related code to simgear
[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 #include <simgear/compiler.h>
22 #include <plib/ul.h>
23
24 #include STL_STRING
25 #include <sstream>
26
27 #include <osg/Array>
28 #include <osg/Geometry>
29 #include <osg/Geode>
30 #include <osg/LOD>
31 #include <osg/MatrixTransform>
32 #include <osg/Math>
33 #include <osg/NodeCallback>
34 #include <osg/Switch>
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/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>
56
57 #include "ReaderWriterSTG.hxx"
58 #include "TileEntry.hxx"
59
60 SG_USING_STD(string);
61 using namespace simgear;
62
63 ModelLoadHelper *TileEntry::_modelLoader=0;
64
65 namespace {
66 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
67 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
68 }
69
70 // FIXME: investigate what huge update flood is clamped away here ...
71 class FGTileUpdateCallback : public osg::NodeCallback {
72 public:
73   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
74   {
75     assert(dynamic_cast<SGUpdateVisitor*>(nv));
76     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
77
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)
82       return;
83
84     traverse(node, nv);
85   }
86 };
87
88 namespace
89 {
90 // Update the timestamp on a tile whenever it is in view.
91
92 class TileCullCallback : public osg::NodeCallback
93 {
94 public:
95     TileCullCallback() : _timeStamp(0) {}
96     TileCullCallback(const TileCullCallback& tc, const osg::CopyOp& copyOp) :
97         NodeCallback(tc, copyOp), _timeStamp(tc._timeStamp)
98     {
99     }
100
101     virtual void operator()(osg::Node* node, osg::NodeVisitor* nv);
102     double getTimeStamp() const { return _timeStamp; }
103     void setTimeStamp(double timeStamp) { _timeStamp = timeStamp; }
104 protected:
105     double _timeStamp;
106 };
107 }
108
109 void TileCullCallback::operator()(osg::Node* node, osg::NodeVisitor* nv)
110 {
111     if (nv->getFrameStamp())
112         _timeStamp = nv->getFrameStamp()->getReferenceTime();
113     traverse(node, nv);
114 }
115
116 double TileEntry::get_timestamp() const
117 {
118     if (_node.valid()) {
119         return (dynamic_cast<TileCullCallback*>(_node->getCullCallback()))
120             ->getTimeStamp();
121     } else
122         return DBL_MAX;
123 }
124
125 void TileEntry::set_timestamp(double time_ms)
126 {
127     if (_node.valid()) {
128         TileCullCallback* cb
129             = dynamic_cast<TileCullCallback*>(_node->getCullCallback());
130         if (cb)
131             cb->setTimeStamp(time_ms);
132     }
133 }
134
135 // Constructor
136 TileEntry::TileEntry ( const SGBucket& b )
137     : tile_bucket( b ),
138       _node( new osg::LOD ),
139       is_inner_ring(false),
140       free_tracker(0),
141       tileFileName(b.gen_index_str())
142 {
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);
151 }
152
153
154 // Destructor
155 TileEntry::~TileEntry ()
156 {
157 }
158
159 static void WorldCoordinate(osg::Matrix& obj_pos, double lat,
160                             double lon, double elev, double hdg)
161 {
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
165     // around the Z axis
166     obj_pos.preMult(osg::Matrix::rotate(hdg * SGD_DEGREES_TO_RADIANS,
167                                         0.0, 0.0, 1.0));
168 }
169
170
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
174 // several frames.
175 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
176     int num_deletes = b->getNumChildren();
177
178     b->removeChildren(0, b->getNumChildren());
179
180     return num_deletes;
181 }
182
183
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 << ")" );
190
191     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
192
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 ) {
202             _node = 0;
203             free_tracker |= TERRA_NODE;
204         }
205     } else if ( !(free_tracker & LIGHTMAPS) ) {
206         free_tracker |= LIGHTMAPS;
207     } else {
208         return true;
209     }
210
211     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
212
213     // if we fall down to here, we still have work todo, return false
214     return false;
215 }
216
217
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) {
221     if (!is_loaded())
222         return;
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 );
227 }
228
229 bool TileEntry::obj_load( const string& path,
230                             osg::Group *geometry, bool is_base, const osgDB::ReaderWriter::Options*options)
231 {
232     osg::Node* node = osgDB::readNodeFile(path, options);
233     if (node)
234       geometry->addChild(node);
235
236     return node;
237 }
238
239
240 typedef enum {
241     OBJECT,
242     OBJECT_SHARED,
243     OBJECT_STATIC,
244     OBJECT_SIGN,
245     OBJECT_RUNWAY_SIGN
246 } object_type;
247
248
249 // storage class for deferred object processing in TileEntry::load()
250 struct Object {
251     Object(object_type t, const string& token, const SGPath& p, istream& in)
252         : type(t), path(p)
253     {
254         in >> name;
255         if (type != OBJECT)
256             in >> lon >> lat >> elev >> hdg;
257         in >> ::skipeol;
258
259         if (type == OBJECT)
260             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
261         else
262             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
263                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
264     }
265     object_type type;
266     string name;
267     SGPath path;
268     double lon, lat, elev, hdg;
269 };
270
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.
273
274 osg::Node*
275 TileEntry::loadTileByName(const string& index_str,
276                           const osgDB::ReaderWriter::Options* options)
277 {
278     long tileIndex;
279     {
280         std::istringstream idxStream(index_str);
281         idxStream >> tileIndex;
282     }
283     SGBucket tile_bucket(tileIndex);
284     const string basePath = tile_bucket.gen_base_path();
285
286     bool found_tile_base = false;
287
288     SGPath object_base;
289     vector<const Object*> objects;
290
291     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
292
293     osgDB::FilePathList path_list=options->getDatabasePathList();
294
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
300         // as marker.
301
302         if (path_list[i].empty()) {
303             if (found_tile_base)
304                 break;
305             else
306                 continue;
307         }
308
309         bool has_base = false;
310
311         SGPath tile_path = path_list[i];
312         tile_path.append(basePath);
313
314         SGPath basename = tile_path;
315         basename.append( index_str );
316
317         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
318
319
320         // Check for master .stg (scene terra gear) file
321         SGPath stg_name = basename;
322         stg_name.concat( ".stg" );
323
324         sg_gzifstream in( stg_name.str() );
325         if ( !in.is_open() )
326             continue;
327
328         while ( ! in.eof() ) {
329             string token;
330             in >> token;
331
332             if ( token.empty() || token[0] == '#' ) {
333                in >> ::skipeol;
334                continue;
335             }
336                             // Load only once (first found)
337             if ( token == "OBJECT_BASE" ) {
338                 string name;
339                 in >> name >> ::skipws;
340                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
341
342                 if (!found_tile_base) {
343                     found_tile_base = true;
344                     has_base = true;
345
346                     object_base = tile_path;
347                     object_base.append(name);
348
349                 } else
350                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
351
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));
356                 else {
357                     string name;
358                     in >> name >> ::skipeol;
359                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
360                             << name << "  (skipped)");
361                 }
362
363                             // Always OK to load
364             } else if ( token == "OBJECT_STATIC" ) {
365                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
366
367             } else if ( token == "OBJECT_SHARED" ) {
368                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
369
370             } else if ( token == "OBJECT_SIGN" ) {
371                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
372
373             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
374                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
375
376             } else {
377                 SG_LOG( SG_TERRAIN, SG_DEBUG,
378                         "Unknown token '" << token << "' in " << stg_name.str() );
379                 in >> ::skipws;
380             }
381         }
382     }
383
384     SGReaderWriterBTGOptions *opt = new SGReaderWriterBTGOptions(*dynamic_cast<const SGReaderWriterBTGOptions *>(options));
385
386     // obj_load() will generate ground lighting for us ...
387     osg::Group* new_tile = new osg::Group;
388
389     if (found_tile_base) {
390         // load tile if found ...
391         opt->setCalcLights(true);
392         obj_load( object_base.str(), new_tile, true, options);
393
394     } else {
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!" );
401         }
402     }
403
404
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];
408
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);
414
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.
418             SGPath custom_path;
419             if ( obj->type == OBJECT_STATIC ) {
420                 custom_path = obj->path;
421             } else {
422                 // custom_path = globals->get_fg_root();
423             }
424             custom_path.append( obj->name );
425
426             osg::Matrix obj_pos;
427             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
428
429             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
430             obj_trans->setMatrix( obj_pos );
431
432             // wire as much of the scene graph together as we can
433             new_tile->addChild( obj_trans );
434
435             osg::Node* model = 0;
436             if(_modelLoader)
437                 model = _modelLoader->loadTileModel(custom_path.str(),
438                                                     obj->type == OBJECT_SHARED);
439             if (model)
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 );
445
446             osg::Matrix obj_pos;
447             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
448
449             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
450             obj_trans->setMatrix( obj_pos );
451
452             osg::Node *custom_obj = 0;
453             if (obj->type == OBJECT_SIGN)
454                 custom_obj = SGMakeSign(opt->getMatlib(), custom_path.str(), obj->name);
455             else
456                 custom_obj = SGMakeRunwaySign(opt->getMatlib(), custom_path.str(), obj->name);
457
458             // wire the pieces together
459             if ( custom_obj != NULL ) {
460                 obj_trans -> addChild( custom_obj );
461             }
462             new_tile->addChild( obj_trans );
463
464         }
465         delete obj;
466     }
467     return new_tile;
468 }
469
470 void
471 TileEntry::addToSceneGraph(osg::Group *terrain_branch)
472 {
473     terrain_branch->addChild( _node.get() );
474
475     SG_LOG( SG_TERRAIN, SG_DEBUG,
476             "connected a tile into scene graph.  _node = "
477             << _node.get() );
478     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
479             << _node->getNumParents() );
480 }
481
482
483 void
484 TileEntry::removeFromSceneGraph()
485 {
486     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting TileEntry nodes" );
487
488     if (! is_loaded()) {
489         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
490     } else {
491         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  _node = " << _node.get() );
492     }
493
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 ) ;
498         if( parent ) {
499             parent->removeChild( _node.get() );
500         }
501     }
502 }
503