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.
36 #include <simgear/constants.h>
37 #include <simgear/debug/logstream.hxx>
38 #include <simgear/math/point3d.hxx>
39 #include <simgear/math/polar3d.hxx>
40 #include <simgear/math/sg_geodesy.hxx>
41 #include <simgear/math/vector.hxx>
42 #include <simgear/misc/exception.hxx>
44 #include <Main/globals.hxx>
45 #include <Main/fg_props.hxx>
46 #include <Main/viewer.hxx>
47 #include <Model/loader.hxx>
48 #include <Objects/obj.hxx>
50 #include "newcache.hxx"
51 #include "scenery.hxx"
52 #include "tilemgr.hxx"
54 #define TEST_LAST_HIT_CACHE
57 FGTileMgr global_tile_mgr;
61 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
62 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
64 queue<FGTileEntry *> FGTileMgr::attach_queue;
65 queue<FGDeferredModel *> FGTileMgr::model_queue;
66 #endif // ENABLE_THREADS
67 queue<FGTileEntry *> FGTileMgr::delete_queue;
71 FGTileMgr::FGTileMgr():
81 FGTileMgr::~FGTileMgr() {
85 // Initialize the Tile Manager subsystem
86 int FGTileMgr::init() {
87 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
93 // instead it's just a lot easier to let any pending work flush
94 // through, rather than trying to arrest the queue and nuke all
95 // the various work at all the various stages and get everything
96 // cleaned up properly.
98 while ( ! attach_queue.empty() ) {
102 while ( ! model_queue.empty() ) {
103 #ifdef ENABLE_THREADS
104 FGDeferredModel* dm = model_queue.pop();
106 FGDeferredModel* dm = model_queue.front();
118 previous_bucket.make_bad();
119 current_bucket.make_bad();
121 longitude = latitude = -1000.0;
122 last_longitude = last_latitude = -1000.0;
128 // schedule a tile for loading
129 void FGTileMgr::sched_tile( const SGBucket& b ) {
130 // see if tile already exists in the cache
131 FGTileEntry *t = tile_cache.get_tile( b );
134 // make space in the cache
135 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
136 long index = tile_cache.get_oldest_tile();
138 FGTileEntry *old = tile_cache.get_tile( index );
139 old->disconnect_ssg_nodes();
140 delete_queue.push( old );
141 tile_cache.clear_entry( index );
143 // nothing to free ?!? forge ahead
148 // create a new entry
149 FGTileEntry *e = new FGTileEntry( b );
151 // insert the tile into the cache
152 if ( tile_cache.insert_tile( e ) ) {
153 // Schedule tile for loading
156 // insert failed (cache full with no available entries to
157 // delete.) Try again later
164 // schedule a needed buckets for loading
165 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
166 // sanity check (unfortunately needed!)
167 if ( longitude < -180.0 || longitude > 180.0
168 || latitude < -90.0 || latitude > 90.0 )
170 SG_LOG( SG_TERRAIN, SG_ALERT,
171 "Attempting to schedule tiles for bogus latitude and" );
172 SG_LOG( SG_TERRAIN, SG_ALERT,
173 "longitude. This is a FATAL error. Exiting!" );
177 SG_LOG( SG_TERRAIN, SG_INFO,
178 "scheduling needed tiles for " << longitude << " " << latitude );
180 // vis = fgGetDouble("/environment/visibility-m");
182 double tile_width = curr_bucket.get_width_m();
183 double tile_height = curr_bucket.get_height_m();
184 // cout << "tile width = " << tile_width << " tile_height = "
185 // << tile_height !<< endl;
187 xrange = (int)(vis / tile_width) + 1;
188 yrange = (int)(vis / tile_height) + 1;
189 if ( xrange < 1 ) { xrange /= 1; }
190 if ( yrange < 1 ) { yrange = 1; }
192 // note * 2 at end doubles cache size (for fdm and viewer)
193 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
196 cout << "xrange = " << xrange << " yrange = " << yrange << endl;
197 cout << "max cache size = " << tile_cache.get_max_cache_size()
198 << " current cache size = " << tile_cache.get_size() << endl;
203 // schedule center tile first so it can be loaded first
204 b = sgBucketOffset( longitude, latitude, 0, 0 );
209 // schedule next ring of 8 tiles
210 for ( x = -1; x <= 1; ++x ) {
211 for ( y = -1; y <= 1; ++y ) {
212 if ( x != 0 || y != 0 ) {
213 b = sgBucketOffset( longitude, latitude, x, y );
219 // schedule remaining tiles
220 for ( x = -xrange; x <= xrange; ++x ) {
221 for ( y = -yrange; y <= yrange; ++y ) {
222 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
223 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
231 void FGTileMgr::initialize_queue()
233 // First time through or we have teleported, initialize the
234 // system and load all relavant tiles
236 SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
237 // cout << "tile cache size = " << tile_cache.get_size() << endl;
239 // wipe/initialize tile cache
240 // tile_cache.init();
241 previous_bucket.make_bad();
243 // build the local area list and schedule tiles for loading
245 // start with the center tile and work out in concentric
248 double visibility_meters = fgGetDouble("/environment/visibility-m");
249 schedule_needed(visibility_meters, current_bucket);
251 // do we really want to lose this? CLO
253 // Now force a load of the center tile and inner ring so we
254 // have something to see in our first frame.
256 for ( i = 0; i < 9; ++i ) {
257 if ( load_queue.size() ) {
258 SG_LOG( SG_TERRAIN, SG_DEBUG,
259 "Load queue not empty, loading a tile" );
261 SGBucket pending = load_queue.front();
262 load_queue.pop_front();
263 load_tile( pending );
270 // given the current lon/lat (in degrees), fill in the array of local
271 // chunks. If the chunk isn't already in the cache, then read it from
273 int FGTileMgr::update( double lon, double lat, double visibility_meters ) {
274 sgdVec3 abs_pos_vector;
275 sgdCopyVec3(abs_pos_vector , globals->get_current_view()->get_absolute_view_pos());
276 return update( lon, lat, visibility_meters, abs_pos_vector,
277 current_bucket, previous_bucket,
278 globals->get_scenery()->get_center() );
282 int FGTileMgr::update( double lon, double lat, double visibility_meters,
283 sgdVec3 abs_pos_vector, SGBucket p_current,
284 SGBucket p_previous, Point3D center ) {
285 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
286 // << lon << " " << lat );
290 current_bucket = p_current;
291 previous_bucket = p_previous;
293 // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
294 // " lat " << lonlat[LAT] );
296 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
298 setCurrentTile( longitude, latitude);
300 // do tile load scheduling.
301 // Note that we need keep track of both viewer buckets and fdm buckets.
302 if ( state == Running ) {
303 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
304 if (!(current_bucket == previous_bucket )) {
305 // We've moved to a new bucket, we need to schedule any
306 // needed tiles for loading.
307 schedule_needed(visibility_meters, current_bucket);
309 } else if ( state == Start || state == Inited ) {
310 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
314 // load the next tile in the load queue (or authorize the next
315 // load in the case of the threaded tile pager)
320 // load the next model in the load queue. Currently this must
321 // happen in the render thread because model loading can trigger
322 // texture loading which involves use of the opengl api.
323 if ( !model_queue.empty() ) {
324 // cout << "loading next model ..." << endl;
325 // load the next tile in the queue
326 #ifdef ENABLE_THREADS
327 FGDeferredModel* dm = model_queue.pop();
329 FGDeferredModel* dm = model_queue.front();
333 ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
336 ssgEntity *obj_model =
337 globals->get_model_loader()->load_model(dm->get_model_path());
338 if ( obj_model != NULL ) {
339 dm->get_obj_trans()->addKid( obj_model );
342 catch (const sg_exception& exc)
344 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
347 dm->get_tile()->dec_pending_models();
351 // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
355 previous_bucket = current_bucket;
357 // activate loader thread one out of every 5 frames
358 if ( counter_hack == 0 ) {
359 // Notify the tile loader that it can load another tile
362 counter_hack = (counter_hack + 1) % 5;
365 if ( !attach_queue.empty() ) {
366 #ifdef ENABLE_THREADS
367 FGTileEntry* e = attach_queue.pop();
369 FGTileEntry* e = attach_queue.front();
372 e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
373 globals->get_scenery()->get_gnd_lights_branch(),
374 globals->get_scenery()->get_rwy_lights_branch() );
375 // cout << "Adding ssg nodes for "
378 if ( !delete_queue.empty() ) {
379 // cout << "delete queue = " << delete_queue.size() << endl;
381 while ( delete_queue.size() > 30 ) {
382 // uh oh, delete queue is blowing up, we aren't clearing
383 // it fast enough. Let's just panic, well not panic, but
384 // get real serious and agressively free up some tiles so
385 // we don't explode our memory usage.
387 SG_LOG( SG_TERRAIN, SG_ALERT,
388 "Alert: catching up on tile delete queue" );
390 FGTileEntry* e = delete_queue.front();
391 while ( !e->free_tile() );
396 FGTileEntry* e = delete_queue.front();
397 if ( e->free_tile() ) {
403 // no reason to update this if we haven't moved...
404 if ( longitude != last_longitude || latitude != last_latitude ) {
405 // update current elevation...
406 if (updateCurrentElevAtPos(abs_pos_vector, center)) {
407 last_longitude = longitude;
408 last_latitude = latitude;
419 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
420 void FGTileMgr::refresh_view_timestamps() {
421 SG_LOG( SG_TERRAIN, SG_INFO,
422 "Refreshing timestamps for " << current_bucket.get_center_lon()
423 << " " << current_bucket.get_center_lat() );
424 schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
428 // check and set current tile and scenery center...
429 void FGTileMgr::setCurrentTile(double longitude, double latitude) {
431 // check tile cache entry...
432 current_bucket.set_bucket( longitude, latitude );
433 if ( tile_cache.exists( current_bucket ) ) {
434 current_tile = tile_cache.get_tile( current_bucket );
435 globals->get_scenery()->set_next_center( current_tile->center );
437 SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
438 globals->get_scenery()->set_next_center( Point3D(0.0) );
443 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
452 // overridden with actual values if a terrain intersection is
454 double hit_elev = -9999.0;
455 double hit_radius = 0.0;
456 sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
459 if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
460 // scenery center has been properly defined so any hit
461 // should be valid (and not just luck)
462 hit = fgCurrentElev(abs_pos_vector,
464 current_tile->get_terra_transform(),
472 globals->get_scenery()->set_cur_elev( hit_elev );
473 globals->get_scenery()->set_cur_radius( hit_radius );
474 globals->get_scenery()->set_cur_normal( hit_normal );
476 globals->get_scenery()->set_cur_elev( -9999.0 );
477 globals->get_scenery()->set_cur_radius( 0.0 );
478 globals->get_scenery()->set_cur_normal( hit_normal );
484 void FGTileMgr::prep_ssg_nodes(float vis) {
486 // traverse the potentially viewable tile list and update range
487 // selector and transform
489 // just setup and call new function...
492 sgCopyVec3( up, globals->get_current_view()->get_world_up() );
495 center = globals->get_scenery()->get_center();
496 prep_ssg_nodes( vis, up, center );
501 void FGTileMgr::prep_ssg_nodes(float vis, sgVec3 up, Point3D center) {
503 // traverse the potentially viewable tile list and update range
504 // selector and transform
507 tile_cache.reset_traversal();
509 while ( ! tile_cache.at_end() ) {
510 // cout << "processing a tile" << endl;
511 if ( (e = tile_cache.get_current()) ) {
512 e->prep_ssg_node( center, up, vis);
514 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");