]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Fix for vanishing-model problem: models are drawn in the same scene
[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) {
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 = current_bucket.get_width_m();
166     double tile_height = current_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     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) );
177
178     SGBucket b;
179
180     // schedule center tile first so it can be loaded first
181     b = sgBucketOffset( longitude, latitude, 0, 0 );
182     sched_tile( b );
183
184     int x, y;
185
186     // schedule next ring of 8 tiles
187     for ( x = -1; x <= 1; ++x ) {
188         for ( y = -1; y <= 1; ++y ) {
189             if ( x != 0 || y != 0 ) {
190                 b = sgBucketOffset( longitude, latitude, x, y );
191                 sched_tile( b );
192             }
193         }
194     }
195     
196     // schedule remaining tiles
197     for ( x = -xrange; x <= xrange; ++x ) {
198         for ( y = -yrange; y <= yrange; ++y ) {
199             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
200                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
201                 sched_tile( b );
202             }
203         }
204     }
205 }
206
207
208 void FGTileMgr::initialize_queue()
209 {
210     // First time through or we have teleported, initialize the
211     // system and load all relavant tiles
212
213     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
214     // cout << "tile cache size = " << tile_cache.get_size() << endl;
215
216     // wipe/initialize tile cache
217     // tile_cache.init();
218     previous_bucket.make_bad();
219
220     // build the local area list and schedule tiles for loading
221
222     // start with the center tile and work out in concentric
223     // "rings"
224
225     double visibility_meters = fgGetDouble("/environment/visibility-m");
226     schedule_needed(visibility_meters);
227
228     // do we really want to lose this? CLO
229 #if 0
230     // Now force a load of the center tile and inner ring so we
231     // have something to see in our first frame.
232     int i;
233     for ( i = 0; i < 9; ++i ) {
234         if ( load_queue.size() ) {
235             SG_LOG( SG_TERRAIN, SG_DEBUG, 
236                     "Load queue not empty, loading a tile" );
237
238             SGBucket pending = load_queue.front();
239             load_queue.pop_front();
240             load_tile( pending );
241         }
242     }
243 #endif
244 }
245
246
247 // given the current lon/lat (in degrees), fill in the array of local
248 // chunks.  If the chunk isn't already in the cache, then read it from
249 // disk.
250 int FGTileMgr::update( double lon, double lat, double visibility_meters ) {
251     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
252     //         << lon << " " << lat );
253
254     longitude = lon;
255     latitude = lat;
256     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
257     //      " lat " << lonlat[LAT] );
258
259     current_bucket.set_bucket( longitude, latitude );
260     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
261
262     if ( tile_cache.exists( current_bucket ) ) {
263         current_tile = tile_cache.get_tile( current_bucket );
264         scenery.set_next_center( current_tile->center );
265     } else {
266         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
267         scenery.set_next_center( Point3D(0.0) );
268     }
269
270     if ( state == Running ) {
271         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
272         if ( !(current_bucket == previous_bucket) ) {
273             // We've moved to a new bucket, we need to schedule any
274             // needed tiles for loading.
275             schedule_needed(visibility_meters);
276         }
277     } else if ( state == Start || state == Inited ) {
278         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
279         initialize_queue();
280         state = Running;
281
282         // load the next tile in the load queue (or authorize the next
283         // load in the case of the threaded tile pager)
284         loader.update();
285     }
286
287     // load the next model in the load queue.  Currently this must
288     // happen in the render thread because model loading can trigger
289     // texture loading which involves use of the opengl api.
290     if ( !model_queue.empty() ) {
291         // cout << "loading next model ..." << endl;
292         // load the next tile in the queue
293 #ifdef ENABLE_THREADS
294         FGDeferredModel* dm = model_queue.pop();
295 #else
296         FGDeferredModel* dm = model_queue.front();
297         model_queue.pop();
298 #endif
299         
300         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
301         ssgEntity *obj_model
302             = ssgLoad( (char *)(dm->get_model_path().c_str()) );
303         if ( obj_model != NULL ) {
304             dm->get_obj_trans()->addKid( obj_model );
305         }
306         dm->get_tile()->dec_pending_models();
307
308         delete dm;
309     }
310
311     // cout << "current elevation (ssg) == " << scenery.get_cur_elev() << endl;
312
313     previous_bucket = current_bucket;
314     last_longitude = longitude;
315     last_latitude  = latitude;
316
317     // activate loader thread one out of every 5 frames
318     if ( counter_hack == 0 ) {
319         // Notify the tile loader that it can load another tile
320
321         loader.update();
322
323     }
324     counter_hack = (counter_hack + 1) % 5;
325
326     if ( !attach_queue.empty() ) {
327 #ifdef ENABLE_THREADS
328         FGTileEntry* e = attach_queue.pop();
329 #else
330         FGTileEntry* e = attach_queue.front();
331         attach_queue.pop();
332 #endif
333         e->add_ssg_nodes( globals->get_terrain_branch(),
334                           globals->get_gnd_lights_branch(),
335                           globals->get_rwy_lights_branch() );
336         // cout << "Adding ssg nodes for "
337     }
338
339     sgdVec3 sc;
340     sgdSetVec3( sc,
341                 scenery.get_center()[0],
342                 scenery.get_center()[1],
343                 scenery.get_center()[2] );
344
345 #if 0
346     if ( scenery.center == Point3D(0.0) ) {
347         // initializing
348         cout << "initializing scenery current elevation ... " << endl;
349         sgdVec3 tmp_abs_view_pos;
350
351         Point3D geod_pos = Point3D( longitude * SGD_DEGREES_TO_RADIANS,
352                                     latitude * SGD_DEGREES_TO_RADIANS,
353                                     0.0);
354         Point3D tmp = sgGeodToCart( geod_pos );
355         scenery.center = tmp;
356         sgdSetVec3( tmp_abs_view_pos, tmp.x(), tmp.y(), tmp.z() );
357
358         // cout << "abs_view_pos = " << tmp_abs_view_pos << endl;
359         prep_ssg_nodes(visibility_meters);
360
361         double tmp_elev;
362         if ( fgCurrentElev(tmp_abs_view_pos, sc, &hit_list,
363                            &tmp_elev, &scenery.cur_radius, scenery.cur_normal) )
364         {
365             scenery.set_cur_elev( tmp_elev );
366         } else {
367             scenery.set_cur_elev( 0.0 );
368         }
369         // cout << "result = " << scenery.get_cur_elev() << endl;
370     } else {
371 #endif
372
373          /*
374        cout << "abs view pos = "
375               << globals->get_current_view()->get_abs_view_pos()[0] << ","
376               << globals->get_current_view()->get_abs_view_pos()[1] << ","
377               << globals->get_current_view()->get_abs_view_pos()[2]
378             << " view pos = "
379               << globals->get_current_view()->get_view_pos()[0] << ","
380               << globals->get_current_view()->get_view_pos()[1] << ","
381               << globals->get_current_view()->get_view_pos()[2]
382               << endl;
383          cout << "current_tile = " << current_tile << endl;
384          cout << "Scenery center = " << sc[0] << "," << sc[1] << "," << sc[2]
385               << endl;
386          */
387
388         // overridden with actual values if a terrain intersection is
389         // found
390         double hit_elev = -9999.0;
391         double hit_radius = 0.0;
392         sgdVec3 hit_normal = { 0.0, 0.0, 0.0 };
393
394         bool hit = false;
395         if ( fabs(sc[0]) > 1.0 || fabs(sc[1]) > 1.0 || fabs(sc[2]) > 1.0 ) {
396             // scenery center has been properly defined so any hit
397             // should be valid (and not just luck)
398             sgdSetVec3( sc,
399                         scenery.get_center()[0],
400                         scenery.get_center()[1],
401                         scenery.get_center()[2] );
402             hit = fgCurrentElev(globals->get_current_view()->get_absolute_view_pos(),
403                                 sc,
404                                 current_tile->get_terra_transform(),
405                                 &hit_list,
406                                 &hit_elev,
407                                 &hit_radius,
408                                 hit_normal);
409         }
410
411         if ( hit ) {
412             scenery.set_cur_elev( hit_elev );
413             scenery.set_cur_radius( hit_radius );
414             scenery.set_cur_normal( hit_normal );
415         } else {
416             scenery.set_cur_elev( -9999.0 );
417             scenery.set_cur_radius( 0.0 );
418             scenery.set_cur_normal( hit_normal );
419         }
420         // cout << "Current elevation = " << scenery.get_cur_elev() << endl;
421
422 #if 0
423     }
424 #endif
425
426     return 1;
427 }
428
429
430 void FGTileMgr::prep_ssg_nodes(float vis) {
431 //    float vis = 0.0;
432
433 //    vis = fgGetDouble("/environment/visibility-m");
434
435     // traverse the potentially viewable tile list and update range
436     // selector and transform
437
438     FGTileEntry *e;
439     tile_cache.reset_traversal();
440
441     sgVec3 up;
442     sgCopyVec3( up, globals->get_current_view()->get_world_up() );
443         
444     while ( ! tile_cache.at_end() ) {
445         // cout << "processing a tile" << endl;
446         if ( (e = tile_cache.get_current()) ) {
447             e->prep_ssg_node( scenery.get_center(), up, vis);
448         } else {
449             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
450         }
451         tile_cache.next();
452    }
453 }
454