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