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