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