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