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