]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tileentry.cxx
move callback registration functions to fg_os_common.cxx
[flightgear.git] / src / Scenery / 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 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <plib/ul.h>
30 #include <Main/main.hxx>
31
32
33 #include STL_STRING
34 #include <sstream>
35
36 #include <osg/Array>
37 #include <osg/Geometry>
38 #include <osg/Geode>
39 #include <osg/LOD>
40 #include <osg/MatrixTransform>
41 #include <osg/NodeCallback>
42 #include <osg/Switch>
43
44 #include <osgDB/FileNameUtils>
45 #include <osgDB/ReaderWriter>
46 #include <osgDB/ReadFile>
47 #include <osgDB/Registry>
48
49 #include <simgear/bucket/newbucket.hxx>
50 #include <simgear/debug/logstream.hxx>
51 #include <simgear/math/polar3d.hxx>
52 #include <simgear/math/sg_geodesy.hxx>
53 #include <simgear/math/sg_random.h>
54 #include <simgear/misc/sgstream.hxx>
55 #include <simgear/scene/material/mat.hxx>
56 #include <simgear/scene/material/matlib.hxx>
57 #include <simgear/scene/model/ModelRegistry.hxx>
58 #include <simgear/scene/tgdb/apt_signs.hxx>
59 #include <simgear/scene/tgdb/obj.hxx>
60 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
61 #include <simgear/scene/model/placementtrans.hxx>
62 #include <simgear/scene/util/SGUpdateVisitor.hxx>
63
64 #include <Aircraft/aircraft.hxx>
65 #include <Include/general.hxx>
66 #include <Main/fg_props.hxx>
67 #include <Main/globals.hxx>
68 #include <Main/viewer.hxx>
69 #include <Scenery/scenery.hxx>
70 #include <Time/light.hxx>
71
72 #include "tileentry.hxx"
73 #include "tilemgr.hxx"
74
75 SG_USING_STD(string);
76 using namespace simgear;
77
78 // FIXME: investigate what huge update flood is clamped away here ...
79 class FGTileUpdateCallback : public osg::NodeCallback {
80 public:
81   virtual void operator()(osg::Node* node, osg::NodeVisitor* nv)
82   {
83     assert(dynamic_cast<SGUpdateVisitor*>(nv));
84     SGUpdateVisitor* updateVisitor = static_cast<SGUpdateVisitor*>(nv);
85
86     osg::Vec3 center = node->getBound().center();
87     double distance = dist(updateVisitor->getGlobalEyePos(),
88                            SGVec3d(center[0], center[1], center[2]));
89     if (updateVisitor->getVisibility() + node->getBound().radius() < distance)
90       return;
91
92     traverse(node, nv);
93   }
94 };
95
96 // Constructor
97 FGTileEntry::FGTileEntry ( const SGBucket& b )
98     : tile_bucket( b ),
99       terra_transform( new osg::Group ),
100       terra_range( new osg::LOD ),
101       loaded(false),
102       pending_models(0),
103       is_inner_ring(false),
104       free_tracker(0)
105 {
106     terra_transform->setUpdateCallback(new FGTileUpdateCallback);
107 }
108
109
110 // Destructor
111 FGTileEntry::~FGTileEntry () {
112 }
113
114 static void WorldCoordinate( osg::Matrix& obj_pos, double lat,
115                              double lon, double elev, double hdg )
116 {
117     double lon_rad = lon * SGD_DEGREES_TO_RADIANS;
118     double lat_rad = lat * SGD_DEGREES_TO_RADIANS;
119     double hdg_rad = hdg * SGD_DEGREES_TO_RADIANS;
120
121     // setup transforms
122     Point3D geod( lon_rad, lat_rad, elev );
123     Point3D world_pos = sgGeodToCart( geod );
124
125     double sin_lat = sin( lat_rad );
126     double cos_lat = cos( lat_rad );
127     double cos_lon = cos( lon_rad );
128     double sin_lon = sin( lon_rad );
129     double sin_hdg = sin( hdg_rad ) ;
130     double cos_hdg = cos( hdg_rad ) ;
131
132     obj_pos(0, 0) =  cos_hdg * sin_lat * cos_lon - sin_hdg * sin_lon;
133     obj_pos(0, 1) =  cos_hdg * sin_lat * sin_lon + sin_hdg * cos_lon;
134     obj_pos(0, 2) = -cos_hdg * cos_lat;
135     obj_pos(0, 3) =  SG_ZERO;
136
137     obj_pos(1, 0) = -sin_hdg * sin_lat * cos_lon - cos_hdg * sin_lon;
138     obj_pos(1, 1) = -sin_hdg * sin_lat * sin_lon + cos_hdg * cos_lon;
139     obj_pos(1, 2) =  sin_hdg * cos_lat;
140     obj_pos(1, 3) =  SG_ZERO;
141
142     obj_pos(2, 0) = cos_lat * cos_lon;
143     obj_pos(2, 1) = cos_lat * sin_lon;
144     obj_pos(2, 2) = sin_lat;
145     obj_pos(2, 3) =  SG_ZERO;
146
147     obj_pos(3, 0) = world_pos.x();
148     obj_pos(3, 1) = world_pos.y();
149     obj_pos(3, 2) = world_pos.z();
150     obj_pos(3, 3) = SG_ONE ;
151 }
152
153
154 // Free "n" leaf elements of an ssg tree.  returns the number of
155 // elements freed.  An empty branch node is considered a leaf.  This
156 // is intended to spread the load of freeing a complex tile out over
157 // several frames.
158 static int fgPartialFreeSSGtree( osg::Group *b, int n ) {
159     int num_deletes = b->getNumChildren();
160
161     b->removeChildren(0, b->getNumChildren());
162
163     return num_deletes;
164 }
165
166
167 // Clean up the memory used by this tile and delete the arrays used by
168 // ssg as well as the whole ssg branch
169 bool FGTileEntry::free_tile() {
170     int delete_size = 100;
171     SG_LOG( SG_TERRAIN, SG_DEBUG,
172             "FREEING TILE = (" << tile_bucket << ")" );
173
174     SG_LOG( SG_TERRAIN, SG_DEBUG, "(start) free_tracker = " << free_tracker );
175     
176     if ( !(free_tracker & NODES) ) {
177         free_tracker |= NODES;
178     } else if ( !(free_tracker & VEC_PTRS) ) {
179         free_tracker |= VEC_PTRS;
180     } else if ( !(free_tracker & TERRA_NODE) ) {
181         // delete the terrain branch (this should already have been
182         // disconnected from the scene graph)
183         SG_LOG( SG_TERRAIN, SG_DEBUG, "FREEING terra_transform" );
184         if ( fgPartialFreeSSGtree( terra_transform.get(), delete_size ) == 0 ) {
185             terra_transform = 0;
186             free_tracker |= TERRA_NODE;
187         }
188     } else if ( !(free_tracker & LIGHTMAPS) ) {
189         free_tracker |= LIGHTMAPS;
190     } else {
191         return true;
192     }
193
194     SG_LOG( SG_TERRAIN, SG_DEBUG, "(end) free_tracker = " << free_tracker );
195
196     // if we fall down to here, we still have work todo, return false
197     return false;
198 }
199
200
201 // Update the ssg transform node for this tile so it can be
202 // properly drawn relative to our (0,0,0) point
203 void FGTileEntry::prep_ssg_node(float vis) {
204     if ( !loaded ) return;
205
206     // visibility can change from frame to frame so we update the
207     // range selector cutoff's each time.
208     float bounding_radius = terra_range->getChild(0)->getBound().radius();
209     terra_range->setRange( 0, 0, vis + bounding_radius );
210 }
211
212 bool FGTileEntry::obj_load( const string& path,
213                             osg::Group *geometry, bool is_base )
214 {
215     bool use_random_objects =
216         fgGetBool("/sim/rendering/random-objects", true);
217
218     // try loading binary format
219     osg::ref_ptr<SGReaderWriterBTGOptions> options
220         = new SGReaderWriterBTGOptions();
221     options->setMatlib(globals->get_matlib());
222     options->setCalcLights(is_base);
223     options->setUseRandomObjects(use_random_objects);
224     osg::Node* node = osgDB::readNodeFile(path, options.get());
225     if (node)
226       geometry->addChild(node);
227
228     return node;
229 }
230
231
232 typedef enum {
233     OBJECT,
234     OBJECT_SHARED,
235     OBJECT_STATIC,
236     OBJECT_SIGN,
237     OBJECT_RUNWAY_SIGN
238 } object_type;
239
240
241 // storage class for deferred object processing in FGTileEntry::load()
242 struct Object {
243     Object(object_type t, const string& token, const SGPath& p, istream& in)
244         : type(t), path(p)
245     {
246         in >> name;
247         if (type != OBJECT)
248             in >> lon >> lat >> elev >> hdg;
249         in >> ::skipeol;
250
251         if (type == OBJECT)
252             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name);
253         else
254             SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  " << name << "  lon=" <<
255                     lon << "  lat=" << lat << "  elev=" << elev << "  hdg=" << hdg);
256     }
257     object_type type;
258     string name;
259     SGPath path;
260     double lon, lat, elev, hdg;
261 };
262
263 // Work in progress... load the tile based entirely by name cuz that's
264 // what we'll want to do with the database pager.
265 void
266 FGTileEntry::load( const string_list &path_list, bool is_base )
267 {
268     osgDB::ReaderWriter::ReadResult result
269         = osgDB::Registry::instance()->readNode(tile_bucket.gen_index_str()
270                                                 + ".stg", 0);        
271     if (result.validNode()) {
272         osg::Node* new_tile = result.getNode();
273         terra_range->addChild( new_tile );
274     }
275     terra_transform->addChild( terra_range.get() );
276 }
277
278 osg::Node*
279 FGTileEntry::loadTileByName(const string& index_str,
280                             const string_list &path_list)
281 {
282     long tileIndex;
283     {
284         istringstream idxStream(index_str);
285         idxStream >> tileIndex;
286     }
287     SGBucket tile_bucket(tileIndex);
288     const string basePath = tile_bucket.gen_base_path();
289     
290     bool found_tile_base = false;
291
292     SGPath object_base;
293     vector<const Object*> objects;
294
295     SG_LOG( SG_TERRAIN, SG_INFO, "Loading tile " << index_str );
296
297     // scan and parse all files and store information
298     for (unsigned int i = 0; i < path_list.size(); i++) {
299         // If we found a terrain tile in Terrain/, we have to process the
300         // Objects/ dir in the same group, too, before we can stop scanning.
301         // FGGlobals::set_fg_scenery() inserts an empty string to path_list
302         // as marker.
303         if (path_list[i].empty()) {
304             if (found_tile_base)
305                 break;
306             else
307                 continue;
308         }
309
310         bool has_base = false;
311
312         SGPath tile_path = path_list[i];
313         tile_path.append(basePath);
314
315         SGPath basename = tile_path;
316         basename.append( index_str );
317
318         SG_LOG( SG_TERRAIN, SG_INFO, "  Trying " << basename.str() );
319
320
321         // Check for master .stg (scene terra gear) file
322         SGPath stg_name = basename;
323         stg_name.concat( ".stg" );
324
325         sg_gzifstream in( stg_name.str() );
326         if ( !in.is_open() )
327             continue;
328
329         while ( ! in.eof() ) {
330             string token;
331             in >> token;
332
333             if ( token.empty() || token[0] == '#' ) {
334                in >> ::skipeol;
335                continue;
336             }
337                             // Load only once (first found)
338             if ( token == "OBJECT_BASE" ) {
339                 string name;
340                 in >> name >> ::skipws;
341                 SG_LOG( SG_TERRAIN, SG_INFO, "    " << token << " " << name );
342
343                 if (!found_tile_base) {
344                     found_tile_base = true;
345                     has_base = true;
346
347                     object_base = tile_path;
348                     object_base.append(name);
349
350                 } else
351                     SG_LOG(SG_TERRAIN, SG_INFO, "    (skipped)");
352
353                             // Load only if base is not in another file
354             } else if ( token == "OBJECT" ) {
355                 if (!found_tile_base || has_base)
356                     objects.push_back(new Object(OBJECT, token, tile_path, in));
357                 else {
358                     string name;
359                     in >> name >> ::skipeol;
360                     SG_LOG(SG_TERRAIN, SG_INFO, "    " << token << "  "
361                             << name << "  (skipped)");
362                 }
363
364                             // Always OK to load
365             } else if ( token == "OBJECT_STATIC" ) {
366                 objects.push_back(new Object(OBJECT_STATIC, token, tile_path, in));
367
368             } else if ( token == "OBJECT_SHARED" ) {
369                 objects.push_back(new Object(OBJECT_SHARED, token, tile_path, in));
370
371             } else if ( token == "OBJECT_SIGN" ) {
372                 objects.push_back(new Object(OBJECT_SIGN, token, tile_path, in));
373
374             } else if ( token == "OBJECT_RUNWAY_SIGN" ) {
375                 objects.push_back(new Object(OBJECT_RUNWAY_SIGN, token, tile_path, in));
376
377             } else {
378                 SG_LOG( SG_TERRAIN, SG_DEBUG,
379                         "Unknown token '" << token << "' in " << stg_name.str() );
380                 in >> ::skipws;
381             }
382         }
383     }
384
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         obj_load( object_base.str(), new_tile, true );
392
393     } else {
394         // ... or generate an ocean tile on the fly
395         SG_LOG(SG_TERRAIN, SG_INFO, "  Generating ocean tile");
396         if ( !SGGenTile( path_list[0], tile_bucket,
397                         globals->get_matlib(), new_tile ) ) {
398             SG_LOG( SG_TERRAIN, SG_ALERT,
399                     "Warning: failed to generate ocean tile!" );
400         }
401     }
402
403
404     // now that we have a valid center, process all the objects
405     for (unsigned int j = 0; j < objects.size(); j++) {
406         const Object *obj = objects[j];
407
408         if (obj->type == OBJECT) {
409             SGPath custom_path = obj->path;
410             custom_path.append( obj->name );
411             obj_load( custom_path.str(), new_tile, false );
412
413         } else if (obj->type == OBJECT_SHARED || obj->type == OBJECT_STATIC) {
414             // object loading is deferred to main render thread,
415             // but lets figure out the paths right now.
416             SGPath custom_path;
417             if ( obj->type == OBJECT_STATIC ) {
418                 custom_path = obj->path;
419             } else {
420                 custom_path = globals->get_fg_root();
421             }
422             custom_path.append( obj->name );
423
424             osg::Matrix obj_pos;
425             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
426
427             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
428             obj_trans->setMatrix( obj_pos );
429
430             // wire as much of the scene graph together as we can
431             new_tile->addChild( obj_trans );
432
433             osg::Node* model
434                 = FGTileMgr::loadTileModel(custom_path.str(),
435                                            obj->type == OBJECT_SHARED);
436             if (model)
437                 obj_trans->addChild(model);
438         } else if (obj->type == OBJECT_SIGN || obj->type == OBJECT_RUNWAY_SIGN) {
439             // load the object itself
440             SGPath custom_path = obj->path;
441             custom_path.append( obj->name );
442
443             osg::Matrix obj_pos;
444             WorldCoordinate( obj_pos, obj->lat, obj->lon, obj->elev, obj->hdg );
445
446             osg::MatrixTransform *obj_trans = new osg::MatrixTransform;
447             obj_trans->setMatrix( obj_pos );
448
449             osg::Node *custom_obj = 0;
450             if (obj->type == OBJECT_SIGN)
451                 custom_obj = SGMakeSign(globals->get_matlib(), custom_path.str(), obj->name);
452             else
453                 custom_obj = SGMakeRunwaySign(globals->get_matlib(), custom_path.str(), obj->name);
454
455             // wire the pieces together
456             if ( custom_obj != NULL ) {
457                 obj_trans -> addChild( custom_obj );
458             }
459             new_tile->addChild( obj_trans );
460
461         }
462         delete obj;
463     }
464     return new_tile;
465 }
466
467 void
468 FGTileEntry::add_ssg_nodes( osg::Group *terrain_branch )
469 {
470     // bump up the ref count so we can remove this later without
471     // having ssg try to free the memory.
472     terrain_branch->addChild( terra_transform.get() );
473
474     SG_LOG( SG_TERRAIN, SG_DEBUG,
475             "connected a tile into scene graph.  terra_transform = "
476             << terra_transform.get() );
477     SG_LOG( SG_TERRAIN, SG_DEBUG, "num parents now = "
478             << terra_transform->getNumParents() );
479
480     loaded = true;
481 }
482
483
484 void
485 FGTileEntry::disconnect_ssg_nodes()
486 {
487     SG_LOG( SG_TERRAIN, SG_DEBUG, "disconnecting ssg nodes" );
488
489     if ( ! loaded ) {
490         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a not-fully loaded tile!" );
491     } else {
492         SG_LOG( SG_TERRAIN, SG_DEBUG, "removing a fully loaded tile!  terra_transform = " << terra_transform.get() );
493     }
494         
495     // find the terrain branch parent
496     int pcount = terra_transform->getNumParents();
497     if ( pcount > 0 ) {
498         // find the first parent (should only be one)
499         osg::Group *parent = terra_transform->getParent( 0 ) ;
500         if( parent ) {
501             // disconnect the tile (we previously ref()'d it so it
502             // won't get freed now)
503             parent->removeChild( terra_transform.get() );
504         } else {
505             SG_LOG( SG_TERRAIN, SG_ALERT,
506                     "parent pointer is NULL!  Dying" );
507             exit(-1);
508         }
509     } else {
510         SG_LOG( SG_TERRAIN, SG_ALERT,
511                 "Parent count is zero for an ssg tile!  Dying" );
512         exit(-1);
513     }
514 }
515
516 namespace
517 {
518
519 class ReaderWriterSTG : public osgDB::ReaderWriter {
520 public:
521     virtual const char* className() const;
522  
523     virtual bool acceptsExtension(const string& extension) const;
524
525     virtual ReadResult readNode(const string& fileName,
526                                 const osgDB::ReaderWriter::Options* options)
527         const;
528 };
529
530 const char* ReaderWriterSTG::className() const
531 {
532     return "STG Database reader";
533 }
534
535 bool ReaderWriterSTG::acceptsExtension(const string& extension) const
536 {
537     return (osgDB::equalCaseInsensitive(extension, "gz")
538             || osgDB::equalCaseInsensitive(extension, "stg"));   
539 }
540
541 osgDB::ReaderWriter::ReadResult
542 ReaderWriterSTG::readNode(const string& fileName,
543                           const osgDB::ReaderWriter::Options* options) const
544 {
545     string ext = osgDB::getLowerCaseFileExtension(fileName);
546     if(!acceptsExtension(ext))
547         return ReadResult::FILE_NOT_HANDLED;
548     string stgFileName;
549     if (osgDB::equalCaseInsensitive(ext, "gz")) {
550         stgFileName = osgDB::getNameLessExtension(fileName);
551         if (!acceptsExtension(
552                 osgDB::getLowerCaseFileExtension(stgFileName))) {
553             return ReadResult::FILE_NOT_HANDLED;
554         }
555     } else {
556         stgFileName = fileName;
557     }
558     osg::Node* result
559         = FGTileEntry::loadTileByName(osgDB::getNameLessExtension(stgFileName),
560                                       globals->get_fg_scenery());
561     if (result)
562         return result;           // Constructor converts to ReadResult
563     else
564         return ReadResult::FILE_NOT_HANDLED;
565 }
566
567 osgDB::RegisterReaderWriterProxy<ReaderWriterSTG> g_readerWriterSTGProxy;
568 ModelRegistryCallbackProxy<LoadOnlyCallback> g_stgCallbackProxy("stg");
569 } // namespace