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>
37 #include <simgear/scene/model/modellib.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/viewer.hxx>
43 #include "newcache.hxx"
44 #include "scenery.hxx"
45 #include "tilemgr.hxx"
47 #define TEST_LAST_HIT_CACHE
50 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
51 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
53 queue<FGTileEntry *> FGTileMgr::attach_queue;
54 queue<FGDeferredModel *> FGTileMgr::model_queue;
55 #endif // ENABLE_THREADS
56 queue<FGTileEntry *> FGTileMgr::delete_queue;
60 FGTileMgr::FGTileMgr():
70 FGTileMgr::~FGTileMgr() {
74 // Initialize the Tile Manager subsystem
75 int FGTileMgr::init() {
76 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
82 // instead it's just a lot easier to let any pending work flush
83 // through, rather than trying to arrest the queue and nuke all
84 // the various work at all the various stages and get everything
85 // cleaned up properly.
87 while ( ! attach_queue.empty() ) {
91 while ( ! model_queue.empty() ) {
93 FGDeferredModel* dm = model_queue.pop();
95 FGDeferredModel* dm = model_queue.front();
107 previous_bucket.make_bad();
108 current_bucket.make_bad();
110 longitude = latitude = -1000.0;
111 last_longitude = last_latitude = -1000.0;
117 // schedule a tile for loading
118 void FGTileMgr::sched_tile( const SGBucket& b ) {
119 // see if tile already exists in the cache
120 FGTileEntry *t = tile_cache.get_tile( b );
123 // make space in the cache
124 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
125 long index = tile_cache.get_oldest_tile();
127 FGTileEntry *old = tile_cache.get_tile( index );
128 old->disconnect_ssg_nodes();
129 delete_queue.push( old );
130 tile_cache.clear_entry( index );
132 // nothing to free ?!? forge ahead
137 // create a new entry
138 FGTileEntry *e = new FGTileEntry( b );
140 // insert the tile into the cache
141 if ( tile_cache.insert_tile( e ) ) {
142 // Schedule tile for loading
145 // insert failed (cache full with no available entries to
146 // delete.) Try again later
153 // schedule a needed buckets for loading
154 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
155 // sanity check (unfortunately needed!)
156 if ( longitude < -180.0 || longitude > 180.0
157 || latitude < -90.0 || latitude > 90.0 )
159 SG_LOG( SG_TERRAIN, SG_ALERT,
160 "Attempting to schedule tiles for bogus lon and lat = ("
161 << longitude << "," << latitude << ")" );
162 SG_LOG( SG_TERRAIN, SG_ALERT,
163 "This is a FATAL error. Exiting!" );
167 SG_LOG( SG_TERRAIN, SG_INFO,
168 "scheduling needed tiles for " << longitude << " " << latitude );
170 // vis = fgGetDouble("/environment/visibility-m");
172 double tile_width = curr_bucket.get_width_m();
173 double tile_height = curr_bucket.get_height_m();
174 // cout << "tile width = " << tile_width << " tile_height = "
175 // << tile_height !<< endl;
177 xrange = (int)(vis / tile_width) + 1;
178 yrange = (int)(vis / tile_height) + 1;
179 if ( xrange < 1 ) { xrange /= 1; }
180 if ( yrange < 1 ) { yrange = 1; }
182 // note * 2 at end doubles cache size (for fdm and viewer)
183 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
186 cout << "xrange = " << xrange << " yrange = " << yrange << endl;
187 cout << "max cache size = " << tile_cache.get_max_cache_size()
188 << " current cache size = " << tile_cache.get_size() << endl;
193 // schedule center tile first so it can be loaded first
194 b = sgBucketOffset( longitude, latitude, 0, 0 );
199 // schedule next ring of 8 tiles
200 for ( x = -1; x <= 1; ++x ) {
201 for ( y = -1; y <= 1; ++y ) {
202 if ( x != 0 || y != 0 ) {
203 b = sgBucketOffset( longitude, latitude, x, y );
209 // schedule remaining tiles
210 for ( x = -xrange; x <= xrange; ++x ) {
211 for ( y = -yrange; y <= yrange; ++y ) {
212 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
213 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
221 void FGTileMgr::initialize_queue()
223 // First time through or we have teleported, initialize the
224 // system and load all relavant tiles
226 SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
227 // cout << "tile cache size = " << tile_cache.get_size() << endl;
229 // wipe/initialize tile cache
230 // tile_cache.init();
231 previous_bucket.make_bad();
233 // build the local area list and schedule tiles for loading
235 // start with the center tile and work out in concentric
238 double visibility_meters = fgGetDouble("/environment/visibility-m");
239 schedule_needed(visibility_meters, current_bucket);
241 // do we really want to lose this? CLO
243 // Now force a load of the center tile and inner ring so we
244 // have something to see in our first frame.
246 for ( i = 0; i < 9; ++i ) {
247 if ( load_queue.size() ) {
248 SG_LOG( SG_TERRAIN, SG_DEBUG,
249 "Load queue not empty, loading a tile" );
251 SGBucket pending = load_queue.front();
252 load_queue.pop_front();
253 load_tile( pending );
261 * Update the various queues maintained by the tilemagr (private
262 * internal function, do not call directly.)
264 void FGTileMgr::update_queues()
266 // load the next model in the load queue. Currently this must
267 // happen in the render thread because model loading can trigger
268 // texture loading which involves use of the opengl api.
269 if ( !model_queue.empty() ) {
270 // cout << "loading next model ..." << endl;
271 // load the next tile in the queue
272 #ifdef ENABLE_THREADS
273 FGDeferredModel* dm = model_queue.pop();
275 FGDeferredModel* dm = model_queue.front();
279 ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
282 ssgEntity *obj_model =
283 globals->get_model_lib()->load_model( globals->get_fg_root(),
284 dm->get_model_path(),
285 globals->get_props(),
286 globals->get_sim_time_sec() );
287 if ( obj_model != NULL ) {
288 dm->get_obj_trans()->addKid( obj_model );
291 catch (const sg_exception& exc)
293 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
296 dm->get_tile()->dec_pending_models();
300 // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
302 // activate loader thread one out of every 5 frames
303 if ( counter_hack == 0 ) {
304 // Notify the tile loader that it can load another tile
307 counter_hack = (counter_hack + 1) % 5;
310 if ( !attach_queue.empty() ) {
311 #ifdef ENABLE_THREADS
312 FGTileEntry* e = attach_queue.pop();
314 FGTileEntry* e = attach_queue.front();
317 e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
318 globals->get_scenery()->get_gnd_lights_root(),
319 globals->get_scenery()->get_rwy_lights_root(),
320 globals->get_scenery()->get_taxi_lights_root() );
321 // cout << "Adding ssg nodes for "
324 if ( !delete_queue.empty() ) {
325 // cout << "delete queue = " << delete_queue.size() << endl;
327 while ( delete_queue.size() > 30 ) {
328 // uh oh, delete queue is blowing up, we aren't clearing
329 // it fast enough. Let's just panic, well not panic, but
330 // get real serious and agressively free up some tiles so
331 // we don't explode our memory usage.
333 SG_LOG( SG_TERRAIN, SG_ALERT,
334 "Alert: catching up on tile delete queue" );
336 FGTileEntry* e = delete_queue.front();
337 while ( !e->free_tile() );
342 FGTileEntry* e = delete_queue.front();
343 if ( e->free_tile() ) {
351 // given the current lon/lat (in degrees), fill in the array of local
352 // chunks. If the chunk isn't already in the cache, then read it from
354 int FGTileMgr::update( double visibility_meters )
356 SGLocation *location = globals->get_current_view()->getSGLocation();
357 sgdVec3 abs_pos_vector;
358 sgdCopyVec3( abs_pos_vector,
359 globals->get_current_view()->get_absolute_view_pos() );
360 return update( location, visibility_meters, abs_pos_vector );
364 int FGTileMgr::update( SGLocation *location, double visibility_meters,
365 sgdVec3 abs_pos_vector )
367 longitude = location->getLongitude_deg();
368 latitude = location->getLatitude_deg();
369 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
370 // << longitude << " " << latatitude );
372 current_bucket.set_bucket( longitude, latitude );
373 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
374 // << current_bucket );
375 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
377 // set global scenery center from current tile center
378 current_tile = tile_cache.get_tile( current_bucket );
379 if ( current_tile != NULL ) {
380 globals->get_scenery()->set_next_center( current_tile->center );
382 SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
383 globals->get_scenery()->set_next_center( Point3D(0.0) );
386 // do tile load scheduling.
387 // Note that we need keep track of both viewer buckets and fdm buckets.
388 if ( state == Running ) {
389 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
390 if (!(current_bucket == previous_bucket )) {
391 // We've moved to a new bucket, we need to schedule any
392 // needed tiles for loading.
393 schedule_needed(visibility_meters, current_bucket);
395 } else if ( state == Start || state == Inited ) {
396 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
400 // load the next tile in the load queue (or authorize the next
401 // load in the case of the threaded tile pager)
408 previous_bucket = current_bucket;
410 // no reason to update this if we haven't moved...
411 if ( longitude != last_longitude || latitude != last_latitude ) {
412 // update current elevation...
413 if ( updateCurrentElevAtPos( abs_pos_vector,
414 location->get_tile_center() ) )
416 last_longitude = longitude;
417 last_latitude = latitude;
425 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
426 void FGTileMgr::refresh_view_timestamps() {
427 SG_LOG( SG_TERRAIN, SG_INFO,
428 "Refreshing timestamps for " << current_bucket.get_center_lon()
429 << " " << current_bucket.get_center_lat() );
430 schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
434 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
438 sgdSetVec3( sc, center[0], center[1], center[2]);
440 // overridden with actual values if a terrain intersection is
442 double hit_elev = -9999.0;
443 double hit_radius = 0.0;
444 sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
447 if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
448 // scenery center has been properly defined so any hit should
449 // be valid (and not just luck)
450 hit = fgCurrentElev(abs_pos_vector,
452 // uncomment next paramater to fly under
453 // bridges and a slightly faster algorithm
454 // but you won't be able to land on aircraft carriers
455 // current_tile->get_terra_transform(),
463 // cout << "elev = " << hit_elev << " " << hit_radius << endl;
464 globals->get_scenery()->set_cur_elev( hit_elev );
465 globals->get_scenery()->set_cur_radius( hit_radius );
466 globals->get_scenery()->set_cur_normal( hit_normal );
468 globals->get_scenery()->set_cur_elev( -9999.0 );
469 globals->get_scenery()->set_cur_radius( 0.0 );
470 globals->get_scenery()->set_cur_normal( hit_normal );
476 void FGTileMgr::prep_ssg_nodes( SGLocation *location, float vis ) {
478 // traverse the potentially viewable tile list and update range
479 // selector and transform
481 Point3D center = location->get_tile_center();
482 float *up = location->get_world_up();
485 tile_cache.reset_traversal();
487 while ( ! tile_cache.at_end() ) {
488 // cout << "processing a tile" << endl;
489 if ( (e = tile_cache.get_current()) ) {
490 e->prep_ssg_node( center, up, vis);
492 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");