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