1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
3 // Written by Curtis Olson, started January 1998.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
28 #include <simgear/constants.h>
29 #include <simgear/debug/logstream.hxx>
30 #include <simgear/math/point3d.hxx>
31 #include <simgear/math/polar3d.hxx>
32 #include <simgear/math/sg_geodesy.hxx>
33 #include <simgear/math/vector.hxx>
34 #include <simgear/structure/exception.hxx>
35 #include <simgear/scene/model/modellib.hxx>
37 #include <Main/globals.hxx>
38 #include <Main/fg_props.hxx>
39 #include <Main/viewer.hxx>
40 #include <Scripting/NasalSys.hxx>
42 #include "newcache.hxx"
43 #include "scenery.hxx"
44 #include "tilemgr.hxx"
46 #define TEST_LAST_HIT_CACHE
48 #if defined(ENABLE_THREADS)
49 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
50 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
52 queue<FGTileEntry *> FGTileMgr::attach_queue;
53 queue<FGDeferredModel *> FGTileMgr::model_queue;
54 #endif // ENABLE_THREADS
55 queue<FGTileEntry *> FGTileMgr::delete_queue;
58 FGTileMgr::FGTileMgr():
67 FGTileMgr::~FGTileMgr() {
71 // Initialize the Tile Manager subsystem
72 int FGTileMgr::init() {
73 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
79 // instead it's just a lot easier to let any pending work flush
80 // through, rather than trying to arrest the queue and nuke all
81 // the various work at all the various stages and get everything
82 // cleaned up properly.
84 while ( ! attach_queue.empty() ) {
88 while ( ! model_queue.empty() ) {
89 #if defined(ENABLE_THREADS)
90 FGDeferredModel* dm = model_queue.pop();
92 FGDeferredModel* dm = model_queue.front();
102 previous_bucket.make_bad();
103 current_bucket.make_bad();
105 longitude = latitude = -1000.0;
111 // schedule a tile for loading
112 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
113 // see if tile already exists in the cache
114 FGTileEntry *t = tile_cache.get_tile( b );
117 // make space in the cache
118 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
119 long index = tile_cache.get_oldest_tile();
121 FGTileEntry *old = tile_cache.get_tile( index );
123 // shadows->deleteOccluderFromTile( (ssgBranch *) old->get_terra_transform() );
124 old->disconnect_ssg_nodes();
125 delete_queue.push( old );
126 tile_cache.clear_entry( index );
128 // nothing to free ?!? forge ahead
133 // create a new entry
134 FGTileEntry *e = new FGTileEntry( b );
136 // insert the tile into the cache
137 if ( tile_cache.insert_tile( e ) ) {
138 // Schedule tile for loading
141 // insert failed (cache full with no available entries to
142 // delete.) Try again later
146 t->set_inner_ring( is_inner_ring );
151 // schedule a needed buckets for loading
152 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
153 // sanity check (unfortunately needed!)
154 if ( longitude < -180.0 || longitude > 180.0
155 || latitude < -90.0 || latitude > 90.0 )
157 SG_LOG( SG_TERRAIN, SG_ALERT,
158 "Attempting to schedule tiles for bogus lon and lat = ("
159 << longitude << "," << latitude << ")" );
161 SG_LOG( SG_TERRAIN, SG_ALERT,
162 "This is a FATAL error. Exiting!" );
166 SG_LOG( SG_TERRAIN, SG_INFO,
167 "scheduling needed tiles for " << longitude << " " << latitude );
169 // vis = fgGetDouble("/environment/visibility-m");
171 double tile_width = curr_bucket.get_width_m();
172 double tile_height = curr_bucket.get_height_m();
173 // cout << "tile width = " << tile_width << " tile_height = "
174 // << tile_height << endl;
176 xrange = (int)(vis / tile_width) + 1;
177 yrange = (int)(vis / tile_height) + 1;
178 if ( xrange < 1 ) { xrange = 1; }
179 if ( yrange < 1 ) { yrange = 1; }
181 // note * 2 at end doubles cache size (for fdm and viewer)
182 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
183 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
184 // cout << "max cache size = " << tile_cache.get_max_cache_size()
185 // << " current cache size = " << tile_cache.get_size() << endl;
187 // clear the inner ring flags so we can set them below. This
188 // prevents us from having "true" entries we aren't able to find
189 // to get rid of if we teleport a long ways away from the current
191 tile_cache.clear_inner_ring_flags();
195 // schedule center tile first so it can be loaded first
196 b = sgBucketOffset( longitude, latitude, 0, 0 );
197 sched_tile( b, true );
201 // schedule next ring of 8 tiles
202 for ( x = -1; x <= 1; ++x ) {
203 for ( y = -1; y <= 1; ++y ) {
204 if ( x != 0 || y != 0 ) {
205 b = sgBucketOffset( longitude, latitude, x, y );
206 sched_tile( b, true );
211 // schedule remaining tiles
212 for ( x = -xrange; x <= xrange; ++x ) {
213 for ( y = -yrange; y <= yrange; ++y ) {
214 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
215 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
216 sched_tile( b, false );
223 void FGTileMgr::initialize_queue()
225 // First time through or we have teleported, initialize the
226 // system and load all relavant tiles
228 SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
230 // cout << "tile cache size = " << tile_cache.get_size() << endl;
232 // wipe/initialize tile cache
233 // tile_cache.init();
234 previous_bucket.make_bad();
236 // build the local area list and schedule tiles for loading
238 // start with the center tile and work out in concentric
241 double visibility_meters = fgGetDouble("/environment/visibility-m");
242 schedule_needed(visibility_meters, current_bucket);
244 // do we really want to lose this? CLO
246 // Now force a load of the center tile and inner ring so we
247 // have something to see in our first frame.
249 for ( i = 0; i < 9; ++i ) {
250 if ( load_queue.size() ) {
251 SG_LOG( SG_TERRAIN, SG_DEBUG,
252 "Load queue not empty, loading a tile" );
254 SGBucket pending = load_queue.front();
255 load_queue.pop_front();
256 load_tile( pending );
263 * return current status of queues
267 bool FGTileMgr::all_queues_empty() {
268 return attach_queue.empty() && model_queue.empty();
273 * Update the various queues maintained by the tilemagr (private
274 * internal function, do not call directly.)
276 void FGTileMgr::update_queues()
278 // load the next model in the load queue. Currently this must
279 // happen in the render thread because model loading can trigger
280 // texture loading which involves use of the opengl api. Skip any
281 // models belonging to not loaded tiles (i.e. the tile was removed
282 // before we were able to load some of the associated models.)
283 if ( !model_queue.empty() ) {
284 bool processed_one = false;
286 while ( model_queue.size() > 200 || processed_one == false ) {
287 processed_one = true;
289 if ( model_queue.size() > 200 ) {
290 SG_LOG( SG_TERRAIN, SG_INFO,
291 "Alert: catching up on model load queue" );
294 // cout << "loading next model ..." << endl;
295 // load the next tile in the queue
296 #if defined(ENABLE_THREADS)
297 FGDeferredModel* dm = model_queue.pop();
299 FGDeferredModel* dm = model_queue.front();
303 // only load the model if the tile still exists in the
305 FGTileEntry *t = tile_cache.get_tile( dm->get_bucket() );
308 // ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
310 osg::Node *obj_model =
311 globals->get_model_lib()->load_model( ".",
312 dm->get_model_path(),
313 globals->get_props(),
314 globals->get_sim_time_sec(),
315 dm->get_cache_state(),
316 new FGNasalModelData );
317 if ( obj_model != NULL ) {
318 dm->get_obj_trans()->addChild( obj_model );
320 // shadows->addOccluder( (ssgBranch *) obj_model->getParent(0),
321 // SGShadowVolume::occluderTypeTileObject,
322 // (ssgBranch *) dm->get_tile()->get_terra_transform());
324 } catch (const sg_io_exception& exc) {
325 string m(exc.getMessage());
327 m += exc.getLocation().asString();
328 SG_LOG( SG_ALL, SG_ALERT, m );
329 } catch (const sg_exception& exc) { // XXX may be redundant
330 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
333 dm->get_tile()->dec_pending_models();
339 // Notify the tile loader that it can load another tile
342 if ( !attach_queue.empty() ) {
343 #if defined(ENABLE_THREADS)
344 FGTileEntry* e = attach_queue.pop();
346 FGTileEntry* e = attach_queue.front();
349 e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch() );
350 // cout << "Adding ssg nodes for "
353 if ( !delete_queue.empty() ) {
354 // cout << "delete queue = " << delete_queue.size() << endl;
355 bool processed_one = false;
357 while ( delete_queue.size() > 30 || processed_one == false ) {
358 processed_one = true;
360 if ( delete_queue.size() > 30 ) {
361 // uh oh, delete queue is blowing up, we aren't clearing
362 // it fast enough. Let's just panic, well not panic, but
363 // get real serious and agressively free up some tiles so
364 // we don't explode our memory usage.
366 SG_LOG( SG_TERRAIN, SG_ALERT,
367 "Warning: catching up on tile delete queue" );
370 FGTileEntry* e = delete_queue.front();
371 if ( e->free_tile() ) {
380 // given the current lon/lat (in degrees), fill in the array of local
381 // chunks. If the chunk isn't already in the cache, then read it from
383 int FGTileMgr::update( double visibility_meters )
385 SGLocation *location = globals->get_current_view()->getSGLocation();
386 return update( location, visibility_meters );
390 int FGTileMgr::update( SGLocation *location, double visibility_meters )
392 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
394 longitude = location->getLongitude_deg();
395 latitude = location->getLatitude_deg();
396 // add 1.0m to the max altitude to give a little leeway to the
397 // ground reaction code.
398 altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
400 // if current altitude is apparently not initialized, set max
401 // altitude to something big.
402 if ( altitude_m < -1000 ) {
405 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
406 // << longitude << " " << latatitude );
408 current_bucket.set_bucket( longitude, latitude );
409 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
410 // << current_bucket );
411 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
413 // do tile load scheduling.
414 // Note that we need keep track of both viewer buckets and fdm buckets.
415 if ( state == Running ) {
416 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
417 if (!(current_bucket == previous_bucket )) {
418 // We've moved to a new bucket, we need to schedule any
419 // needed tiles for loading.
420 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
421 schedule_needed(visibility_meters, current_bucket);
423 } else if ( state == Start || state == Inited ) {
424 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
425 // initialize_queue();
428 // load the next tile in the load queue (or authorize the next
429 // load in the case of the threaded tile pager)
436 previous_bucket = current_bucket;
442 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
443 void FGTileMgr::refresh_view_timestamps() {
444 SG_LOG( SG_TERRAIN, SG_INFO,
445 "Refreshing timestamps for " << current_bucket.get_center_lon()
446 << " " << current_bucket.get_center_lat() );
447 if ( longitude >= -180.0 && longitude <= 180.0
448 && latitude >= -90.0 && latitude <= 90.0 )
450 schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
454 void FGTileMgr::prep_ssg_nodes(float vis) {
456 // traverse the potentially viewable tile list and update range
457 // selector and transform
460 tile_cache.reset_traversal();
462 while ( ! tile_cache.at_end() ) {
463 // cout << "processing a tile" << endl;
464 if ( (e = tile_cache.get_current()) ) {
465 e->prep_ssg_node(vis);
467 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
473 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
475 // sanity check (unfortunately needed!)
476 if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
479 SGBucket bucket(lon, lat);
480 FGTileEntry *te = tile_cache.get_tile(bucket);
481 if (!te || !te->is_loaded())
484 // Traverse all tiles required to be there for the given visibility.
485 // This uses exactly the same algorithm like the tile scheduler.
486 double tile_width = bucket.get_width_m();
487 double tile_height = bucket.get_height_m();
489 int xrange = (int)fabs(range_m / tile_width) + 1;
490 int yrange = (int)fabs(range_m / tile_height) + 1;
492 for ( int x = -xrange; x <= xrange; ++x ) {
493 for ( int y = -yrange; y <= yrange; ++y ) {
494 // We have already checked for the center tile.
495 if ( x != 0 || y != 0 ) {
496 SGBucket b = sgBucketOffset( lon, lat, x, y );
497 FGTileEntry *te = tile_cache.get_tile(b);
498 if (!te || !te->is_loaded())
504 // Survived all tests.