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>
33 #include <simgear/constants.h>
34 #include <simgear/debug/logstream.hxx>
35 #include <simgear/math/point3d.hxx>
36 #include <simgear/math/polar3d.hxx>
37 #include <simgear/math/sg_geodesy.hxx>
38 #include <simgear/math/vector.hxx>
39 #include <simgear/structure/exception.hxx>
40 #include <simgear/scene/model/modellib.hxx>
41 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Main/renderer.hxx>
46 #include <Main/viewer.hxx>
47 #include <Scripting/NasalSys.hxx>
49 #include "scenery.hxx"
50 #include "SceneryPager.hxx"
51 #include "tilemgr.hxx"
54 using flightgear::SceneryPager;
55 using simgear::SGModelLib;
56 using simgear::TileEntry;
57 using simgear::TileCache;
59 FGTileMgr::FGTileMgr():
66 FGTileMgr::~FGTileMgr() {
67 // remove all nodes we might have left behind
68 osg::Group* group = globals->get_scenery()->get_terrain_branch();
69 group->removeChildren(0, group->getNumChildren());
73 // Initialize the Tile Manager subsystem
74 int FGTileMgr::init() {
75 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
77 _options = new SGReaderWriterBTGOptions;
78 _options->setMatlib(globals->get_matlib());
79 _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
80 _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
81 osgDB::FilePathList &fp = _options->getDatabasePathList();
82 const string_list &sc = globals->get_fg_scenery();
84 std::copy(sc.begin(), sc.end(), back_inserter(fp));
86 TileEntry::setModelLoadHelper(this);
92 previous_bucket.make_bad();
93 current_bucket.make_bad();
95 longitude = latitude = -1000.0;
100 // schedule a tile for loading
101 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
102 // see if tile already exists in the cache
103 TileEntry *t = tile_cache.get_tile( b );
106 // make space in the cache
107 SceneryPager* pager = FGScenery::getPagerSingleton();
108 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
109 long index = tile_cache.get_oldest_tile();
111 TileEntry *old = tile_cache.get_tile( index );
112 tile_cache.clear_entry( index );
113 osg::ref_ptr<osg::Object> subgraph = old->getNode();
114 old->removeFromSceneGraph();
116 // zeros out subgraph ref_ptr, so subgraph is owned by
117 // the pager and will be deleted in the pager thread.
118 pager->queueDeleteRequest(subgraph);
120 // nothing to free ?!? forge ahead
125 // create a new entry
126 TileEntry *e = new TileEntry( b );
128 // insert the tile into the cache
129 if ( tile_cache.insert_tile( e ) ) {
130 // update_queues will generate load request
132 // insert failed (cache full with no available entries to
133 // delete.) Try again later
136 // Attach to scene graph
137 e->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
139 t->set_inner_ring( is_inner_ring );
144 // schedule a needed buckets for loading
145 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
146 // sanity check (unfortunately needed!)
147 if ( longitude < -180.0 || longitude > 180.0
148 || latitude < -90.0 || latitude > 90.0 )
150 SG_LOG( SG_TERRAIN, SG_ALERT,
151 "Attempting to schedule tiles for bogus lon and lat = ("
152 << longitude << "," << latitude << ")" );
154 SG_LOG( SG_TERRAIN, SG_ALERT,
155 "This is a FATAL error. Exiting!" );
159 SG_LOG( SG_TERRAIN, SG_INFO,
160 "scheduling needed tiles for " << longitude << " " << latitude );
162 // vis = fgGetDouble("/environment/visibility-m");
164 double tile_width = curr_bucket.get_width_m();
165 double tile_height = curr_bucket.get_height_m();
166 // cout << "tile width = " << tile_width << " tile_height = "
167 // << tile_height << endl;
169 xrange = (int)(vis / tile_width) + 1;
170 yrange = (int)(vis / tile_height) + 1;
171 if ( xrange < 1 ) { xrange = 1; }
172 if ( yrange < 1 ) { yrange = 1; }
174 // make the cache twice as large to avoid losing terrain when switching
175 // between aircraft and tower views
176 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
177 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
178 // cout << "max cache size = " << tile_cache.get_max_cache_size()
179 // << " current cache size = " << tile_cache.get_size() << endl;
181 // clear the inner ring flags so we can set them below. This
182 // prevents us from having "true" entries we aren't able to find
183 // to get rid of if we teleport a long ways away from the current
185 tile_cache.clear_inner_ring_flags();
189 // schedule center tile first so it can be loaded first
190 b = sgBucketOffset( longitude, latitude, 0, 0 );
191 sched_tile( b, true );
195 // schedule next ring of 8 tiles
196 for ( x = -1; x <= 1; ++x ) {
197 for ( y = -1; y <= 1; ++y ) {
198 if ( x != 0 || y != 0 ) {
199 b = sgBucketOffset( longitude, latitude, x, y );
200 sched_tile( b, true );
205 // schedule remaining tiles
206 for ( x = -xrange; x <= xrange; ++x ) {
207 for ( y = -yrange; y <= yrange; ++y ) {
208 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
209 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
210 sched_tile( b, false );
217 void FGTileMgr::initialize_queue()
219 // First time through or we have teleported, initialize the
220 // system and load all relavant tiles
222 SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
224 // cout << "tile cache size = " << tile_cache.get_size() << endl;
226 // wipe/initialize tile cache
227 // tile_cache.init();
228 previous_bucket.make_bad();
230 // build the local area list and schedule tiles for loading
232 // start with the center tile and work out in concentric
235 double visibility_meters = fgGetDouble("/environment/visibility-m");
236 schedule_needed(visibility_meters, current_bucket);
240 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
242 osg::Node* result = 0;
246 SGModelLib::loadModel(modelPath, globals->get_props(),
247 new FGNasalModelData);
251 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
252 new FGNasalModelData);
253 } catch (const sg_io_exception& exc) {
254 string m(exc.getMessage());
256 m += exc.getLocation().asString();
257 SG_LOG( SG_ALL, SG_ALERT, m );
258 } catch (const sg_exception& exc) { // XXX may be redundant
259 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
264 // Helper class for STL fun
265 class TileLoad : public std::unary_function<TileCache::tile_map::value_type,
269 TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
270 osg::Group* terrainBranch, osgDB::ReaderWriter::Options* options) :
271 _pager(pager), _framestamp(framestamp), _options(options) {}
273 TileLoad(const TileLoad& rhs) :
274 _pager(rhs._pager), _framestamp(rhs._framestamp),
275 _options(rhs._options) {}
277 void operator()(TileCache::tile_map::value_type& tilePair)
279 TileEntry* entry = tilePair.second;
280 if (entry->getNode()->getNumChildren() == 0) {
281 _pager->queueRequest(entry->tileFileName,
283 entry->get_inner_ring() ? 10.0f : 1.0f,
286 entry->getDatabaseRequest(),
292 SceneryPager* _pager;
293 osg::FrameStamp* _framestamp;
294 osgDB::ReaderWriter::Options* _options;
298 * Update the various queues maintained by the tilemagr (private
299 * internal function, do not call directly.)
301 void FGTileMgr::update_queues()
303 SceneryPager* pager = FGScenery::getPagerSingleton();
304 for_each(tile_cache.begin(), tile_cache.end(),
306 globals->get_renderer()->getViewer()->getFrameStamp(),
307 globals->get_scenery()->get_terrain_branch(), _options.get()));
311 // given the current lon/lat (in degrees), fill in the array of local
312 // chunks. If the chunk isn't already in the cache, then read it from
314 int FGTileMgr::update( double visibility_meters )
316 SGLocation *location = globals->get_current_view()->getSGLocation();
317 return update( location, visibility_meters );
321 int FGTileMgr::update( SGLocation *location, double visibility_meters )
323 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
325 longitude = location->getLongitude_deg();
326 latitude = location->getLatitude_deg();
327 // add 1.0m to the max altitude to give a little leeway to the
328 // ground reaction code.
329 altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
331 // if current altitude is apparently not initialized, set max
332 // altitude to something big.
333 if ( altitude_m < -1000 ) {
336 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
337 // << longitude << " " << latatitude );
339 current_bucket.set_bucket( longitude, latitude );
340 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
341 // << current_bucket );
342 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
344 // do tile load scheduling.
345 // Note that we need keep track of both viewer buckets and fdm buckets.
346 if ( state == Running ) {
347 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
348 if (current_bucket != previous_bucket) {
349 // We've moved to a new bucket, we need to schedule any
350 // needed tiles for loading.
351 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
352 schedule_needed(visibility_meters, current_bucket);
354 } else if ( state == Start || state == Inited ) {
355 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
356 // initialize_queue();
358 if (current_bucket != previous_bucket
359 && current_bucket.get_chunk_lon() != -1000) {
360 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
361 schedule_needed(visibility_meters, current_bucket);
368 previous_bucket = current_bucket;
373 void FGTileMgr::prep_ssg_nodes(float vis) {
375 // traverse the potentially viewable tile list and update range
376 // selector and transform
379 tile_cache.reset_traversal();
381 while ( ! tile_cache.at_end() ) {
382 // cout << "processing a tile" << endl;
383 if ( (e = tile_cache.get_current()) ) {
384 e->prep_ssg_node(vis);
386 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
392 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
394 // sanity check (unfortunately needed!)
395 if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
398 SGBucket bucket(lon, lat);
399 TileEntry *te = tile_cache.get_tile(bucket);
400 if (!te || !te->is_loaded())
403 // Traverse all tiles required to be there for the given visibility.
404 // This uses exactly the same algorithm like the tile scheduler.
405 double tile_width = bucket.get_width_m();
406 double tile_height = bucket.get_height_m();
408 int xrange = (int)fabs(range_m / tile_width) + 1;
409 int yrange = (int)fabs(range_m / tile_height) + 1;
411 for ( int x = -xrange; x <= xrange; ++x ) {
412 for ( int y = -yrange; y <= yrange; ++y ) {
413 // We have already checked for the center tile.
414 if ( x != 0 || y != 0 ) {
415 SGBucket b = sgBucketOffset( lon, lat, x, y );
416 TileEntry *te = tile_cache.get_tile(b);
417 if (!te || !te->is_loaded())
423 // Survived all tests.
429 struct IsTileLoaded :
430 public std::unary_function<TileCache::tile_map::value_type, bool>
432 bool operator()(const TileCache::tile_map::value_type& tilePair) const
434 return tilePair.second->is_loaded();
439 bool FGTileMgr::isSceneryLoaded()
441 return (std::find_if(tile_cache.begin(), tile_cache.end(),
442 std::not1(IsTileLoaded()))
443 == tile_cache.end());