]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Check for the plib version when using display lists, just to be sure.
[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  - curt@infoplane.com
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., 675 Mass Ave, Cambridge, MA 02139, 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
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/viewer.hxx>
42
43 #include "newcache.hxx"
44 #include "scenery.hxx"
45 #include "tilemgr.hxx"
46
47 #define TEST_LAST_HIT_CACHE
48
49 #if defined(ENABLE_THREADS) && ENABLE_THREADS
50 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
51 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
52 #else
53 queue<FGTileEntry *> FGTileMgr::attach_queue;
54 queue<FGDeferredModel *> FGTileMgr::model_queue;
55 #endif // ENABLE_THREADS
56 queue<FGTileEntry *> FGTileMgr::delete_queue;
57
58 bool FGTileMgr::tile_filter = true;
59
60 // Constructor
61 FGTileMgr::FGTileMgr():
62     state( Start ),
63     current_tile( NULL ),
64     vis( 16000 )
65 {
66 }
67
68
69 // Destructor
70 FGTileMgr::~FGTileMgr() {
71 }
72
73
74 // Initialize the Tile Manager subsystem
75 int FGTileMgr::init() {
76     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
77
78     tile_cache.init();
79
80 #if 0
81
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.
86
87     while ( ! attach_queue.empty() ) {
88         attach_queue.pop();
89     }
90
91     while ( ! model_queue.empty() ) {
92 #if defined(ENABLE_THREADS) && ENABLE_THREADS
93         FGDeferredModel* dm = model_queue.pop();
94 #else
95         FGDeferredModel* dm = model_queue.front();
96         model_queue.pop();
97 #endif
98         delete dm;
99     }
100     loader.reinit();
101 #endif
102
103     hit_list.clear();
104
105     state = Inited;
106
107     previous_bucket.make_bad();
108     current_bucket.make_bad();
109
110     longitude = latitude = -1000.0;
111
112     return 1;
113 }
114
115
116 // schedule a tile for loading
117 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
118     // see if tile already exists in the cache
119     FGTileEntry *t = tile_cache.get_tile( b );
120
121     if ( t == NULL ) {
122         // make space in the cache
123         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
124             long index = tile_cache.get_oldest_tile();
125             if ( index >= 0 ) {
126                 FGTileEntry *old = tile_cache.get_tile( index );
127                 old->disconnect_ssg_nodes();
128                 delete_queue.push( old );
129                 tile_cache.clear_entry( index );
130             } else {
131                 // nothing to free ?!? forge ahead
132                 break;
133             }
134         }
135
136         // create a new entry
137         FGTileEntry *e = new FGTileEntry( b );
138
139         // insert the tile into the cache
140         if ( tile_cache.insert_tile( e ) ) {
141             // Schedule tile for loading
142             loader.add( e );
143         } else {
144             // insert failed (cache full with no available entries to
145             // delete.)  Try again later
146             delete e;
147         }
148     } else {
149         t->set_inner_ring( is_inner_ring );
150     }
151 }
152
153
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 )
159     {
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!" );
165         exit(-1);        
166     }
167
168     SG_LOG( SG_TERRAIN, SG_INFO,
169             "scheduling needed tiles for " << longitude << " " << latitude );
170
171     // vis = fgGetDouble("/environment/visibility-m");
172
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;
177
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; }
182
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 );
185     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
186     // cout << "max cache size = " << tile_cache.get_max_cache_size()
187     //      << " current cache size = " << tile_cache.get_size() << endl;
188
189     // clear the inner ring flags so we can set them below.  This
190     // prevents us from having "true" entries we aren't able to find
191     // to get rid of if we teleport a long ways away from the current
192     // location.
193     tile_cache.clear_inner_ring_flags();
194
195     SGBucket b;
196
197     // schedule center tile first so it can be loaded first
198     b = sgBucketOffset( longitude, latitude, 0, 0 );
199     sched_tile( b, true );
200
201     int x, y;
202
203     // schedule next ring of 8 tiles
204     for ( x = -1; x <= 1; ++x ) {
205         for ( y = -1; y <= 1; ++y ) {
206             if ( x != 0 || y != 0 ) {
207                 b = sgBucketOffset( longitude, latitude, x, y );
208                 sched_tile( b, true );
209             }
210         }
211     }
212
213     // schedule remaining tiles
214     for ( x = -xrange; x <= xrange; ++x ) {
215         for ( y = -yrange; y <= yrange; ++y ) {
216             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
217                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
218                 sched_tile( b, false );
219             }
220         }
221     }
222 }
223
224
225 void FGTileMgr::initialize_queue()
226 {
227     // First time through or we have teleported, initialize the
228     // system and load all relavant tiles
229
230     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
231             << current_bucket );
232     // cout << "tile cache size = " << tile_cache.get_size() << endl;
233
234     // wipe/initialize tile cache
235     // tile_cache.init();
236     previous_bucket.make_bad();
237
238     // build the local area list and schedule tiles for loading
239
240     // start with the center tile and work out in concentric
241     // "rings"
242
243     double visibility_meters = fgGetDouble("/environment/visibility-m");
244     schedule_needed(visibility_meters, current_bucket);
245
246     // do we really want to lose this? CLO
247 #if 0
248     // Now force a load of the center tile and inner ring so we
249     // have something to see in our first frame.
250     int i;
251     for ( i = 0; i < 9; ++i ) {
252         if ( load_queue.size() ) {
253             SG_LOG( SG_TERRAIN, SG_DEBUG, 
254                     "Load queue not empty, loading a tile" );
255
256             SGBucket pending = load_queue.front();
257             load_queue.pop_front();
258             load_tile( pending );
259         }
260     }
261 #endif
262 }
263
264 /**
265  * return current status of queues
266  *
267  */
268
269 bool FGTileMgr::all_queues_empty() {
270         return attach_queue.empty() && model_queue.empty();
271 }
272
273
274 /**
275  * Update the various queues maintained by the tilemagr (private
276  * internal function, do not call directly.)
277  */
278 void FGTileMgr::update_queues()
279 {
280     // load the next model in the load queue.  Currently this must
281     // happen in the render thread because model loading can trigger
282     // texture loading which involves use of the opengl api.  Skip any
283     // models belonging to not loaded tiles (i.e. the tile was removed
284     // before we were able to load some of the associated models.)
285     if ( !model_queue.empty() ) {
286         bool processed_one = false;
287
288         while ( model_queue.size() > 200 || processed_one == false ) {
289             processed_one = true;
290
291             if ( model_queue.size() > 200 ) {
292                 SG_LOG( SG_TERRAIN, SG_INFO,
293                         "Alert: catching up on model load queue" );
294             }
295
296             // cout << "loading next model ..." << endl;
297             // load the next tile in the queue
298 #if defined(ENABLE_THREADS) && ENABLE_THREADS
299             FGDeferredModel* dm = model_queue.pop();
300 #else
301             FGDeferredModel* dm = model_queue.front();
302             model_queue.pop();
303 #endif
304
305             // only load the model if the tile still exists in the
306             // tile cache
307             FGTileEntry *t = tile_cache.get_tile( dm->get_bucket() );
308             if ( t != NULL ) {
309                 ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
310                 try {
311                     ssgEntity *obj_model =
312                         globals->get_model_lib()->load_model( ".",
313                                                   dm->get_model_path(),
314                                                   globals->get_props(),
315                                                   globals->get_sim_time_sec() );
316                     if ( obj_model != NULL ) {
317                         dm->get_obj_trans()->addKid( obj_model );
318                     }
319                 } catch (const sg_exception& exc) {
320                     SG_LOG( SG_ALL, SG_ALERT, exc.getMessage() );
321                 }
322                 
323                 dm->get_tile()->dec_pending_models();
324             }
325             delete dm;
326         }
327     }
328     
329     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
330
331     // Notify the tile loader that it can load another tile
332     loader.update();
333
334     if ( !attach_queue.empty() ) {
335 #if defined(ENABLE_THREADS) && ENABLE_THREADS
336         FGTileEntry* e = attach_queue.pop();
337 #else
338         FGTileEntry* e = attach_queue.front();
339         attach_queue.pop();
340 #endif
341         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
342                           globals->get_scenery()->get_gnd_lights_root(),
343                           globals->get_scenery()->get_vasi_lights_root(),
344                           globals->get_scenery()->get_rwy_lights_root(),
345                           globals->get_scenery()->get_taxi_lights_root() );
346         // cout << "Adding ssg nodes for "
347     }
348
349     if ( !delete_queue.empty() ) {
350         // cout << "delete queue = " << delete_queue.size() << endl;
351         bool processed_one = false;
352
353         while ( delete_queue.size() > 30 || processed_one == false ) {
354             processed_one = true;
355
356             if ( delete_queue.size() > 30 ) {
357                 // uh oh, delete queue is blowing up, we aren't clearing
358                 // it fast enough.  Let's just panic, well not panic, but
359                 // get real serious and agressively free up some tiles so
360                 // we don't explode our memory usage.
361
362                 SG_LOG( SG_TERRAIN, SG_ALERT,
363                         "Alert: catching up on tile delete queue" );
364             }
365
366             FGTileEntry* e = delete_queue.front();
367             if ( e->free_tile() ) {
368                 delete_queue.pop();
369                 delete e;
370             }
371         }
372     }
373 }
374
375
376 // given the current lon/lat (in degrees), fill in the array of local
377 // chunks.  If the chunk isn't already in the cache, then read it from
378 // disk.
379 int FGTileMgr::update( double visibility_meters )
380 {
381     SGLocation *location = globals->get_current_view()->getSGLocation();
382     sgdVec3 abs_pos_vector;
383     sgdCopyVec3( abs_pos_vector,
384                  globals->get_current_view()->get_absolute_view_pos() );
385     return update( location, visibility_meters, abs_pos_vector );
386 }
387
388
389 int FGTileMgr::update( SGLocation *location, double visibility_meters,
390                        sgdVec3 abs_pos_vector )
391 {
392     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
393
394     longitude = location->getLongitude_deg();
395     latitude = location->getLatitude_deg();
396     // add 1.0m to the max altitude to give a little leeway to the
397     // ground reaction code.
398     altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
399
400     // if current altitude is apparently not initialized, set max
401     // altitude to something big.
402     if ( altitude_m < -1000 ) {
403         altitude_m = 10000;
404     }
405     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
406     //         << longitude << " " << latatitude );
407
408     current_bucket.set_bucket( longitude, latitude );
409     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
410     //         << current_bucket );
411     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
412
413     // set global scenery center from current tile center
414     current_tile = tile_cache.get_tile( current_bucket );
415     if ( current_tile != NULL ) {
416         globals->get_scenery()->set_next_center( current_tile->center );
417     } else {
418         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
419         globals->get_scenery()->set_next_center( Point3D(0.0) );
420     }
421
422     // do tile load scheduling. 
423     // Note that we need keep track of both viewer buckets and fdm buckets.
424     if ( state == Running ) {
425         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
426         if (!(current_bucket == previous_bucket )) {
427             // We've moved to a new bucket, we need to schedule any
428             // needed tiles for loading.
429             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
430             schedule_needed(visibility_meters, current_bucket);
431         }
432     } else if ( state == Start || state == Inited ) {
433         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
434 //        initialize_queue();
435         state = Running;
436
437         // load the next tile in the load queue (or authorize the next
438         // load in the case of the threaded tile pager)
439         loader.update();
440     }
441
442     update_queues();
443
444     // save bucket...
445     previous_bucket = current_bucket;
446
447     updateCurrentElevAtPos( abs_pos_vector, altitude_m,
448                             location->get_tile_center() );
449
450     return 1;
451 }
452
453
454 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
455 void FGTileMgr::refresh_view_timestamps() {
456     SG_LOG( SG_TERRAIN, SG_INFO,
457             "Refreshing timestamps for " << current_bucket.get_center_lon()
458             << " " << current_bucket.get_center_lat() );
459     if ( longitude >= -180.0 && longitude <= 180.0 
460          && latitude >= -90.0 && latitude <= 90.0 )
461     {
462         schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
463     }
464 }
465
466
467 int FGTileMgr::updateCurrentElevAtPos( sgdVec3 abs_pos_vector,
468                                        double max_alt_m,
469                                        Point3D center)
470 {
471     sgdVec3 sc;
472
473     sgdSetVec3( sc, center[0], center[1], center[2]);
474
475     // overridden with actual values if a terrain intersection is
476     // found
477     double hit_elev = -9999.0;
478     double hit_radius = 0.0;
479     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
480     
481     bool hit = false;
482     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
483         // scenery center has been properly defined so any hit should
484         // be valid (and not just luck)
485         hit = fgCurrentElev(abs_pos_vector,
486                             max_alt_m,
487                             sc,
488                 // uncomment next paramater to fly under
489                 // bridges and a slightly faster algorithm
490                 // but you won't be able to land on aircraft carriers
491                             // current_tile->get_terra_transform(),
492                             &hit_list,
493                             &hit_elev,
494                             &hit_radius,
495                             hit_normal);
496     }
497
498     if ( hit ) {
499         // cout << "elev = " << hit_elev << " " << hit_radius << endl;
500         globals->get_scenery()->set_cur_elev( hit_elev );
501         globals->get_scenery()->set_cur_radius( hit_radius );
502         globals->get_scenery()->set_cur_normal( hit_normal );
503     } else {
504         globals->get_scenery()->set_cur_elev( -9999.0 );
505         globals->get_scenery()->set_cur_radius( 0.0 );
506         globals->get_scenery()->set_cur_normal( hit_normal );
507     }
508     return hit;
509 }
510
511
512 void FGTileMgr::prep_ssg_nodes( SGLocation *location, float vis ) {
513
514     // traverse the potentially viewable tile list and update range
515     // selector and transform
516
517     Point3D center = location->get_tile_center();
518     float *up = location->get_world_up();
519
520     FGTileEntry *e;
521     tile_cache.reset_traversal();
522
523     while ( ! tile_cache.at_end() ) {
524         // cout << "processing a tile" << endl;
525         if ( (e = tile_cache.get_current()) ) {
526             e->prep_ssg_node( center, up, vis);
527         } else {
528             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
529         }
530         tile_cache.next();
531     }
532 }
533
534 bool FGTileMgr::set_tile_filter( bool f ) {
535     bool old = tile_filter;
536     tile_filter = f;
537     return old;
538 }
539
540 int FGTileMgr::tile_filter_cb( ssgEntity *, int )
541 {
542   return tile_filter ? 1 : 0;
543 }