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 <simgear/constants.h>
32 #include <simgear/debug/logstream.hxx>
33 #include <simgear/math/point3d.hxx>
34 #include <simgear/math/polar3d.hxx>
35 #include <simgear/math/sg_geodesy.hxx>
36 #include <simgear/math/vector.hxx>
37 #include <simgear/structure/exception.hxx>
38 #include <simgear/scene/model/modellib.hxx>
39 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
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>
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
52 using flightgear::SceneryPager;
53 using simgear::SGModelLib;
54 using simgear::TileEntry;
55 using simgear::TileCache;
57 FGTileMgr::FGTileMgr():
64 FGTileMgr::~FGTileMgr() {
65 // remove all nodes we might have left behind
66 osg::Group* group = globals->get_scenery()->get_terrain_branch();
67 group->removeChildren(0, group->getNumChildren());
71 // Initialize the Tile Manager subsystem
72 int FGTileMgr::init() {
73 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
75 _options = new SGReaderWriterBTGOptions;
76 _options->setMatlib(globals->get_matlib());
77 _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
78 _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
79 osgDB::FilePathList &fp = _options->getDatabasePathList();
80 const string_list &sc = globals->get_fg_scenery();
82 std::copy(sc.begin(), sc.end(), back_inserter(fp));
84 TileEntry::setModelLoadHelper(this);
90 previous_bucket.make_bad();
91 current_bucket.make_bad();
93 longitude = latitude = -1000.0;
98 // schedule a tile for loading
99 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
100 // see if tile already exists in the cache
101 TileEntry *t = tile_cache.get_tile( b );
104 // make space in the cache
105 SceneryPager* pager = FGScenery::getPagerSingleton();
106 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
107 long index = tile_cache.get_oldest_tile();
109 TileEntry *old = tile_cache.get_tile( index );
110 tile_cache.clear_entry( index );
111 osg::ref_ptr<osg::Object> subgraph = old->getNode();
112 old->removeFromSceneGraph();
114 // zeros out subgraph ref_ptr, so subgraph is owned by
115 // the pager and will be deleted in the pager thread.
116 pager->queueDeleteRequest(subgraph);
118 // nothing to free ?!? forge ahead
123 // create a new entry
124 TileEntry *e = new TileEntry( b );
126 // insert the tile into the cache
127 if ( tile_cache.insert_tile( e ) ) {
128 // update_queues will generate load request
130 // insert failed (cache full with no available entries to
131 // delete.) Try again later
134 // Attach to scene graph
135 e->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
137 t->set_inner_ring( is_inner_ring );
142 // schedule a needed buckets for loading
143 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
144 // sanity check (unfortunately needed!)
145 if ( longitude < -180.0 || longitude > 180.0
146 || latitude < -90.0 || latitude > 90.0 )
148 SG_LOG( SG_TERRAIN, SG_ALERT,
149 "Attempting to schedule tiles for bogus lon and lat = ("
150 << longitude << "," << latitude << ")" );
152 SG_LOG( SG_TERRAIN, SG_ALERT,
153 "This is a FATAL error. Exiting!" );
157 SG_LOG( SG_TERRAIN, SG_INFO,
158 "scheduling needed tiles for " << longitude << " " << latitude );
160 // vis = fgGetDouble("/environment/visibility-m");
162 double tile_width = curr_bucket.get_width_m();
163 double tile_height = curr_bucket.get_height_m();
164 // cout << "tile width = " << tile_width << " tile_height = "
165 // << tile_height << endl;
167 xrange = (int)(vis / tile_width) + 1;
168 yrange = (int)(vis / tile_height) + 1;
169 if ( xrange < 1 ) { xrange = 1; }
170 if ( yrange < 1 ) { yrange = 1; }
172 // make the cache twice as large to avoid losing terrain when switching
173 // between aircraft and tower views
174 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
175 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
176 // cout << "max cache size = " << tile_cache.get_max_cache_size()
177 // << " current cache size = " << tile_cache.get_size() << endl;
179 // clear the inner ring flags so we can set them below. This
180 // prevents us from having "true" entries we aren't able to find
181 // to get rid of if we teleport a long ways away from the current
183 tile_cache.clear_inner_ring_flags();
187 // schedule center tile first so it can be loaded first
188 b = sgBucketOffset( longitude, latitude, 0, 0 );
189 sched_tile( b, true );
193 // schedule next ring of 8 tiles
194 for ( x = -1; x <= 1; ++x ) {
195 for ( y = -1; y <= 1; ++y ) {
196 if ( x != 0 || y != 0 ) {
197 b = sgBucketOffset( longitude, latitude, x, y );
198 sched_tile( b, true );
203 // schedule remaining tiles
204 for ( x = -xrange; x <= xrange; ++x ) {
205 for ( y = -yrange; y <= yrange; ++y ) {
206 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
207 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
208 sched_tile( b, false );
215 void FGTileMgr::initialize_queue()
217 // First time through or we have teleported, initialize the
218 // system and load all relavant tiles
220 SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
222 // cout << "tile cache size = " << tile_cache.get_size() << endl;
224 // wipe/initialize tile cache
225 // tile_cache.init();
226 previous_bucket.make_bad();
228 // build the local area list and schedule tiles for loading
230 // start with the center tile and work out in concentric
233 double visibility_meters = fgGetDouble("/environment/visibility-m");
234 schedule_needed(visibility_meters, current_bucket);
238 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
240 osg::Node* result = 0;
244 SGModelLib::loadModel(modelPath, globals->get_props(),
245 new FGNasalModelData);
249 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
250 new FGNasalModelData);
251 } catch (const sg_io_exception& exc) {
252 string m(exc.getMessage());
254 m += exc.getLocation().asString();
255 SG_LOG( SG_ALL, SG_ALERT, m );
256 } catch (const sg_exception& exc) { // XXX may be redundant
257 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
262 // Helper class for STL fun
263 class TileLoad : public std::unary_function<TileCache::tile_map::value_type,
267 TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
268 osg::Group* terrainBranch, osgDB::ReaderWriter::Options* options) :
269 _pager(pager), _framestamp(framestamp), _options(options) {}
271 TileLoad(const TileLoad& rhs) :
272 _pager(rhs._pager), _framestamp(rhs._framestamp),
273 _options(rhs._options) {}
275 void operator()(TileCache::tile_map::value_type& tilePair)
277 TileEntry* entry = tilePair.second;
278 if (entry->getNode()->getNumChildren() == 0) {
279 _pager->queueRequest(entry->tileFileName,
281 entry->get_inner_ring() ? 10.0f : 1.0f,
284 entry->getDatabaseRequest(),
290 SceneryPager* _pager;
291 osg::FrameStamp* _framestamp;
292 osgDB::ReaderWriter::Options* _options;
296 * Update the various queues maintained by the tilemagr (private
297 * internal function, do not call directly.)
299 void FGTileMgr::update_queues()
301 SceneryPager* pager = FGScenery::getPagerSingleton();
302 for_each(tile_cache.begin(), tile_cache.end(),
304 globals->get_renderer()->getViewer()->getFrameStamp(),
305 globals->get_scenery()->get_terrain_branch(), _options.get()));
309 // given the current lon/lat (in degrees), fill in the array of local
310 // chunks. If the chunk isn't already in the cache, then read it from
312 int FGTileMgr::update( double visibility_meters )
314 SGLocation *location = globals->get_current_view()->getSGLocation();
315 return update( location, visibility_meters );
319 int FGTileMgr::update( SGLocation *location, double visibility_meters )
321 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
323 longitude = location->getLongitude_deg();
324 latitude = location->getLatitude_deg();
325 // add 1.0m to the max altitude to give a little leeway to the
326 // ground reaction code.
327 altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
329 // if current altitude is apparently not initialized, set max
330 // altitude to something big.
331 if ( altitude_m < -1000 ) {
334 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
335 // << longitude << " " << latatitude );
337 current_bucket.set_bucket( longitude, latitude );
338 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
339 // << current_bucket );
340 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
342 // do tile load scheduling.
343 // Note that we need keep track of both viewer buckets and fdm buckets.
344 if ( state == Running ) {
345 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
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 schedule_needed(visibility_meters, current_bucket);
352 } else if ( state == Start || state == Inited ) {
353 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
354 // initialize_queue();
356 if (current_bucket != previous_bucket
357 && current_bucket.get_chunk_lon() != -1000) {
358 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
359 schedule_needed(visibility_meters, current_bucket);
366 previous_bucket = current_bucket;
371 void FGTileMgr::prep_ssg_nodes(float vis) {
373 // traverse the potentially viewable tile list and update range
374 // selector and transform
377 tile_cache.reset_traversal();
379 while ( ! tile_cache.at_end() ) {
380 // cout << "processing a tile" << endl;
381 if ( (e = tile_cache.get_current()) ) {
382 e->prep_ssg_node(vis);
384 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
390 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
392 // sanity check (unfortunately needed!)
393 if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
396 SGBucket bucket(lon, lat);
397 TileEntry *te = tile_cache.get_tile(bucket);
398 if (!te || !te->is_loaded())
401 // Traverse all tiles required to be there for the given visibility.
402 // This uses exactly the same algorithm like the tile scheduler.
403 double tile_width = bucket.get_width_m();
404 double tile_height = bucket.get_height_m();
406 int xrange = (int)fabs(range_m / tile_width) + 1;
407 int yrange = (int)fabs(range_m / tile_height) + 1;
409 for ( int x = -xrange; x <= xrange; ++x ) {
410 for ( int y = -yrange; y <= yrange; ++y ) {
411 // We have already checked for the center tile.
412 if ( x != 0 || y != 0 ) {
413 SGBucket b = sgBucketOffset( lon, lat, x, y );
414 TileEntry *te = tile_cache.get_tile(b);
415 if (!te || !te->is_loaded())
421 // Survived all tests.
427 struct IsTileLoaded :
428 public std::unary_function<TileCache::tile_map::value_type, bool>
430 bool operator()(const TileCache::tile_map::value_type& tilePair) const
432 return tilePair.second->is_loaded();
437 bool FGTileMgr::isSceneryLoaded()
439 return (std::find_if(tile_cache.begin(), tile_cache.end(),
440 std::not1(IsTileLoaded()))
441 == tile_cache.end());