]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
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 #include <simgear/xgl/xgl.h>
34
35 #include <simgear/constants.h>
36 #include <simgear/debug/logstream.hxx>
37 #include <simgear/math/fg_geodesy.hxx>
38 #include <simgear/math/point3d.hxx>
39 #include <simgear/math/polar3d.hxx>
40 #include <simgear/math/vector.hxx>
41
42 // #include <Aircraft/aircraft.hxx>
43 #include <Main/options.hxx>
44 #include <Main/views.hxx>
45 #include <Objects/obj.hxx>
46
47 #ifndef FG_OLD_WEATHER
48 #  include <WeatherCM/FGLocalWeatherDatabase.h>
49 #else
50 #  include <Weather/weather.hxx>
51 #endif
52
53 #include "scenery.hxx"
54 #include "tilecache.hxx"
55 #include "tilemgr.hxx"
56
57 #define TEST_LAST_HIT_CACHE
58
59 extern ssgRoot *scene;
60 extern ssgBranch *terrain;
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
73 // Constructor
74 FGTileMgr::FGTileMgr ( void ):
75     state( Start )
76 {
77 }
78
79
80 // Destructor
81 FGTileMgr::~FGTileMgr ( void ) {
82 }
83
84
85 // Initialize the Tile Manager subsystem
86 int FGTileMgr::init( void ) {
87     FG_LOG( FG_TERRAIN, FG_INFO, "Initializing Tile Manager subsystem." );
88
89     if ( state != Start ) {
90         FG_LOG( FG_TERRAIN, FG_INFO,
91                 "... Reinitializing." );
92         destroy_queue();
93     } else {
94         FG_LOG( FG_TERRAIN, FG_INFO,
95                 "... First time through." );
96     }
97
98     global_tile_cache.init();
99     hit_list.clear();
100
101     state = Inited;
102
103     tile_diameter = current_options.get_tile_diameter();
104     FG_LOG( FG_TERRAIN, FG_INFO, "Tile Diameter = " << tile_diameter);
105     
106     previous_bucket.make_bad();
107     current_bucket.make_bad();
108
109     scroll_direction = SCROLL_INIT;
110     tile_index = -9999;
111
112     longitude = latitude = -1000.0;
113     last_longitude = last_latitude = -1000.0;
114         
115     return 1;
116 }
117
118
119 // schedule a tile for loading
120 int FGTileMgr::sched_tile( const FGBucket& b ) {
121     // see if tile already exists in the cache
122     int cache_index = global_tile_cache.exists( b );
123
124     if ( cache_index >= 0 ) {
125         // tile exists in cache, reenable it.
126         // cout << "REENABLING DISABLED TILE" << endl;
127         FGTileEntry *t = global_tile_cache.get_tile( cache_index );
128         t->select_ptr->select( 1 );
129         t->mark_loaded();
130     } else {
131         // find the next available cache entry and mark it as
132         // scheduled
133         cache_index = global_tile_cache.next_avail();
134         FGTileEntry *t = global_tile_cache.get_tile( cache_index );
135         t->mark_scheduled_for_use();
136
137         // register a load request
138         FGLoadRec request;
139         request.b = b;
140         request.cache_index = cache_index;
141         load_queue.push_back( request );
142     }
143
144     return cache_index;
145 }
146
147
148 // load a tile
149 void FGTileMgr::load_tile( const FGBucket& b, int cache_index) {
150
151     FG_LOG( FG_TERRAIN, FG_DEBUG, "Loading tile " << b );
152     global_tile_cache.fill_in(cache_index, b);
153     FG_LOG( FG_TERRAIN, FG_DEBUG, "Loaded for cache index: " << cache_index );
154 }
155
156
157 // Determine scenery altitude via ssg.  Normally this just happens
158 // when we render the scene, but we'd also like to be able to do this
159 // explicitely.  lat & lon are in radians.  view_pos in current world
160 // coordinate translated near (0,0,0) (in meters.)  Returns result in
161 // meters.
162
163 bool
164 FGTileMgr::current_elev_ssg( const Point3D& abs_view_pos, 
165                              const Point3D& view_pos )
166 {
167     sgdVec3 orig, dir;
168
169     sgdSetVec3(orig, view_pos.x(), view_pos.y(), view_pos.z() );
170     sgdSetVec3(dir, abs_view_pos.x(), abs_view_pos.y(), abs_view_pos.z() );
171
172     hit_list.Intersect( terrain, orig, dir );
173
174     int this_hit=0;
175     Point3D geoc;
176     double result = -9999;
177
178     int hitcount = hit_list.num_hits();
179     for ( int i = 0; i < hitcount; ++i ) {
180         geoc = fgCartToPolar3d( scenery.center + hit_list.get_point(i) );      
181         double lat_geod, alt, sea_level_r;
182         fgGeocToGeod(geoc.lat(), geoc.radius(), &lat_geod, 
183                      &alt, &sea_level_r);
184         if ( alt > result && alt < 10000 ) {
185             result = alt;
186             this_hit = i;
187         }
188     }
189
190     if ( result > -9000 ) {
191         scenery.cur_elev = result;
192         scenery.cur_radius = geoc.radius();
193         sgVec3 tmp;
194         sgSetVec3(tmp, hit_list.get_normal(this_hit));
195         ssgState *IntersectedLeafState =
196             ((ssgLeaf*)hit_list.get_entity(this_hit))->getState();
197         current_view.CurrentNormalInLocalPlane(tmp, tmp);
198         sgdSetVec3( scenery.cur_normal, tmp );
199         // cout << "NED: " << tmp[0] << " " << tmp[1] << " " << tmp[2] << endl;
200         return true;
201     } else {
202         FG_LOG( FG_TERRAIN, FG_INFO, "no terrain intersection" );
203         scenery.cur_elev = 0.0;
204         float *up = current_view.local_up;
205         sgdSetVec3(scenery.cur_normal, up[0], up[1], up[2]);
206         return false;
207     }
208 }
209
210
211 FGBucket FGTileMgr::BucketOffset( int dx, int dy )
212 {
213     double clat, clon, span;
214     if( scroll_direction == SCROLL_INIT ) {
215         // use current latitude and longitude
216         // walk dy units in the lat direction
217         clat = current_bucket.get_center_lat() + dy * FG_BUCKET_SPAN;
218
219         // find the lon span for the new latitude
220         span = bucket_span( clat );
221         
222         // walk dx units in the lon direction
223         clon = longitude + dx * span;
224     } else      {
225         // use previous latitude and longitude
226         // walk dy units in the lat direction
227         clat = previous_bucket.get_center_lat() + dy * FG_BUCKET_SPAN;
228
229         // find the lon span for the new latitude
230         span = bucket_span( clat );
231
232         // walk dx units in the lon direction
233         clon = last_longitude + dx * span;
234     }    
235         
236     while ( clon < -180.0 ) clon += 360.0;
237     while ( clon >= 180.0 ) clon -= 360.0;
238     pending.set_bucket( clon, clat );
239
240     FG_LOG( FG_TERRAIN, FG_DEBUG, "    fgBucketOffset " << pending );
241     return pending;
242 }
243
244
245 // schedule a tile row(column) for loading
246 void FGTileMgr::scroll( void )
247 {
248     FG_LOG( FG_TERRAIN, FG_DEBUG, "schedule_row: Scrolling" );
249
250     int i, dw, dh;
251         
252     switch( scroll_direction ) {
253     case SCROLL_NORTH:
254         FG_LOG( FG_TERRAIN, FG_DEBUG, 
255                 "  (North) Loading " << tile_diameter << " tiles" );
256         dw = tile_diameter / 2;
257         dh = dw + 1;
258         for ( i = 0; i < tile_diameter; i++ ) {
259             sched_tile( BucketOffset( i - dw, dh ) );
260         }
261         break;
262     case SCROLL_EAST:
263         FG_LOG( FG_TERRAIN, FG_DEBUG, 
264                 "  (East) Loading " << tile_diameter << " tiles" );
265         dh = tile_diameter / 2;
266         dw = dh + 1;
267         for ( i = 0; i < tile_diameter; i++ ) {
268             sched_tile( BucketOffset( dw, i - dh ) );
269         }
270         break;
271     case SCROLL_SOUTH:
272         FG_LOG( FG_TERRAIN, FG_DEBUG, 
273                 "  (South) Loading " << tile_diameter << " tiles" );
274         dw = tile_diameter / 2;
275         dh = -dw - 1;
276         for ( i = 0; i < tile_diameter; i++ ) {
277             sched_tile( BucketOffset( i - dw, dh ) );
278         }
279         break;
280     case SCROLL_WEST:
281         FG_LOG( FG_TERRAIN, FG_DEBUG, 
282                 "  (West) Loading " << tile_diameter << " tiles" );
283         dh = tile_diameter / 2;
284         dw = -dh - 1;
285         for ( i = 0; i < tile_diameter; i++ ) {
286             sched_tile( BucketOffset( dw, i - dh ) );
287         }
288         break;
289     default:
290         FG_LOG( FG_TERRAIN, FG_WARN, "UNKNOWN SCROLL DIRECTION in schedule_row" );
291         ;
292     }
293     FG_LOG( FG_TERRAIN, FG_DEBUG, "\tschedule_row returns" );
294 }
295
296
297 void FGTileMgr::initialize_queue()
298 {
299     // First time through or we have teleported, initialize the
300     // system and load all relavant tiles
301
302     FG_LOG( FG_TERRAIN, FG_INFO, "Updating Tile list for " << current_bucket );
303     FG_LOG( FG_TERRAIN, FG_INFO, "  Updating Tile list for " << current_bucket );
304     FG_LOG( FG_TERRAIN, FG_INFO, "  Loading " 
305             << tile_diameter * tile_diameter << " tiles" );
306
307     int i;
308     scroll_direction = SCROLL_INIT;
309
310     // wipe/initialize tile cache
311     global_tile_cache.init();
312     previous_bucket.make_bad();
313
314     // build the local area list and schedule tiles for loading
315
316     // start with the center tile and work out in concentric
317     // "rings"
318
319     sched_tile( current_bucket );
320
321     for ( i = 3; i <= tile_diameter; i = i + 2 ) {
322         int j;
323         int span = i / 2;
324
325         // bottom row
326         for ( j = -span; j <= span; ++j ) {
327             sched_tile( BucketOffset( j, -span ) );
328         }
329
330         // top row
331         for ( j = -span; j <= span; ++j ) {
332             sched_tile( BucketOffset( j, span ) );
333         }
334
335         // middle rows
336         for ( j = -span + 1; j <= span - 1; ++j ) {
337             sched_tile( BucketOffset( -span, j ) );
338             sched_tile( BucketOffset( span, j ) );
339         }
340
341     }
342
343     // Now force a load of the center tile and inner ring so we
344     // have something to see in our first frame.
345     for ( i = 0; i < 9; ++i ) {
346         if ( load_queue.size() ) {
347             FG_LOG( FG_TERRAIN, FG_DEBUG, 
348                     "Load queue not empty, loading a tile" );
349
350             FGLoadRec pending = load_queue.front();
351             load_queue.pop_front();
352             load_tile( pending.b, pending.cache_index );
353         }
354     }
355 }
356
357
358 // forced emptying of the queue
359 // This is necessay to keep bookeeping straight for the
360 // tile_cache   -- which actually handles all the
361 // (de)allocations  
362 void FGTileMgr::destroy_queue() {
363     while( load_queue.size() ) {
364         FG_LOG( FG_TERRAIN, FG_INFO, 
365                 "Load queue not empty, popping a tile" );
366         FGLoadRec pending = load_queue.front();
367         load_queue.pop_front();
368         FGTileEntry *t = global_tile_cache.get_tile( pending.cache_index );
369         // just t->mark_unused() should be enough
370         // but a little paranoia doesn't hurt us here
371         if(t->is_scheduled_for_use())
372             t->mark_unused();
373         else
374             load_tile( pending.b, pending.cache_index );
375     }
376 }
377
378
379 // given the current lon/lat (in degrees), fill in the array of local
380 // chunks.  If the chunk isn't already in the cache, then read it from
381 // disk.
382 int FGTileMgr::update( double lon, double lat ) {
383     // FG_LOG( FG_TERRAIN, FG_DEBUG, "FGTileMgr::update()" );
384
385     // FGInterface *f = current_aircraft.fdm_state;
386
387     // lonlat for this update 
388     // longitude = f->get_Longitude() * RAD_TO_DEG;
389     // latitude = f->get_Latitude() * RAD_TO_DEG;
390     longitude = lon;
391     latitude = lat;
392     // FG_LOG( FG_TERRAIN, FG_DEBUG, "lon "<< lonlat[LON] <<
393     //      " lat " << lonlat[LAT] );
394
395     current_bucket.set_bucket( longitude, latitude );
396     // FG_LOG( FG_TERRAIN, FG_DEBUG, "Updating Tile list for " << current_bucket );
397
398     tile_index = global_tile_cache.exists(current_bucket);
399     // FG_LOG( FG_TERRAIN, FG_DEBUG, "tile index " << tile_index );
400
401     if ( tile_index >= 0 ) {
402         current_tile = global_tile_cache.get_tile(tile_index);
403         scenery.next_center = current_tile->center;
404     } else {
405         FG_LOG( FG_TERRAIN, FG_WARN, "Tile not found (Ok if initializing)" );
406     }
407
408     if ( state == Running ) {
409         if( current_bucket == previous_bucket) {
410             FG_LOG( FG_TERRAIN, FG_DEBUG, "Same bucket as last time" );
411             scroll_direction = SCROLL_NONE;
412         } else {
413             // We've moved to a new bucket, we need to scroll our
414             // structures, and load in the new tiles
415             // CURRENTLY THIS ASSUMES WE CAN ONLY MOVE TO ADJACENT TILES.
416             // AT ULTRA HIGH SPEEDS THIS ASSUMPTION MAY NOT BE VALID IF
417             // THE AIRCRAFT CAN SKIP A TILE IN A SINGLE ITERATION.
418
419             if ( (current_bucket.get_lon() > previous_bucket.get_lon()) ||
420                  ( (current_bucket.get_lon() == previous_bucket.get_lon()) && 
421                    (current_bucket.get_x() > previous_bucket.get_x()) ) )
422                 {
423                     scroll_direction = SCROLL_EAST;
424                 }
425             else if ( (current_bucket.get_lon() < previous_bucket.get_lon()) ||
426                       ( (current_bucket.get_lon() == previous_bucket.get_lon()) && 
427                         (current_bucket.get_x() < previous_bucket.get_x()) ) )
428                 {   
429                     scroll_direction = SCROLL_WEST;
430                 }   
431
432             if ( (current_bucket.get_lat() > previous_bucket.get_lat()) ||
433                  ( (current_bucket.get_lat() == previous_bucket.get_lat()) && 
434                    (current_bucket.get_y() > previous_bucket.get_y()) ) )
435                 {   
436                     scroll_direction = SCROLL_NORTH;
437                 }
438             else if ( (current_bucket.get_lat() < previous_bucket.get_lat()) ||
439                       ( (current_bucket.get_lat() == previous_bucket.get_lat()) && 
440                         (current_bucket.get_y() < previous_bucket.get_y()) ) )
441                 {
442                     scroll_direction = SCROLL_SOUTH;
443                 }
444
445             scroll();
446         }
447
448     } else if ( state == Start || state == Inited ) {
449         initialize_queue();
450         state = Running;
451     }
452
453     if ( load_queue.size() ) {
454         FG_LOG( FG_TERRAIN, FG_DEBUG, "Load queue not empty, loading a tile" );
455
456         FGLoadRec pending = load_queue.front();
457         load_queue.pop_front();
458         load_tile( pending.b, pending.cache_index );
459     }
460
461     if ( scenery.center == Point3D(0.0) ) {
462         // initializing
463         // cout << "initializing ... " << endl;
464         Point3D geod_pos = Point3D( longitude * DEG_TO_RAD,
465                                     latitude * DEG_TO_RAD,
466                                     0.0);
467         Point3D tmp_abs_view_pos = fgGeodToCart( geod_pos );
468         scenery.center = tmp_abs_view_pos;
469         // cout << "abs_view_pos = " << tmp_abs_view_pos << endl;
470         prep_ssg_nodes();
471         current_elev_ssg( tmp_abs_view_pos,
472                           Point3D( 0.0 ) );
473     } else {
474         // cout << "abs view pos = " << current_view.abs_view_pos
475         //      << " view pos = " << current_view.view_pos << endl;
476         current_elev_ssg( current_view.abs_view_pos,
477                           current_view.view_pos );
478     }
479
480     // cout << "current elevation (ssg) == " << scenery.cur_elev << endl;
481
482     previous_bucket = current_bucket;
483     last_longitude = longitude;
484     last_latitude  = latitude;
485
486     return 1;
487 }
488
489 // Prepare the ssg nodes ... for each tile, set it's proper
490 // transform and update it's range selector based on current
491 // visibilty
492 void FGTileMgr::prep_ssg_node( int idx ) {
493 }
494
495 void FGTileMgr::prep_ssg_nodes( void ) {
496     FGTileEntry *t;
497     float ranges[2];
498     ranges[0] = 0.0f;
499     double vis = 0.0;
500
501 #ifndef FG_OLD_WEATHER
502     if ( WeatherDatabase != NULL ) {
503         vis = WeatherDatabase->getWeatherVisibility();
504     } else {
505         vis = 16000;
506     }
507 #else
508     vis = current_weather.get_visibility();
509 #endif
510     // cout << "visibility = " << vis << endl;
511
512     // traverse the potentially viewable tile list and update range
513     // selector and transform
514     for ( int i = 0; i < (int)global_tile_cache.get_size(); i++ ) {
515         t = global_tile_cache.get_tile( i );
516
517         if ( t->is_loaded() ) {
518             // set range selector (LOD trick) to be distance to center
519             // of tile + bounding radius
520
521             ranges[1] = vis + t->bounding_radius;
522             t->range_ptr->setRanges( ranges, 2 );
523
524             // calculate tile offset
525             t->SetOffset( scenery.center );
526
527             // calculate ssg transform
528             sgCoord sgcoord;
529             sgSetCoord( &sgcoord,
530                         t->offset.x(), t->offset.y(), t->offset.z(),
531                         0.0, 0.0, 0.0 );
532             t->transform_ptr->setTransform( &sgcoord );
533         }
534     }
535 }