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