1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
3 // Written by Curtis Olson, started January 1998.
5 // Copyright (C) 1997 Curtis L. Olson - http://www.flightgear.org/~curt
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.
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.
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.
31 #include <osgViewer/Viewer>
32 #include <osgDB/Registry>
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 #include <simgear/scene/material/matlib.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Viewer/renderer.hxx>
46 #include <Viewer/splash.hxx>
47 #include <Scripting/NasalSys.hxx>
48 #include <Scripting/NasalModelData.hxx>
50 #include "scenery.hxx"
51 #include "SceneryPager.hxx"
52 #include "tilemgr.hxx"
54 using flightgear::SceneryPager;
57 FGTileMgr::FGTileMgr():
59 last_state( Running ),
62 scheduled_visibility(100.0),
64 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
65 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
66 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
67 _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
68 _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
69 _pager(FGScenery::getPagerSingleton())
74 FGTileMgr::~FGTileMgr()
76 // remove all nodes we might have left behind
77 osg::Group* group = globals->get_scenery()->get_terrain_branch();
78 group->removeChildren(0, group->getNumChildren());
80 osgDB::Registry::instance()->clearObjectCache();
84 // Initialize the Tile Manager subsystem
85 void FGTileMgr::init() {
86 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
88 _options = new simgear::SGReaderWriterOptions;
91 _options->setPropertyNode(globals->get_props());
93 osgDB::FilePathList &fp = _options->getDatabasePathList();
94 const string_list &sc = globals->get_fg_scenery();
96 std::copy(sc.begin(), sc.end(), back_inserter(fp));
97 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
99 if (globals->get_subsystem("terrasync")) {
100 _options->setPluginStringData("SimGear::TERRASYNC_ROOT", fgGetString("/sim/terrasync/scenery-dir"));
103 if (!_disableNasalHooks->getBoolValue())
104 _options->setModelData(new FGNasalModelDataProxy);
109 void FGTileMgr::reinit()
111 _terra_sync = static_cast<simgear::SGTerraSync*> (globals->get_subsystem("terrasync"));
113 // protect against multiple scenery reloads and properly reset flags,
114 // otherwise aircraft fall through the ground while reloading scenery
115 if (!fgGetBool("/sim/sceneryloaded",true))
117 fgSetBool("/sim/sceneryloaded",false);
118 fgSetDouble("/sim/startup/splash-alpha", 1.0);
120 materialLibChanged();
122 // remove all old scenery nodes from scenegraph and clear cache
123 osg::Group* group = globals->get_scenery()->get_terrain_branch();
124 group->removeChildren(0, group->getNumChildren());
127 // clear OSG cache, except on initial start-up
130 osgDB::Registry::instance()->clearObjectCache();
135 previous_bucket.make_bad();
136 current_bucket.make_bad();
137 longitude = latitude = -1000.0;
138 scheduled_visibility = 100.0;
140 // force an update now
144 void FGTileMgr::materialLibChanged()
146 _options->setMaterialLib(globals->get_matlib());
147 _options->getMaterialLib()->refreshActiveMaterials();
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)
154 // see if tile already exists in the cache
155 TileEntry *t = tile_cache.get_tile( b );
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 ) )
163 // Attach to scene graph
165 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
168 // insert failed (cache full with no available entries to
169 // delete.) Try again later
174 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
177 // update tile's properties
178 tile_cache.request_tile(t,priority,current_view,duration);
180 return t->is_loaded();
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)
187 // sanity check (unfortunately needed!)
188 if ( longitude < -180.0 || longitude > 180.0
189 || latitude < -90.0 || latitude > 90.0 )
191 SG_LOG( SG_TERRAIN, SG_ALERT,
192 "Attempting to schedule tiles for bogus lon and lat = ("
193 << longitude << "," << latitude << ")" );
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());
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;
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; }
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;
219 // clear flags of all tiles belonging to the previous view set
220 tile_cache.clear_current_view();
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());
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 )
235 for ( y = -yrange; y <= yrange; ++y )
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 );
242 _terra_sync->scheduleTile(b);
249 * Update the various queues maintained by the tilemagr (private
250 * internal function, do not call directly.)
252 void FGTileMgr::update_queues(bool& isDownloadingScenery)
254 osg::FrameStamp* framestamp
255 = globals->get_renderer()->getViewer()->getFrameStamp();
256 double current_time = framestamp->getReferenceTime();
257 double vis = _visibilityMeters->getDoubleValue();
261 bool didRefreshMaterialCache = false;
263 tile_cache.set_current_time( current_time );
264 tile_cache.reset_traversal();
266 while ( ! tile_cache.at_end() )
268 e = tile_cache.get_current();
271 // Prepare the ssg nodes corresponding to each tile.
272 // Set the ssg transform and update it's range selector
273 // based on current visibilty
274 e->prep_ssg_node(vis);
276 if (!e->is_loaded()) {
277 if (!didRefreshMaterialCache) {
278 didRefreshMaterialCache = true;
279 globals->get_matlib()->refreshActiveMaterials();
282 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
283 bool downloading = isTileDirSyncing(e->tileFileName);
284 isDownloadingScenery |= downloading;
285 if ( !downloading && nonExpiredOrCurrent) {
286 // schedule tile for loading with osg pager
287 _pager->queueRequest(e->tileFileName,
291 e->getDatabaseRequest(),
295 } // of tile not loaded case
297 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
303 int drop_count = sz - tile_cache.get_max_cache_size();
304 if (( drop_count > 0 )&&
305 ((loading==0)||(drop_count > 10)))
307 long drop_index = tile_cache.get_drop_tile();
308 while ( drop_index > -1 )
310 // schedule tile for deletion with osg pager
311 TileEntry* old = tile_cache.get_tile(drop_index);
312 tile_cache.clear_entry(drop_index);
314 osg::ref_ptr<osg::Object> subgraph = old->getNode();
315 old->removeFromSceneGraph();
317 // zeros out subgraph ref_ptr, so subgraph is owned by
318 // the pager and will be deleted in the pager thread.
319 _pager->queueDeleteRequest(subgraph);
321 if (--drop_count > 0)
322 drop_index = tile_cache.get_drop_tile();
329 // given the current lon/lat (in degrees), fill in the array of local
330 // chunks. If the chunk isn't already in the cache, then read it from
332 void FGTileMgr::update(double)
334 double vis = _visibilityMeters->getDoubleValue();
335 schedule_tiles_at(globals->get_view_position(), vis);
337 bool waitingOnTerrasync = false;
338 update_queues(waitingOnTerrasync);
340 // scenery loading check, triggers after each sim (tile manager) reinit
341 if (!_scenery_loaded->getBoolValue())
343 bool fdmInited = fgGetBool("sim/fdm-initialized");
344 bool positionFinalized = fgGetBool("sim/position-finalized");
345 bool sceneryOverride = _scenery_override->getBoolValue();
348 // we are done if final position is set and the scenery & FDM are done.
349 // scenery-override can ignore the last two, but not position finalization.
350 if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
352 _scenery_loaded->setBoolValue(true);
353 fgSplashProgress("");
357 if (!positionFinalized) {
358 fgSplashProgress("finalize-position");
359 } else if (waitingOnTerrasync) {
360 fgSplashProgress("downloading-scenery");
362 fgSplashProgress("loading-scenery");
365 // be nice to loader threads while waiting for initial scenery, reduce to 20fps
366 SGTimeStamp::sleepForMSec(50);
371 // schedule tiles for the viewer bucket
372 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
373 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
375 longitude = location.getLongitudeDeg();
376 latitude = location.getLatitudeDeg();
378 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
379 // << longitude << " " << latitude );
381 current_bucket.set_bucket( location );
383 // schedule more tiles when visibility increased considerably
384 // TODO Calculate tile size - instead of using fixed value (5000m)
385 if (range_m - scheduled_visibility > 5000.0)
386 previous_bucket.make_bad();
388 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
389 // << current_bucket );
390 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
392 // do tile load scheduling.
393 // Note that we need keep track of both viewer buckets and fdm buckets.
394 if ( state == Running ) {
395 if (last_state != state)
397 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
399 if (current_bucket != previous_bucket) {
400 // We've moved to a new bucket, we need to schedule any
401 // needed tiles for loading.
402 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
403 scheduled_visibility = range_m;
404 schedule_needed(current_bucket, range_m);
408 previous_bucket = current_bucket;
409 } else if ( state == Start || state == Inited ) {
410 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
411 // do not update bucket yet (position not valid in initial loop)
413 previous_bucket.make_bad();
418 /** Schedules scenery for given position. Load request remains valid for given duration
419 * (duration=0.0 => nothing is loaded).
420 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
421 * Returns true when all tiles for the given position are already loaded, false otherwise.
423 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
425 const float priority = 0.0;
426 double current_longitude = position.getLongitudeDeg();
427 double current_latitude = position.getLatitudeDeg();
428 bool available = true;
430 // sanity check (unfortunately needed!)
431 if (current_longitude < -180 || current_longitude > 180 ||
432 current_latitude < -90 || current_latitude > 90)
435 SGBucket bucket(position);
436 available = sched_tile( bucket, priority, false, duration );
438 if ((!available)&&(duration==0.0))
441 SGVec3d cartPos = SGVec3d::fromGeod(position);
443 // Traverse all tiles required to be there for the given visibility.
444 double tile_width = bucket.get_width_m();
445 double tile_height = bucket.get_height_m();
446 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
447 double max_dist = tile_r + range_m;
448 double max_dist2 = max_dist*max_dist;
450 int xrange = (int)fabs(range_m / tile_width) + 1;
451 int yrange = (int)fabs(range_m / tile_height) + 1;
453 for ( int x = -xrange; x <= xrange; ++x )
455 for ( int y = -yrange; y <= yrange; ++y )
457 // We have already checked for the center tile.
458 if ( x != 0 || y != 0 )
460 SGBucket b = sgBucketOffset( current_longitude,
461 current_latitude, x, y );
462 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
463 // Do not ask if it is just the next tile but way out of range.
464 if (distance2 <= max_dist2)
466 available &= sched_tile( b, priority, false, duration );
467 if ((!available)&&(duration==0.0))
477 // Returns true if tiles around current view position have been loaded
478 bool FGTileMgr::isSceneryLoaded()
480 double range_m = 100.0;
481 if (scheduled_visibility < range_m)
482 range_m = scheduled_visibility;
484 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
487 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
493 std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
494 long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
495 SGBucket bucket(bucketIndex);
497 return _terra_sync->isTileDirPending(bucket.gen_base_path());