]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Tile pager tweaks.
[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 <Objects/obj.hxx>
45
46 #ifndef FG_OLD_WEATHER
47 #  include <WeatherCM/FGLocalWeatherDatabase.h>
48 #else
49 #  include <Weather/weather.hxx>
50 #endif
51
52 #include "newcache.hxx"
53 #include "scenery.hxx"
54 #include "tilemgr.hxx"
55
56 #define TEST_LAST_HIT_CACHE
57
58 extern ssgRoot *scene;
59 extern ssgBranch *terrain;
60 extern ssgBranch *ground;
61
62 // the tile manager
63 FGTileMgr global_tile_mgr;
64
65
66 // a temporary hack until we get everything rewritten with sgdVec3
67 static inline Point3D operator + (const Point3D& a, const sgdVec3 b)
68 {
69     return Point3D(a.x()+b[0], a.y()+b[1], a.z()+b[2]);
70 }
71
72 #ifdef ENABLE_THREADS
73 SGLockedQueue<FGTileEntry *> FGTileMgr::attach_queue;
74 SGLockedQueue<FGDeferredModel *> FGTileMgr::model_queue;
75 #else
76 queue<FGTileEntry *> FGTileMgr::attach_queue;
77 queue<FGDeferredModel *> FGTileMgr::model_queue;
78 #endif // ENABLE_THREADS
79
80
81 // Constructor
82 FGTileMgr::FGTileMgr():
83     state( Start ),
84     vis( 16000 ),
85     counter_hack(0)
86 {
87 }
88
89
90 // Destructor
91 FGTileMgr::~FGTileMgr() {
92 }
93
94
95 // Initialize the Tile Manager subsystem
96 int FGTileMgr::init() {
97     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
98
99     tile_cache.init();
100     destroy_queue();
101
102     while ( ! attach_queue.empty() ) {
103         attach_queue.pop();
104     }
105
106     while ( ! model_queue.empty() ) {
107 #ifdef ENABLE_THREADS
108         FGDeferredModel* dm = model_queue.pop();
109 #else
110         FGDeferredModel* dm = model_queue.front();
111         model_queue.pop();
112 #endif
113         delete dm;
114     }
115     loader.reinit();
116
117 #if 0        
118     if ( state != Start ) {
119         SG_LOG( SG_TERRAIN, SG_INFO,
120                 "... Reinitializing." );
121         destroy_queue();
122     } else {
123         SG_LOG( SG_TERRAIN, SG_INFO,
124                 "... First time through." );
125         tile_cache.init();
126     }
127 #endif
128
129     hit_list.clear();
130
131     state = Inited;
132
133     previous_bucket.make_bad();
134     current_bucket.make_bad();
135
136     longitude = latitude = -1000.0;
137     last_longitude = last_latitude = -1000.0;
138         
139     return 1;
140 }
141
142
143 // schedule a tile for loading
144 void FGTileMgr::sched_tile( const SGBucket& b ) {
145     // see if tile already exists in the cache
146     FGTileEntry *t = tile_cache.get_tile( b );
147
148     if ( t == NULL ) {
149         // create a new entry
150         FGTileEntry *e = new FGTileEntry( b );
151
152         // insert the tile into the cache
153         tile_cache.insert_tile( e );
154
155         // Schedule tile for loading
156         loader.add( e );
157     }
158 }
159
160
161 static void CurrentNormalInLocalPlane(sgVec3 dst, sgVec3 src) {
162     sgVec3 tmp;
163     sgSetVec3(tmp, src[0], src[1], src[2] );
164     sgMat4 TMP;
165     sgTransposeNegateMat4 ( TMP, globals->get_current_view()->get_UP() ) ;
166     sgXformVec3(tmp, tmp, TMP);
167     sgSetVec3(dst, tmp[2], tmp[1], tmp[0] );
168 }
169
170
171 // Determine scenery altitude via ssg.  Normally this just happens
172 // when we render the scene, but we'd also like to be able to do this
173 // explicitely.  lat & lon are in radians.  view_pos in current world
174 // coordinate translated near (0,0,0) (in meters.)  Returns result in
175 // meters.
176 bool FGTileMgr::current_elev_ssg( sgdVec3 abs_view_pos, double *terrain_elev ) {
177     sgdVec3 view_pos;
178     sgdVec3 sc;
179     sgdSetVec3( sc, scenery.center.x(), scenery.center.y(), scenery.center.z());
180     sgdSubVec3( view_pos, abs_view_pos, sc );
181
182     sgdVec3 orig, dir;
183     sgdCopyVec3(orig, view_pos );
184     sgdCopyVec3(dir, abs_view_pos );
185
186     hit_list.Intersect( terrain, orig, dir );
187
188     int this_hit=0;
189     Point3D geoc;
190     double result = -9999;
191
192     int hitcount = hit_list.num_hits();
193     for ( int i = 0; i < hitcount; ++i ) {
194         geoc = sgCartToPolar3d( scenery.center + hit_list.get_point(i) );      
195         double lat_geod, alt, sea_level_r;
196         sgGeocToGeod(geoc.lat(), geoc.radius(), &lat_geod, 
197                      &alt, &sea_level_r);
198         if ( alt > result && alt < 10000 ) {
199             result = alt;
200             this_hit = i;
201         }
202     }
203
204     if ( result > -9000 ) {
205         *terrain_elev = result;
206         scenery.cur_radius = geoc.radius();
207         sgVec3 tmp;
208         sgSetVec3(tmp, hit_list.get_normal(this_hit));
209         // cout << "cur_normal: " << tmp[0] << " " << tmp[1] << " "
210         //      << tmp[2] << endl;
211         ssgState *IntersectedLeafState =
212             ((ssgLeaf*)hit_list.get_entity(this_hit))->getState();
213         CurrentNormalInLocalPlane(tmp, tmp);
214         sgdSetVec3( scenery.cur_normal, tmp );
215         // cout << "NED: " << tmp[0] << " " << tmp[1] << " " << tmp[2] << endl;
216         return true;
217     } else {
218         SG_LOG( SG_TERRAIN, SG_INFO, "no terrain intersection" );
219         *terrain_elev = 0.0;
220         float *up = globals->get_current_view()->get_world_up();
221         sgdSetVec3(scenery.cur_normal, up[0], up[1], up[2]);
222         return false;
223     }
224 }
225
226
227 // schedule a needed buckets for loading
228 void FGTileMgr::schedule_needed() {
229 #ifndef FG_OLD_WEATHER
230     if ( WeatherDatabase != NULL ) {
231         vis = WeatherDatabase->getWeatherVisibility();
232     } else {
233         vis = 16000;
234     }
235 #else
236     vis = current_weather.get_visibility();
237 #endif
238     // cout << "visibility = " << vis << endl;
239
240     double tile_width = current_bucket.get_width_m();
241     double tile_height = current_bucket.get_height_m();
242     // cout << "tile width = " << tile_width << "  tile_height = "
243     //      << tile_height !<< endl;
244
245     xrange = (int)(vis / tile_width) + 1;
246     yrange = (int)(vis / tile_height) + 1;
247     if ( xrange < 1 ) { xrange = 1; }
248     if ( yrange < 1 ) { yrange = 1; }
249     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
250
251     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) );
252
253     SGBucket b;
254
255     // schedule center tile first so it can be loaded first
256     b = sgBucketOffset( longitude, latitude, 0, 0 );
257     sched_tile( b );
258
259     int x, y;
260
261     // schedule next ring of 8 tiles
262     for ( x = -1; x <= 1; ++x ) {
263         for ( y = -1; y <= 1; ++y ) {
264             if ( x != 0 || y != 0 ) {
265                 b = sgBucketOffset( longitude, latitude, x, y );
266                 sched_tile( b );
267             }
268         }
269     }
270     
271     // schedule remaining tiles
272     for ( x = -xrange; x <= xrange; ++x ) {
273         for ( y = -yrange; y <= yrange; ++y ) {
274             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
275                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
276                 sched_tile( b );
277             }
278         }
279     }
280 }
281
282
283 void FGTileMgr::initialize_queue()
284 {
285     // First time through or we have teleported, initialize the
286     // system and load all relavant tiles
287
288     SG_LOG( SG_TERRAIN, SG_INFO, "Updating Tile list for " << current_bucket );
289     // cout << "tile cache size = " << tile_cache.get_size() << endl;
290
291     // wipe/initialize tile cache
292     // tile_cache.init();
293     previous_bucket.make_bad();
294
295     // build the local area list and schedule tiles for loading
296
297     // start with the center tile and work out in concentric
298     // "rings"
299
300     schedule_needed();
301
302     // do we really want to lose this? CLO
303 #if 0
304     // Now force a load of the center tile and inner ring so we
305     // have something to see in our first frame.
306     int i;
307     for ( i = 0; i < 9; ++i ) {
308         if ( load_queue.size() ) {
309             SG_LOG( SG_TERRAIN, SG_DEBUG, 
310                     "Load queue not empty, loading a tile" );
311
312             SGBucket pending = load_queue.front();
313             load_queue.pop_front();
314             load_tile( pending );
315         }
316     }
317 #endif
318 }
319
320
321 // forced emptying of the queue
322 // This is necessay to keep bookeeping straight for the
323 // tile_cache   -- which actually handles all the
324 // (de)allocations  
325 void FGTileMgr::destroy_queue() {
326     // load_queue.clear();
327 }
328
329
330 // given the current lon/lat (in degrees), fill in the array of local
331 // chunks.  If the chunk isn't already in the cache, then read it from
332 // disk.
333 int FGTileMgr::update( double lon, double lat ) {
334     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
335
336     // FGInterface *f = current_aircraft.fdm_state;
337
338     // lonlat for this update 
339     // longitude = f->get_Longitude() * SGD_RADIANS_TO_DEGREES;
340     // latitude = f->get_Latitude() * SGD_RADIANS_TO_DEGREES;
341     longitude = lon;
342     latitude = lat;
343     // SG_LOG( SG_TERRAIN, SG_DEBUG, "lon "<< lonlat[LON] <<
344     //      " lat " << lonlat[LAT] );
345
346     current_bucket.set_bucket( longitude, latitude );
347     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating Tile list for " << current_bucket );
348
349     if ( tile_cache.exists( current_bucket ) ) {
350         current_tile = tile_cache.get_tile( current_bucket );
351         scenery.next_center = current_tile->center;
352     } else {
353         SG_LOG( SG_TERRAIN, SG_WARN, "Tile not found (Ok if initializing)" );
354     }
355
356     if ( state == Running ) {
357         if ( !(current_bucket == previous_bucket) ) {
358             // We've moved to a new bucket, we need to schedule any
359             // needed tiles for loading.
360             schedule_needed();
361         }
362     } else if ( state == Start || state == Inited ) {
363         initialize_queue();
364         state = Running;
365     }
366
367     // load the next tile in the load queue (or authorize the next
368     // load in the case of the threaded tile pager)
369     loader.update();
370
371     // load the next model in the load queue.  Currently this must
372     // happen in the render thread because model loading can trigger
373     // texture loading which involves use of the opengl api.
374     if ( !model_queue.empty() ) {
375         cout << "loading next model ..." << endl;
376         // load the next tile in the queue
377 #ifdef ENABLE_THREADS
378         FGDeferredModel* dm = model_queue.pop();
379 #else
380         FGDeferredModel* dm = model_queue.front();
381         model_queue.pop();
382 #endif
383         
384         ssgTexturePath( (char *)(dm->get_texture_path().c_str()) );
385         ssgEntity *obj_model
386             = ssgLoad( (char *)(dm->get_model_path().c_str()) );
387         dm->get_obj_trans()->addKid( obj_model );
388         dm->get_tile()->dec_pending_models();
389
390         delete dm;
391     }
392
393     if ( scenery.center == Point3D(0.0) ) {
394         // initializing
395         cout << "initializing scenery current elevation  ... " << endl;
396         sgdVec3 tmp_abs_view_pos;
397         sgVec3 tmp_view_pos;
398
399         Point3D geod_pos = Point3D( longitude * SGD_DEGREES_TO_RADIANS,
400                                     latitude * SGD_DEGREES_TO_RADIANS,
401                                     0.0);
402         Point3D tmp = sgGeodToCart( geod_pos );
403         scenery.center = tmp;
404         sgdSetVec3( tmp_abs_view_pos, tmp.x(), tmp.y(), tmp.z() );
405
406         // cout << "abs_view_pos = " << tmp_abs_view_pos << endl;
407         prep_ssg_nodes();
408         sgSetVec3( tmp_view_pos, 0.0, 0.0, 0.0 );
409         double tmp_elev;
410         if ( current_elev_ssg(tmp_abs_view_pos, &tmp_elev) ) {
411             scenery.cur_elev = tmp_elev;
412         } else {
413             scenery.cur_elev = 0.0;
414         }
415         cout << "result = " << scenery.cur_elev << endl;
416     } else {
417         // cout << "abs view pos = " << current_view.abs_view_pos
418         //      << " view pos = " << current_view.view_pos << endl;
419         double tmp_elev;
420         if ( current_elev_ssg(globals->get_current_view()->get_abs_view_pos(),
421                               &tmp_elev) )
422         {
423             scenery.cur_elev = tmp_elev;
424         } else {
425             scenery.cur_elev = 0.0;
426         }  
427     }
428
429     // cout << "current elevation (ssg) == " << scenery.cur_elev << endl;
430
431     previous_bucket = current_bucket;
432     last_longitude = longitude;
433     last_latitude  = latitude;
434
435     // activate loader thread one out of every 5 frames
436     counter_hack = (counter_hack + 1) % 5;
437     if ( !counter_hack ) {
438         // Notify the tile loader that it can load another tile
439         // loader.update();
440
441         if ( !attach_queue.empty() ) {
442 #ifdef ENABLE_THREADS
443             FGTileEntry* e = attach_queue.pop();
444 #else
445             FGTileEntry* e = attach_queue.front();
446             attach_queue.pop();
447 #endif
448             e->add_ssg_nodes( terrain, ground );
449             // cout << "Adding ssg nodes for "
450         }
451     }
452
453     return 1;
454 }
455
456
457 void FGTileMgr::prep_ssg_nodes() {
458     float vis = 0.0;
459
460 #ifndef FG_OLD_WEATHER
461     if ( WeatherDatabase ) {
462         vis = WeatherDatabase->getWeatherVisibility();
463     } else {
464         vis = 16000;
465     }
466 #else
467     vis = current_weather.get_visibility();
468 #endif
469     // cout << "visibility = " << vis << endl;
470
471     // traverse the potentially viewable tile list and update range
472     // selector and transform
473
474     FGTileEntry *e;
475     tile_cache.reset_traversal();
476
477     while ( ! tile_cache.at_end() ) {
478         // cout << "processing a tile" << endl;
479         if ( (e = tile_cache.get_current()) ) {
480             e->prep_ssg_node( scenery.center, vis);
481         } else {
482             cout << "warning ... empty tile in cache" << endl;
483         }
484         tile_cache.next();
485    }
486 }