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