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 - curt@infoplane.com
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., 675 Mass Ave, Cambridge, MA 02139, USA.
30 #include <simgear/constants.h>
31 #include <simgear/debug/logstream.hxx>
32 #include <simgear/math/point3d.hxx>
33 #include <simgear/math/polar3d.hxx>
34 #include <simgear/math/sg_geodesy.hxx>
35 #include <simgear/math/vector.hxx>
36 #include <simgear/misc/exception.hxx>
38 #include <Main/globals.hxx>
39 #include <Main/fg_props.hxx>
40 #include <Main/viewer.hxx>
41 #include <Model/loader.hxx>
42 #include <Objects/obj.hxx>
44 #include "newcache.hxx"
45 #include "scenery.hxx"
46 #include "tilemgr.hxx"
48 #define TEST_LAST_HIT_CACHE
51 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
52 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
54 queue<FGTileEntry *> FGTileMgr::attach_queue;
55 queue<FGDeferredModel *> FGTileMgr::model_queue;
56 #endif // ENABLE_THREADS
57 queue<FGTileEntry *> FGTileMgr::delete_queue;
61 FGTileMgr::FGTileMgr():
71 FGTileMgr::~FGTileMgr() {
75 // Initialize the Tile Manager subsystem
76 int FGTileMgr::init() {
77 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
83 // instead it's just a lot easier to let any pending work flush
84 // through, rather than trying to arrest the queue and nuke all
85 // the various work at all the various stages and get everything
86 // cleaned up properly.
88 while ( ! attach_queue.empty() ) {
92 while ( ! model_queue.empty() ) {
94 FGDeferredModel* dm = model_queue.pop();
96 FGDeferredModel* dm = model_queue.front();
108 previous_bucket.make_bad();
109 current_bucket.make_bad();
111 longitude = latitude = -1000.0;
112 last_longitude = last_latitude = -1000.0;
118 // schedule a tile for loading
119 void FGTileMgr::sched_tile( const SGBucket& b ) {
120 // see if tile already exists in the cache
121 FGTileEntry *t = tile_cache.get_tile( b );
124 // make space in the cache
125 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
126 long index = tile_cache.get_oldest_tile();
128 FGTileEntry *old = tile_cache.get_tile( index );
129 old->disconnect_ssg_nodes();
130 delete_queue.push( old );
131 tile_cache.clear_entry( index );
133 // nothing to free ?!? forge ahead
138 // create a new entry
139 FGTileEntry *e = new FGTileEntry( b );
141 // insert the tile into the cache
142 if ( tile_cache.insert_tile( e ) ) {
143 // Schedule tile for loading
146 // insert failed (cache full with no available entries to
147 // delete.) Try again later
154 // schedule a needed buckets for loading
155 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
156 // sanity check (unfortunately needed!)
157 if ( longitude < -180.0 || longitude > 180.0
158 || latitude < -90.0 || latitude > 90.0 )
160 SG_LOG( SG_TERRAIN, SG_ALERT,
161 "Attempting to schedule tiles for bogus lon and lat = ("
162 << longitude << "," << latitude << ")" );
163 SG_LOG( SG_TERRAIN, SG_ALERT,
164 "This is a FATAL error. Exiting!" );
168 SG_LOG( SG_TERRAIN, SG_INFO,
169 "scheduling needed tiles for " << longitude << " " << latitude );
171 // vis = fgGetDouble("/environment/visibility-m");
173 double tile_width = curr_bucket.get_width_m();
174 double tile_height = curr_bucket.get_height_m();
175 // cout << "tile width = " << tile_width << " tile_height = "
176 // << tile_height !<< endl;
178 xrange = (int)(vis / tile_width) + 1;
179 yrange = (int)(vis / tile_height) + 1;
180 if ( xrange < 1 ) { xrange /= 1; }
181 if ( yrange < 1 ) { yrange = 1; }
183 // note * 2 at end doubles cache size (for fdm and viewer)
184 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
187 cout << "xrange = " << xrange << " yrange = " << yrange << endl;
188 cout << "max cache size = " << tile_cache.get_max_cache_size()
189 << " current cache size = " << tile_cache.get_size() << endl;
194 // schedule center tile first so it can be loaded first
195 b = sgBucketOffset( longitude, latitude, 0, 0 );
200 // schedule next ring of 8 tiles
201 for ( x = -1; x <= 1; ++x ) {
202 for ( y = -1; y <= 1; ++y ) {
203 if ( x != 0 || y != 0 ) {
204 b = sgBucketOffset( longitude, latitude, x, y );
210 // schedule remaining tiles
211 for ( x = -xrange; x <= xrange; ++x ) {
212 for ( y = -yrange; y <= yrange; ++y ) {
213 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
214 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
222 void FGTileMgr::initialize_queue()
224 // First time through or we have teleported, initialize the
225 // system and load all relavant tiles
227 SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
228 // cout << "tile cache size = " << tile_cache.get_size() << endl;
230 // wipe/initialize tile cache
231 // tile_cache.init();
232 previous_bucket.make_bad();
234 // build the local area list and schedule tiles for loading
236 // start with the center tile and work out in concentric
239 double visibility_meters = fgGetDouble("/environment/visibility-m");
240 schedule_needed(visibility_meters, current_bucket);
242 // do we really want to lose this? CLO
244 // Now force a load of the center tile and inner ring so we
245 // have something to see in our first frame.
247 for ( i = 0; i < 9; ++i ) {
248 if ( load_queue.size() ) {
249 SG_LOG( SG_TERRAIN, SG_DEBUG,
250 "Load queue not empty, loading a tile" );
252 SGBucket pending = load_queue.front();
253 load_queue.pop_front();
254 load_tile( pending );
262 * Update the various queues maintained by the tilemagr (private
263 * internal function, do not call directly.)
265 void FGTileMgr::update_queues()
267 // load the next model in the load queue. Currently this must
268 // happen in the render thread because model loading can trigger
269 // texture loading which involves use of the opengl api.
270 if ( !model_queue.empty() ) {
271 // cout << "loading next model ..." << endl;
272 // load the next tile in the queue
273 #ifdef ENABLE_THREADS
274 FGDeferredModel* dm = model_queue.pop();
276 FGDeferredModel* dm = model_queue.front();
280 ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
283 ssgEntity *obj_model =
284 globals->get_model_loader()->load_model(dm->get_model_path());
285 if ( obj_model != NULL ) {
286 dm->get_obj_trans()->addKid( obj_model );
289 catch (const sg_exception& exc)
291 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
294 dm->get_tile()->dec_pending_models();
298 // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
300 // activate loader thread one out of every 5 frames
301 if ( counter_hack == 0 ) {
302 // Notify the tile loader that it can load another tile
305 counter_hack = (counter_hack + 1) % 5;
308 if ( !attach_queue.empty() ) {
309 #ifdef ENABLE_THREADS
310 FGTileEntry* e = attach_queue.pop();
312 FGTileEntry* e = attach_queue.front();
315 e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
316 globals->get_scenery()->get_gnd_lights_root(),
317 globals->get_scenery()->get_rwy_lights_root(),
318 globals->get_scenery()->get_taxi_lights_root() );
319 // cout << "Adding ssg nodes for "
322 if ( !delete_queue.empty() ) {
323 // cout << "delete queue = " << delete_queue.size() << endl;
325 while ( delete_queue.size() > 30 ) {
326 // uh oh, delete queue is blowing up, we aren't clearing
327 // it fast enough. Let's just panic, well not panic, but
328 // get real serious and agressively free up some tiles so
329 // we don't explode our memory usage.
331 SG_LOG( SG_TERRAIN, SG_ALERT,
332 "Alert: catching up on tile delete queue" );
334 FGTileEntry* e = delete_queue.front();
335 while ( !e->free_tile() );
340 FGTileEntry* e = delete_queue.front();
341 if ( e->free_tile() ) {
349 // given the current lon/lat (in degrees), fill in the array of local
350 // chunks. If the chunk isn't already in the cache, then read it from
352 int FGTileMgr::update( double visibility_meters )
354 FGLocation *location = globals->get_current_view()->getFGLocation();
355 sgdVec3 abs_pos_vector;
356 sgdCopyVec3( abs_pos_vector,
357 globals->get_current_view()->get_absolute_view_pos() );
358 return update( location, visibility_meters, abs_pos_vector );
362 int FGTileMgr::update( FGLocation *location, double visibility_meters,
363 sgdVec3 abs_pos_vector )
365 longitude = location->getLongitude_deg();
366 latitude = location->getLatitude_deg();
367 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
368 // << longitude << " " << latatitude );
370 current_bucket.set_bucket( longitude, latitude );
371 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
372 // << current_bucket );
374 // set global scenery center from current tile center
375 current_tile = tile_cache.get_tile( current_bucket );
376 if ( current_tile != NULL ) {
377 globals->get_scenery()->set_next_center( current_tile->center );
379 SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
380 globals->get_scenery()->set_next_center( Point3D(0.0) );
383 // do tile load scheduling.
384 // Note that we need keep track of both viewer buckets and fdm buckets.
385 if ( state == Running ) {
386 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
387 if (!(current_bucket == previous_bucket )) {
388 // We've moved to a new bucket, we need to schedule any
389 // needed tiles for loading.
390 schedule_needed(visibility_meters, current_bucket);
392 } else if ( state == Start || state == Inited ) {
393 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
397 // load the next tile in the load queue (or authorize the next
398 // load in the case of the threaded tile pager)
405 previous_bucket = current_bucket;
407 // no reason to update this if we haven't moved...
408 if ( longitude != last_longitude || latitude != last_latitude ) {
409 // update current elevation...
410 if ( updateCurrentElevAtPos( abs_pos_vector,
411 location->get_tile_center() ) )
413 last_longitude = longitude;
414 last_latitude = latitude;
422 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
423 void FGTileMgr::refresh_view_timestamps() {
424 SG_LOG( SG_TERRAIN, SG_INFO,
425 "Refreshing timestamps for " << current_bucket.get_center_lon()
426 << " " << current_bucket.get_center_lat() );
427 schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
431 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
435 sgdSetVec3( sc, center[0], center[1], center[2]);
437 // overridden with actual values if a terrain intersection is
439 double hit_elev = -9999.0;
440 double hit_radius = 0.0;
441 sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
444 if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
445 // scenery center has been properly defined so any hit should
446 // be valid (and not just luck)
447 hit = fgCurrentElev(abs_pos_vector,
449 // current_tile->get_terra_transform(),
457 // cout << "elev = " << hit_elev << " " << hit_radius << endl;
458 globals->get_scenery()->set_cur_elev( hit_elev );
459 globals->get_scenery()->set_cur_radius( hit_radius );
460 globals->get_scenery()->set_cur_normal( hit_normal );
462 globals->get_scenery()->set_cur_elev( -9999.0 );
463 globals->get_scenery()->set_cur_radius( 0.0 );
464 globals->get_scenery()->set_cur_normal( hit_normal );
470 void FGTileMgr::prep_ssg_nodes( FGLocation *location, float vis ) {
472 // traverse the potentially viewable tile list and update range
473 // selector and transform
475 Point3D center = location->get_tile_center();
476 float *up = location->get_world_up();
479 tile_cache.reset_traversal();
481 while ( ! tile_cache.at_end() ) {
482 // cout << "processing a tile" << endl;
483 if ( (e = tile_cache.get_current()) ) {
484 e->prep_ssg_node( center, up, vis);
486 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");