]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
move callback registration functions to fg_os_common.cxx
[flightgear.git] / src / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  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/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>
36
37 #include <Main/globals.hxx>
38 #include <Main/fg_props.hxx>
39 #include <Main/viewer.hxx>
40 #include <Scripting/NasalSys.hxx>
41
42 #include "newcache.hxx"
43 #include "scenery.hxx"
44 #include "tilemgr.hxx"
45
46 #define TEST_LAST_HIT_CACHE
47
48 #if defined(ENABLE_THREADS)
49 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
50 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
51 #else
52 queue<FGTileEntry *> FGTileMgr::attach_queue;
53 queue<FGDeferredModel *> FGTileMgr::model_queue;
54 #endif // ENABLE_THREADS
55 queue<FGTileEntry *> FGTileMgr::delete_queue;
56
57 // Constructor
58 FGTileMgr::FGTileMgr():
59     state( Start ),
60     current_tile( NULL ),
61     vis( 16000 )
62 {
63 }
64
65
66 // Destructor
67 FGTileMgr::~FGTileMgr() {
68 }
69
70
71 // Initialize the Tile Manager subsystem
72 int FGTileMgr::init() {
73     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
74
75     tile_cache.init();
76
77 #if 0
78
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.
83
84     while ( ! attach_queue.empty() ) {
85         attach_queue.pop();
86     }
87
88     while ( ! model_queue.empty() ) {
89 #if defined(ENABLE_THREADS)
90         FGDeferredModel* dm = model_queue.pop();
91 #else
92         FGDeferredModel* dm = model_queue.front();
93         model_queue.pop();
94 #endif
95         delete dm;
96     }
97     loader.reinit();
98 #endif
99
100     state = Inited;
101
102     previous_bucket.make_bad();
103     current_bucket.make_bad();
104
105     longitude = latitude = -1000.0;
106
107     return 1;
108 }
109
110
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 );
115
116     if ( t == NULL ) {
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();
120             if ( index >= 0 ) {
121                 FGTileEntry *old = tile_cache.get_tile( index );
122                 // OSGFIXME
123 //                 shadows->deleteOccluderFromTile( (ssgBranch *) old->get_terra_transform() );
124                 old->disconnect_ssg_nodes();
125                 delete_queue.push( old );
126                 tile_cache.clear_entry( index );
127             } else {
128                 // nothing to free ?!? forge ahead
129                 break;
130             }
131         }
132
133         // create a new entry
134         FGTileEntry *e = new FGTileEntry( b );
135
136         // insert the tile into the cache
137         if ( tile_cache.insert_tile( e ) ) {
138             // Schedule tile for loading
139             loader.add( e );
140         } else {
141             // insert failed (cache full with no available entries to
142             // delete.)  Try again later
143             delete e;
144         }
145     } else {
146         t->set_inner_ring( is_inner_ring );
147     }
148 }
149
150
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 )
156     {
157         SG_LOG( SG_TERRAIN, SG_ALERT,
158                 "Attempting to schedule tiles for bogus lon and lat  = ("
159                 << longitude << "," << latitude << ")" );
160         return;         // FIXME
161         SG_LOG( SG_TERRAIN, SG_ALERT,
162                 "This is a FATAL error.  Exiting!" );
163         exit(-1);
164     }
165
166     SG_LOG( SG_TERRAIN, SG_INFO,
167             "scheduling needed tiles for " << longitude << " " << latitude );
168
169     // vis = fgGetDouble("/environment/visibility-m");
170
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;
175
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; }
180
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;
186
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
190     // location.
191     tile_cache.clear_inner_ring_flags();
192
193     SGBucket b;
194
195     // schedule center tile first so it can be loaded first
196     b = sgBucketOffset( longitude, latitude, 0, 0 );
197     sched_tile( b, true );
198
199     int x, y;
200
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 );
207             }
208         }
209     }
210
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 );
217             }
218         }
219     }
220 }
221
222
223 void FGTileMgr::initialize_queue()
224 {
225     // First time through or we have teleported, initialize the
226     // system and load all relavant tiles
227
228     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
229             << current_bucket );
230     // cout << "tile cache size = " << tile_cache.get_size() << endl;
231
232     // wipe/initialize tile cache
233     // tile_cache.init();
234     previous_bucket.make_bad();
235
236     // build the local area list and schedule tiles for loading
237
238     // start with the center tile and work out in concentric
239     // "rings"
240
241     double visibility_meters = fgGetDouble("/environment/visibility-m");
242     schedule_needed(visibility_meters, current_bucket);
243
244     // do we really want to lose this? CLO
245 #if 0
246     // Now force a load of the center tile and inner ring so we
247     // have something to see in our first frame.
248     int i;
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" );
253
254             SGBucket pending = load_queue.front();
255             load_queue.pop_front();
256             load_tile( pending );
257         }
258     }
259 #endif
260 }
261
262 /**
263  * return current status of queues
264  *
265  */
266
267 bool FGTileMgr::all_queues_empty() {
268         return attach_queue.empty() && model_queue.empty();
269 }
270
271 osg::Node*
272 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
273 {
274     osg::Node* result = 0;
275     try {
276         result =
277             globals->get_model_lib()->load_model(".",
278                                                  modelPath,
279                                                  globals->get_props(),
280                                                  globals->get_sim_time_sec(),
281                                                  cacheModel,
282                                                  new FGNasalModelData );
283     } catch (const sg_io_exception& exc) {
284         string m(exc.getMessage());
285         m += " ";
286         m += exc.getLocation().asString();
287         SG_LOG( SG_ALL, SG_ALERT, m );
288     } catch (const sg_exception& exc) { // XXX may be redundant
289         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
290     }
291     return result;
292 }
293
294 /**
295  * Update the various queues maintained by the tilemagr (private
296  * internal function, do not call directly.)
297  */
298 void FGTileMgr::update_queues()
299 {
300     // load the next model in the load queue.  Currently this must
301     // happen in the render thread because model loading can trigger
302     // texture loading which involves use of the opengl api.  Skip any
303     // models belonging to not loaded tiles (i.e. the tile was removed
304     // before we were able to load some of the associated models.)
305     if ( !model_queue.empty() ) {
306         bool processed_one = false;
307
308         while ( model_queue.size() > 200 || processed_one == false ) {
309             processed_one = true;
310
311             if ( model_queue.size() > 200 ) {
312                 SG_LOG( SG_TERRAIN, SG_INFO,
313                         "Alert: catching up on model load queue" );
314             }
315
316             // cout << "loading next model ..." << endl;
317             // load the next tile in the queue
318 #if defined(ENABLE_THREADS)
319             FGDeferredModel* dm = model_queue.pop();
320 #else
321             FGDeferredModel* dm = model_queue.front();
322             model_queue.pop();
323 #endif
324
325             // only load the model if the tile still exists in the
326             // tile cache
327             FGTileEntry *t = tile_cache.get_tile( dm->get_bucket() );
328             if ( t != NULL ) {
329               //OSGFIXME
330 //                 ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
331                 try {
332                     osg::Node *obj_model =
333                         globals->get_model_lib()->load_model( ".",
334                                                   dm->get_model_path(),
335                                                   globals->get_props(),
336                                                   globals->get_sim_time_sec(),
337                                                   dm->get_cache_state(),
338                                                   new FGNasalModelData );
339                     if ( obj_model != NULL ) {
340                         dm->get_obj_trans()->addChild( obj_model );
341               //OSGFIXME
342 //                         shadows->addOccluder( (ssgBranch *) obj_model->getParent(0),
343 //                             SGShadowVolume::occluderTypeTileObject,
344 //                             (ssgBranch *) dm->get_tile()->get_terra_transform());
345                     }
346                 } catch (const sg_io_exception& exc) {
347                                         string m(exc.getMessage());
348                                         m += " ";
349                                         m += exc.getLocation().asString();
350                     SG_LOG( SG_ALL, SG_ALERT, m );
351                 } catch (const sg_exception& exc) { // XXX may be redundant
352                     SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
353                 }
354                 
355                 dm->get_tile()->dec_pending_models();
356             }
357             delete dm;
358         }
359     }
360     
361     // Notify the tile loader that it can load another tile
362     loader.update();
363
364     if ( !attach_queue.empty() ) {
365 #if defined(ENABLE_THREADS)
366         FGTileEntry* e = attach_queue.pop();
367 #else
368         FGTileEntry* e = attach_queue.front();
369         attach_queue.pop();
370 #endif
371         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch() );
372         // cout << "Adding ssg nodes for "
373     }
374
375     if ( !delete_queue.empty() ) {
376         // cout << "delete queue = " << delete_queue.size() << endl;
377         bool processed_one = false;
378
379         while ( delete_queue.size() > 30 || processed_one == false ) {
380             processed_one = true;
381
382             if ( delete_queue.size() > 30 ) {
383                 // uh oh, delete queue is blowing up, we aren't clearing
384                 // it fast enough.  Let's just panic, well not panic, but
385                 // get real serious and agressively free up some tiles so
386                 // we don't explode our memory usage.
387
388                 SG_LOG( SG_TERRAIN, SG_WARN,
389                         "Warning: catching up on tile delete queue" );
390             }
391
392             FGTileEntry* e = delete_queue.front();
393             if ( e->free_tile() ) {
394                 delete_queue.pop();
395                 delete e;
396             }
397         }
398     }
399 }
400
401
402 // given the current lon/lat (in degrees), fill in the array of local
403 // chunks.  If the chunk isn't already in the cache, then read it from
404 // disk.
405 int FGTileMgr::update( double visibility_meters )
406 {
407     SGLocation *location = globals->get_current_view()->getSGLocation();
408     return update( location, visibility_meters );
409 }
410
411
412 int FGTileMgr::update( SGLocation *location, double visibility_meters )
413 {
414     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
415
416     longitude = location->getLongitude_deg();
417     latitude = location->getLatitude_deg();
418     // add 1.0m to the max altitude to give a little leeway to the
419     // ground reaction code.
420     altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
421
422     // if current altitude is apparently not initialized, set max
423     // altitude to something big.
424     if ( altitude_m < -1000 ) {
425         altitude_m = 10000;
426     }
427     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
428     //         << longitude << " " << latatitude );
429
430     current_bucket.set_bucket( longitude, latitude );
431     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
432     //         << current_bucket );
433     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
434
435     // do tile load scheduling. 
436     // Note that we need keep track of both viewer buckets and fdm buckets.
437     if ( state == Running ) {
438         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
439         if (!(current_bucket == previous_bucket )) {
440             // We've moved to a new bucket, we need to schedule any
441             // needed tiles for loading.
442             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
443             schedule_needed(visibility_meters, current_bucket);
444         }
445     } else if ( state == Start || state == Inited ) {
446         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
447 //        initialize_queue();
448         state = Running;
449
450         // load the next tile in the load queue (or authorize the next
451         // load in the case of the threaded tile pager)
452         loader.update();
453     }
454
455     update_queues();
456
457     // save bucket...
458     previous_bucket = current_bucket;
459
460     return 1;
461 }
462
463
464 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
465 void FGTileMgr::refresh_view_timestamps() {
466     SG_LOG( SG_TERRAIN, SG_INFO,
467             "Refreshing timestamps for " << current_bucket.get_center_lon()
468             << " " << current_bucket.get_center_lat() );
469     if ( longitude >= -180.0 && longitude <= 180.0 
470          && latitude >= -90.0 && latitude <= 90.0 )
471     {
472         schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
473     }
474 }
475
476 void FGTileMgr::prep_ssg_nodes(float vis) {
477
478     // traverse the potentially viewable tile list and update range
479     // selector and transform
480
481     FGTileEntry *e;
482     tile_cache.reset_traversal();
483
484     while ( ! tile_cache.at_end() ) {
485         // cout << "processing a tile" << endl;
486         if ( (e = tile_cache.get_current()) ) {
487             e->prep_ssg_node(vis);
488         } else {
489             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
490         }
491         tile_cache.next();
492     }
493 }
494
495 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
496 {
497   // sanity check (unfortunately needed!)
498   if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
499     return false;
500   
501   SGBucket bucket(lon, lat);
502   FGTileEntry *te = tile_cache.get_tile(bucket);
503   if (!te || !te->is_loaded())
504     return false;
505
506   // Traverse all tiles required to be there for the given visibility.
507   // This uses exactly the same algorithm like the tile scheduler.
508   double tile_width = bucket.get_width_m();
509   double tile_height = bucket.get_height_m();
510   
511   int xrange = (int)fabs(range_m / tile_width) + 1;
512   int yrange = (int)fabs(range_m / tile_height) + 1;
513   
514   for ( int x = -xrange; x <= xrange; ++x ) {
515     for ( int y = -yrange; y <= yrange; ++y ) {
516       // We have already checked for the center tile.
517       if ( x != 0 || y != 0 ) {
518         SGBucket b = sgBucketOffset( lon, lat, x, y );
519         FGTileEntry *te = tile_cache.get_tile(b);
520         if (!te || !te->is_loaded())
521           return false;
522       }
523     }
524   }
525
526   // Survived all tests.
527   return true;
528 }