]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Restructure the way tile freeing is handled. When a tile is removed from
[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 #ifdef HAVE_WINDOWS_H
29 #  include <windows.h>
30 #endif
31
32 #include <GL/glut.h>
33
34 #include <plib/ssg.h>
35
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
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Main/viewer.hxx>
46 #include <Objects/obj.hxx>
47
48 #include "newcache.hxx"
49 #include "scenery.hxx"
50 #include "tilemgr.hxx"
51
52 #define TEST_LAST_HIT_CACHE
53
54 // the tile manager
55 FGTileMgr global_tile_mgr;
56
57
58 #ifdef ENABLE_THREADS
59 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
60 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
61 #else
62 queue<FGTileEntry *> FGTileMgr::attach_queue;
63 queue<FGDeferredModel *> FGTileMgr::model_queue;
64 #endif // ENABLE_THREADS
65 queue<FGTileEntry *> FGTileMgr::delete_queue;
66
67
68 // Constructor
69 FGTileMgr::FGTileMgr():
70     state( Start ),
71     current_tile( NULL ),
72     vis( 16000 ),
73     max_cache_size(100),
74     counter_hack(0)
75 {
76 }
77
78
79 // Destructor
80 FGTileMgr::~FGTileMgr() {
81 }
82
83
84 // Initialize the Tile Manager subsystem
85 int FGTileMgr::init() {
86     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
87
88     tile_cache.init();
89
90 #if 0
91
92     // instead it's just a lot easier to let any pending work flush
93     // through, rather than trying to arrest the queue and nuke all
94     // the various work at all the various stages and get everything
95     // cleaned up properly.
96
97     while ( ! attach_queue.empty() ) {
98         attach_queue.pop();
99     }
100
101     while ( ! model_queue.empty() ) {
102 #ifdef ENABLE_THREADS
103         FGDeferredModel* dm = model_queue.pop();
104 #else
105         FGDeferredModel* dm = model_queue.front();
106         model_queue.pop();
107 #endif
108         delete dm;
109     }
110     loader.reinit();
111 #endif
112
113     hit_list.clear();
114
115     state = Inited;
116
117     previous_bucket.make_bad();
118     current_bucket.make_bad();
119
120     longitude = latitude = -1000.0;
121     last_longitude = last_latitude = -1000.0;
122         
123     return 1;
124 }
125
126
127 // schedule a tile for loading
128 void FGTileMgr::sched_tile( const SGBucket& b ) {
129     // see if tile already exists in the cache
130     FGTileEntry *t = tile_cache.get_tile( b );
131
132     if ( t == NULL ) {
133         // make space in the cache
134         while ( (int)tile_cache.get_size() > max_cache_size ) {
135             long index = tile_cache.get_oldest_tile();
136             if ( index >= 0 ) {
137                 FGTileEntry *old = tile_cache.get_tile( index );
138                 old->disconnect_ssg_nodes();
139                 delete_queue.push( old );
140                 tile_cache.clear_entry( index );
141             } else {
142                 // nothing to free ?!? forge ahead
143                 break;
144             }
145         }
146
147         // create a new entry
148         FGTileEntry *e = new FGTileEntry( b );
149
150         // insert the tile into the cache
151         if ( tile_cache.insert_tile( e ) ) {
152           // Schedule tile for loading
153           loader.add( e );
154         } else {
155           // insert failed (cache full with no available entries to
156           // delete.)  Try again later
157           delete e;
158         }
159     }
160 }
161
162
163 // schedule a needed buckets for loading
164 void FGTileMgr::schedule_needed( double vis, SGBucket curr_bucket) {
165     // sanity check (unfortunately needed!)
166     if ( longitude < -180.0 || longitude > 180.0 
167          || latitude < -90.0 || latitude > 90.0 )
168     {
169         SG_LOG( SG_TERRAIN, SG_ALERT,
170                 "Attempting to schedule tiles for bogus latitude and" );
171         SG_LOG( SG_TERRAIN, SG_ALERT,
172                 "longitude.  This is a FATAL error.  Exiting!" );
173         exit(-1);        
174     }
175
176    SG_LOG( SG_TERRAIN, SG_INFO,
177            "scheduling needed tiles for " << longitude << " " << latitude );
178
179 //   vis = fgGetDouble("/environment/visibility-m");
180
181     double tile_width = curr_bucket.get_width_m();
182     double tile_height = curr_bucket.get_height_m();
183     // cout << "tile width = " << tile_width << "  tile_height = "
184     //      << tile_height !<< endl;
185
186     xrange = (int)(vis / tile_width) + 1;
187     yrange = (int)(vis / tile_height) + 1;
188     if ( xrange < 1 ) { xrange = 1; }
189     if ( yrange < 1 ) { yrange = 1; }
190     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
191
192     // note * 2 at end doubles cache size (for fdm and viewer)
193     max_cache_size = (2*xrange + 2) * (2*yrange + 2) * 2;
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 );
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 );
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 );
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, "Updating Tile list for " << current_bucket );
231     // cout << "tile cache size = " << tile_cache.get_size() << endl;
232
233     // wipe/initialize tile cache
234     // tile_cache.init();
235     previous_bucket.make_bad();
236
237     // build the local area list and schedule tiles for loading
238
239     // start with the center tile and work out in concentric
240     // "rings"
241
242     double visibility_meters = fgGetDouble("/environment/visibility-m");
243     schedule_needed(visibility_meters, current_bucket);
244
245     // do we really want to lose this? CLO
246 #if 0
247     // Now force a load of the center tile and inner ring so we
248     // have something to see in our first frame.
249     int i;
250     for ( i = 0; i < 9; ++i ) {
251         if ( load_queue.size() ) {
252             SG_LOG( SG_TERRAIN, SG_DEBUG, 
253                     "Load queue not empty, loading a tile" );
254
255             SGBucket pending = load_queue.front();
256             load_queue.pop_front();
257             load_tile( pending );
258         }
259     }
260 #endif
261 }
262
263
264 // given the current lon/lat (in degrees), fill in the array of local
265 // chunks.  If the chunk isn't already in the cache, then read it from
266 // disk.
267 int FGTileMgr::update( double lon, double lat, double visibility_meters ) {
268         sgdVec3 abs_pos_vector;
269         sgdCopyVec3(abs_pos_vector , globals->get_current_view()->get_absolute_view_pos());
270         return update( lon, lat, visibility_meters, abs_pos_vector,
271                        current_bucket, previous_bucket,
272                        globals->get_scenery()->get_center() );
273 }
274
275
276 int FGTileMgr::update( double lon, double lat, double visibility_meters,
277                        sgdVec3 abs_pos_vector, SGBucket p_current,
278                        SGBucket p_previous, Point3D center ) {
279     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
280     //         << lon << " " << lat );
281
282     longitude = lon;
283     latitude = lat;
284     current_bucket = p_current;
285     previous_bucket = p_previous;
286
287     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
288     //      " lat " << lonlat[LAT] );
289
290     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
291
292     setCurrentTile( longitude, latitude);
293
294     // do tile load scheduling. 
295     // Note that we need keep track of both viewer buckets and fdm buckets.
296     if ( state == Running ) {
297        SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
298        if (!(current_bucket == previous_bucket )) {
299          // We've moved to a new bucket, we need to schedule any
300          // needed tiles for loading.
301          schedule_needed(visibility_meters, current_bucket);
302        }
303     } else if ( state == Start || state == Inited ) {
304         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
305         initialize_queue();
306         state = Running;
307
308         // load the next tile in the load queue (or authorize the next
309         // load in the case of the threaded tile pager)
310         loader.update();
311     }
312
313     
314     // load the next model in the load queue.  Currently this must
315     // happen in the render thread because model loading can trigger
316     // texture loading which involves use of the opengl api.
317     if ( !model_queue.empty() ) {
318         // cout << "loading next model ..." << endl;
319         // load the next tile in the queue
320 #ifdef ENABLE_THREADS
321         FGDeferredModel* dm = model_queue.pop();
322 #else
323         FGDeferredModel* dm = model_queue.front();
324         model_queue.pop();
325 #endif
326         
327         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
328         ssgEntity *obj_model
329             = ssgLoad( (char *)(dm->get_model_path().c_str()) );
330         if ( obj_model != NULL ) {
331             dm->get_obj_trans()->addKid( obj_model );
332         }
333         dm->get_tile()->dec_pending_models();
334
335         delete dm;
336     }
337     
338     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
339
340
341     // save bucket...
342     previous_bucket = current_bucket;
343
344     // activate loader thread one out of every 5 frames
345     if ( counter_hack == 0 ) {
346       // Notify the tile loader that it can load another tile
347       loader.update();
348     } else {
349       counter_hack = (counter_hack + 1) % 5;
350     }
351
352     if ( !attach_queue.empty() ) {
353 #ifdef ENABLE_THREADS
354         FGTileEntry* e = attach_queue.pop();
355 #else
356         FGTileEntry* e = attach_queue.front();
357         attach_queue.pop();
358 #endif
359         e->add_ssg_nodes( globals->get_scenery()->get_terrain_branch(),
360                           globals->get_scenery()->get_gnd_lights_branch(),
361                           globals->get_scenery()->get_rwy_lights_branch() );
362         // cout << "Adding ssg nodes for "
363     }
364
365     // cout << "delete queue = " << delete_queue.size() << endl;
366     if ( !delete_queue.empty() ) {
367         FGTileEntry* e = delete_queue.front();
368         if ( e->free_tile() ) {
369             delete_queue.pop();
370             delete e;
371         }
372     }
373
374     // no reason to update this if we haven't moved...
375     if ( longitude != last_longitude || latitude != last_latitude ) {
376       // update current elevation... 
377       if (updateCurrentElevAtPos(abs_pos_vector, center)) {
378         last_longitude = longitude;
379         last_latitude = latitude;
380       }
381     }
382
383 #if 0
384     }
385 #endif
386
387     return 1;
388 }
389
390 // timer event driven call to scheduler for the purpose of refreshing the tile timestamps
391 void FGTileMgr::refresh_view_timestamps() {
392     SG_LOG( SG_TERRAIN, SG_INFO,
393         "Refreshing timestamps for " << current_bucket.get_center_lon()
394         << " " << current_bucket.get_center_lat() );
395     schedule_needed(fgGetDouble("/environment/visibility-m"), current_bucket);
396 }
397
398
399 // check and set current tile and scenery center...
400 void FGTileMgr::setCurrentTile(double longitude, double latitude) {
401
402     // check tile cache entry...
403     current_bucket.set_bucket( longitude, latitude );
404     if ( tile_cache.exists( current_bucket ) ) {
405         current_tile = tile_cache.get_tile( current_bucket );
406         globals->get_scenery()->set_next_center( current_tile->center );
407     } else {
408         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
409         globals->get_scenery()->set_next_center( Point3D(0.0) );
410     }
411 }
412
413
414 int FGTileMgr::updateCurrentElevAtPos(sgdVec3 abs_pos_vector, Point3D center) {
415
416   sgdVec3 sc;
417
418   sgdSetVec3( sc,
419     center[0],
420     center[1],
421     center[2]);
422
423     // overridden with actual values if a terrain intersection is
424     // found
425     double hit_elev = -9999.0;
426     double hit_radius = 0.0;
427     sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
428     
429     bool hit = false;
430     if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
431        // scenery center has been properly defined so any hit
432        // should be valid (and not just luck)
433        hit = fgCurrentElev(abs_pos_vector,
434           sc,
435           current_tile->get_terra_transform(),
436           &hit_list,
437           &hit_elev,
438           &hit_radius,
439           hit_normal);
440     }
441
442     if ( hit ) {
443           globals->get_scenery()->set_cur_elev( hit_elev );
444           globals->get_scenery()->set_cur_radius( hit_radius );
445           globals->get_scenery()->set_cur_normal( hit_normal );
446     } else {
447           globals->get_scenery()->set_cur_elev( -9999.0 );
448           globals->get_scenery()->set_cur_radius( 0.0 );
449           globals->get_scenery()->set_cur_normal( hit_normal );
450     }
451     return hit;
452 }
453
454
455 void FGTileMgr::prep_ssg_nodes(float vis) {
456
457     // traverse the potentially viewable tile list and update range
458     // selector and transform
459
460     // just setup and call new function...
461
462     sgVec3 up;
463     sgCopyVec3( up, globals->get_current_view()->get_world_up() );
464
465     Point3D center;
466     center = globals->get_scenery()->get_center();
467     prep_ssg_nodes( vis, up, center );
468
469 }
470
471
472 void FGTileMgr::prep_ssg_nodes(float vis, sgVec3 up, Point3D center) {
473
474     // traverse the potentially viewable tile list and update range
475     // selector and transform
476
477     FGTileEntry *e;
478     tile_cache.reset_traversal();
479
480     while ( ! tile_cache.at_end() ) {
481         // cout << "processing a tile" << endl;
482         if ( (e = tile_cache.get_current()) ) {
483             e->prep_ssg_node( center, up, vis);
484         } else {
485             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
486         }
487         tile_cache.next();
488    }
489 }
490