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