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