]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
0f566485b4c11f3a4453792783c615e18dacafb6
[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  - http://www.flightgear.org/~curt
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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <algorithm>
29 #include <functional>
30
31 #include <osgViewer/Viewer>
32 #include <osgDB/Registry>
33
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
39 #include <simgear/scene/tsync/terrasync.hxx>
40
41 #include <Main/globals.hxx>
42 #include <Main/fg_props.hxx>
43 #include <Main/renderer.hxx>
44 #include <Main/viewer.hxx>
45 #include <Scripting/NasalSys.hxx>
46
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
50
51 using flightgear::SceneryPager;
52
53
54 FGTileMgr::FGTileMgr():
55     state( Start ),
56     last_state( Running ),
57     longitude(-1000.0),
58     latitude(-1000.0),
59     scheduled_visibility(100.0),
60     _terra_sync(NULL),
61     _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
62     _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
63     _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true))
64 {
65 }
66
67
68 FGTileMgr::~FGTileMgr()
69 {
70     // remove all nodes we might have left behind
71     osg::Group* group = globals->get_scenery()->get_terrain_branch();
72     group->removeChildren(0, group->getNumChildren());
73     // clear OSG cache
74     osgDB::Registry::instance()->clearObjectCache();
75 }
76
77
78 // Initialize the Tile Manager subsystem
79 void FGTileMgr::init() {
80     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
81
82     _options = new simgear::SGReaderWriterOptions;
83     _options->setMaterialLib(globals->get_matlib());
84     _options->setPropertyNode(globals->get_props());
85
86     osgDB::FilePathList &fp = _options->getDatabasePathList();
87     const string_list &sc = globals->get_fg_scenery();
88     fp.clear();
89     std::copy(sc.begin(), sc.end(), back_inserter(fp));
90     _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
91     if (!_disableNasalHooks->getBoolValue())
92         _options->setModelData(new FGNasalModelDataProxy);
93
94     reinit();
95 }
96
97 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
98 {
99     ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
100 }
101
102 void FGTileMgr::reinit()
103 {
104     // protect against multiple scenery reloads and properly reset flags,
105     // otherwise aircraft fall through the ground while reloading scenery
106     if (!fgGetBool("/sim/sceneryloaded",true))
107         return;
108     fgSetBool("/sim/sceneryloaded",false);
109     fgSetDouble("/sim/startup/splash-alpha", 1.0);
110
111     // remove all old scenery nodes from scenegraph and clear cache
112     osg::Group* group = globals->get_scenery()->get_terrain_branch();
113     group->removeChildren(0, group->getNumChildren());
114     tile_cache.init();
115     
116     // clear OSG cache, except on initial start-up
117     if (state != Start)
118     {
119         osgDB::Registry::instance()->clearObjectCache();
120     }
121     
122     state = Inited;
123     
124     previous_bucket.make_bad();
125     current_bucket.make_bad();
126     longitude = latitude = -1000.0;
127     scheduled_visibility = 100.0;
128
129     _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
130     if (_terra_sync)
131         _terra_sync->setTileRefreshCb(&refresh_tile, this);
132
133     // force an update now
134     update(0.0);
135 }
136
137 /* schedule a tile for loading, keep request for given amount of time.
138  * Returns true if tile is already loaded. */
139 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
140 {
141     // see if tile already exists in the cache
142     TileEntry *t = tile_cache.get_tile( b );
143     if (!t)
144     {
145         // create a new entry
146         t = new TileEntry( b );
147         // insert the tile into the cache, update will generate load request
148         if ( tile_cache.insert_tile( t ) )
149         {
150             // Attach to scene graph
151
152             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
153         } else
154         {
155             // insert failed (cache full with no available entries to
156             // delete.)  Try again later
157             delete t;
158             return false;
159         }
160
161         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
162     }
163
164     // update tile's properties
165     tile_cache.request_tile(t,priority,current_view,duration);
166
167     return t->is_loaded();
168 }
169
170 /* schedule needed buckets for the current view position for loading,
171  * keep request for given amount of time */
172 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
173 {
174     // sanity check (unfortunately needed!)
175     if ( longitude < -180.0 || longitude > 180.0 
176          || latitude < -90.0 || latitude > 90.0 )
177     {
178         SG_LOG( SG_TERRAIN, SG_ALERT,
179                 "Attempting to schedule tiles for bogus lon and lat  = ("
180                 << longitude << "," << latitude << ")" );
181         return;
182     }
183
184     SG_LOG( SG_TERRAIN, SG_INFO,
185             "scheduling needed tiles for " << longitude << " " << latitude );
186
187     double tile_width = curr_bucket.get_width_m();
188     double tile_height = curr_bucket.get_height_m();
189     // cout << "tile width = " << tile_width << "  tile_height = "
190     //      << tile_height << endl;
191
192     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
193     int xrange = (int)(tileRangeM / tile_width) + 1;
194     int yrange = (int)(tileRangeM / tile_height) + 1;
195     if ( xrange < 1 ) { xrange = 1; }
196     if ( yrange < 1 ) { yrange = 1; }
197
198     // make the cache twice as large to avoid losing terrain when switching
199     // between aircraft and tower views
200     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
201     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
202     // cout << "max cache size = " << tile_cache.get_max_cache_size()
203     //      << " current cache size = " << tile_cache.get_size() << endl;
204
205     // clear flags of all tiles belonging to the previous view set 
206     tile_cache.clear_current_view();
207
208     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
209     osg::FrameStamp* framestamp
210             = globals->get_renderer()->getViewer()->getFrameStamp();
211     tile_cache.set_current_time(framestamp->getReferenceTime());
212
213     SGBucket b;
214
215     int x, y;
216
217     /* schedule all tiles, use distance-based loading priority,
218      * so tiles are loaded in innermost-to-outermost sequence. */
219     for ( x = -xrange; x <= xrange; ++x )
220     {
221         for ( y = -yrange; y <= yrange; ++y )
222         {
223             SGBucket b = sgBucketOffset( longitude, latitude, x, y );
224             float priority = (-1.0) * (x*x+y*y);
225             sched_tile( b, priority, true, 0.0 );
226         }
227     }
228 }
229
230 /**
231  * Update the various queues maintained by the tilemagr (private
232  * internal function, do not call directly.)
233  */
234 void FGTileMgr::update_queues()
235 {
236     SceneryPager* pager = FGScenery::getPagerSingleton();
237     osg::FrameStamp* framestamp
238         = globals->get_renderer()->getViewer()->getFrameStamp();
239     double current_time = framestamp->getReferenceTime();
240     double vis = _visibilityMeters->getDoubleValue();
241     TileEntry *e;
242     int loading=0;
243     int sz=0;
244
245     tile_cache.set_current_time( current_time );
246     tile_cache.reset_traversal();
247
248     while ( ! tile_cache.at_end() )
249     {
250         e = tile_cache.get_current();
251         // cout << "processing a tile" << endl;
252         if ( e )
253         {
254             // Prepare the ssg nodes corresponding to each tile.
255             // Set the ssg transform and update it's range selector
256             // based on current visibilty
257             e->prep_ssg_node(vis);
258
259             if (( !e->is_loaded() )&&
260                 ((!e->is_expired(current_time))||
261                   e->is_current_view() ))
262             {
263                 // schedule tile for loading with osg pager
264                 pager->queueRequest(e->tileFileName,
265                                     e->getNode(),
266                                     e->get_priority(),
267                                     framestamp,
268                                     e->getDatabaseRequest(),
269                                     _options.get());
270                 loading++;
271             }
272         } else
273         {
274             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
275         }
276         tile_cache.next();
277         sz++;
278     }
279
280     int drop_count = sz - tile_cache.get_max_cache_size();
281     if (( drop_count > 0 )&&
282          ((loading==0)||(drop_count > 10)))
283     {
284         long drop_index = tile_cache.get_drop_tile();
285         while ( drop_index > -1 )
286         {
287             // schedule tile for deletion with osg pager
288             TileEntry* old = tile_cache.get_tile(drop_index);
289             tile_cache.clear_entry(drop_index);
290             
291             osg::ref_ptr<osg::Object> subgraph = old->getNode();
292             old->removeFromSceneGraph();
293             delete old;
294             // zeros out subgraph ref_ptr, so subgraph is owned by
295             // the pager and will be deleted in the pager thread.
296             pager->queueDeleteRequest(subgraph);
297             
298             if (--drop_count > 0)
299                 drop_index = tile_cache.get_drop_tile();
300             else
301                 drop_index = -1;
302         }
303     }
304 }
305
306 // given the current lon/lat (in degrees), fill in the array of local
307 // chunks.  If the chunk isn't already in the cache, then read it from
308 // disk.
309 void FGTileMgr::update(double)
310 {
311     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
312     double vis = _visibilityMeters->getDoubleValue();
313     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
314
315     update_queues();
316 }
317
318 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
319 // "schedule_scenery" instead
320 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
321 {
322     longitude = location.getLongitudeDeg();
323     latitude = location.getLatitudeDeg();
324
325     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
326     //         << longitude << " " << latatitude );
327
328     current_bucket.set_bucket( location );
329
330     // schedule more tiles when visibility increased considerably
331     // TODO Calculate tile size - instead of using fixed value (5000m)
332     if (range_m - scheduled_visibility > 5000.0)
333         previous_bucket.make_bad();
334
335     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
336     //         << current_bucket );
337     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
338
339     // do tile load scheduling.
340     // Note that we need keep track of both viewer buckets and fdm buckets.
341     if ( state == Running ) {
342         if (last_state != state)
343         {
344             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
345         }
346         if (current_bucket != previous_bucket) {
347             // We've moved to a new bucket, we need to schedule any
348             // needed tiles for loading.
349             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
350             scheduled_visibility = range_m;
351             schedule_needed(current_bucket, range_m);
352             if (_terra_sync)
353                 _terra_sync->schedulePosition(latitude,longitude);
354         }
355         // save bucket
356         previous_bucket = current_bucket;
357     } else if ( state == Start || state == Inited ) {
358         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
359         // do not update bucket yet (position not valid in initial loop)
360         state = Running;
361         previous_bucket.make_bad();
362     }
363     last_state = state;
364
365     return 1;
366 }
367
368 /** Schedules scenery for given position. Load request remains valid for given duration
369  * (duration=0.0 => nothing is loaded).
370  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
371  * Returns true when all tiles for the given position are already loaded, false otherwise.
372  */
373 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
374 {
375     const float priority = 0.0;
376     double current_longitude = position.getLongitudeDeg();
377     double current_latitude = position.getLatitudeDeg();
378     bool available = true;
379     
380     // sanity check (unfortunately needed!)
381     if (current_longitude < -180 || current_longitude > 180 ||
382         current_latitude < -90 || current_latitude > 90)
383         return false;
384   
385     SGBucket bucket(position);
386     available = sched_tile( bucket, priority, false, duration );
387   
388     if ((!available)&&(duration==0.0))
389         return false;
390
391     SGVec3d cartPos = SGVec3d::fromGeod(position);
392
393     // Traverse all tiles required to be there for the given visibility.
394     double tile_width = bucket.get_width_m();
395     double tile_height = bucket.get_height_m();
396     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
397     double max_dist = tile_r + range_m;
398     double max_dist2 = max_dist*max_dist;
399     
400     int xrange = (int)fabs(range_m / tile_width) + 1;
401     int yrange = (int)fabs(range_m / tile_height) + 1;
402
403     for ( int x = -xrange; x <= xrange; ++x )
404     {
405         for ( int y = -yrange; y <= yrange; ++y )
406         {
407             // We have already checked for the center tile.
408             if ( x != 0 || y != 0 )
409             {
410                 SGBucket b = sgBucketOffset( current_longitude,
411                                              current_latitude, x, y );
412                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
413                 // Do not ask if it is just the next tile but way out of range.
414                 if (distance2 <= max_dist2)
415                 {
416                     available &= sched_tile( b, priority, false, duration );
417                     if ((!available)&&(duration==0.0))
418                         return false;
419                 }
420             }
421         }
422     }
423
424     return available;
425 }
426
427 // Returns true if tiles around current view position have been loaded
428 bool FGTileMgr::isSceneryLoaded()
429 {
430     double range_m = 100.0;
431     if (scheduled_visibility < range_m)
432         range_m = scheduled_visibility;
433
434     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
435 }