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>
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Main/renderer.hxx>
43 #include <Main/viewer.hxx>
44 #include <Scripting/NasalSys.hxx>
46 #include "newcache.hxx"
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
52 using flightgear::SceneryPager;
54 #define TEST_LAST_HIT_CACHE
57 FGTileMgr::FGTileMgr():
66 FGTileMgr::~FGTileMgr() {
70 // Initialize the Tile Manager subsystem
71 int FGTileMgr::init() {
72 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
78 previous_bucket.make_bad();
79 current_bucket.make_bad();
81 longitude = latitude = -1000.0;
87 // schedule a tile for loading
88 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
89 // see if tile already exists in the cache
90 FGTileEntry *t = tile_cache.get_tile( b );
93 // make space in the cache
94 SceneryPager* pager = FGScenery::getPagerSingleton();
95 while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
96 long index = tile_cache.get_oldest_tile();
98 FGTileEntry *old = tile_cache.get_tile( index );
99 tile_cache.clear_entry( index );
100 osg::ref_ptr<osg::Object> subgraph = old->getNode();
101 old->disconnect_ssg_nodes();
103 // zeros out subgraph ref_ptr, so subgraph is owned by
104 // the pager and will be deleted in the pager thread.
105 pager->queueDeleteRequest(subgraph);
107 // nothing to free ?!? forge ahead
112 // create a new entry
113 FGTileEntry *e = new FGTileEntry( b );
115 // insert the tile into the cache
116 if ( tile_cache.insert_tile( e ) ) {
117 // update_queues will generate load request
119 // insert failed (cache full with no available entries to
120 // delete.) Try again later
123 // Attach to scene graph
124 e->add_ssg_nodes(globals->get_scenery()->get_terrain_branch());
126 t->set_inner_ring( is_inner_ring );
131 // schedule a needed buckets for loading
132 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
133 // sanity check (unfortunately needed!)
134 if ( longitude < -180.0 || longitude > 180.0
135 || latitude < -90.0 || latitude > 90.0 )
137 SG_LOG( SG_TERRAIN, SG_ALERT,
138 "Attempting to schedule tiles for bogus lon and lat = ("
139 << longitude << "," << latitude << ")" );
141 SG_LOG( SG_TERRAIN, SG_ALERT,
142 "This is a FATAL error. Exiting!" );
146 SG_LOG( SG_TERRAIN, SG_INFO,
147 "scheduling needed tiles for " << longitude << " " << latitude );
149 // vis = fgGetDouble("/environment/visibility-m");
151 double tile_width = curr_bucket.get_width_m();
152 double tile_height = curr_bucket.get_height_m();
153 // cout << "tile width = " << tile_width << " tile_height = "
154 // << tile_height << endl;
156 xrange = (int)(vis / tile_width) + 1;
157 yrange = (int)(vis / tile_height) + 1;
158 if ( xrange < 1 ) { xrange = 1; }
159 if ( yrange < 1 ) { yrange = 1; }
161 // note * 2 at end doubles cache size (for fdm and viewer)
162 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
163 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
164 // cout << "max cache size = " << tile_cache.get_max_cache_size()
165 // << " current cache size = " << tile_cache.get_size() << endl;
167 // clear the inner ring flags so we can set them below. This
168 // prevents us from having "true" entries we aren't able to find
169 // to get rid of if we teleport a long ways away from the current
171 tile_cache.clear_inner_ring_flags();
175 // schedule center tile first so it can be loaded first
176 b = sgBucketOffset( longitude, latitude, 0, 0 );
177 sched_tile( b, true );
181 // schedule next ring of 8 tiles
182 for ( x = -1; x <= 1; ++x ) {
183 for ( y = -1; y <= 1; ++y ) {
184 if ( x != 0 || y != 0 ) {
185 b = sgBucketOffset( longitude, latitude, x, y );
186 sched_tile( b, true );
191 // schedule remaining tiles
192 for ( x = -xrange; x <= xrange; ++x ) {
193 for ( y = -yrange; y <= yrange; ++y ) {
194 if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
195 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
196 sched_tile( b, false );
203 void FGTileMgr::initialize_queue()
205 // First time through or we have teleported, initialize the
206 // system and load all relavant tiles
208 SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
210 // cout << "tile cache size = " << tile_cache.get_size() << endl;
212 // wipe/initialize tile cache
213 // tile_cache.init();
214 previous_bucket.make_bad();
216 // build the local area list and schedule tiles for loading
218 // start with the center tile and work out in concentric
221 double visibility_meters = fgGetDouble("/environment/visibility-m");
222 schedule_needed(visibility_meters, current_bucket);
224 // do we really want to lose this? CLO
226 // Now force a load of the center tile and inner ring so we
227 // have something to see in our first frame.
229 for ( i = 0; i < 9; ++i ) {
230 if ( load_queue.size() ) {
231 SG_LOG( SG_TERRAIN, SG_DEBUG,
232 "Load queue not empty, loading a tile" );
234 SGBucket pending = load_queue.front();
235 load_queue.pop_front();
236 load_tile( pending );
243 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
245 osg::Node* result = 0;
248 globals->get_model_lib()->load_model(".",
250 globals->get_props(),
251 globals->get_sim_time_sec(),
253 new FGNasalModelData );
254 } catch (const sg_io_exception& exc) {
255 string m(exc.getMessage());
257 m += exc.getLocation().asString();
258 SG_LOG( SG_ALL, SG_ALERT, m );
259 } catch (const sg_exception& exc) { // XXX may be redundant
260 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
265 // Helper class for STL fun
266 class TileLoad : public std::unary_function<FGNewCache::tile_map::value_type,
270 TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
271 osg::Group* terrainBranch) :
272 _pager(pager), _framestamp(framestamp) {}
273 TileLoad(const TileLoad& rhs) :
274 _pager(rhs._pager), _framestamp(rhs._framestamp) {}
275 void operator()(FGNewCache::tile_map::value_type& tilePair)
277 FGTileEntry* entry = tilePair.second;
278 if (entry->getNode()->getNumChildren() == 0) {
279 _pager->queueRequest(entry->tileFileName,
281 entry->get_inner_ring() ? 10.0f : 1.0f,
286 SceneryPager* _pager;
287 osg::FrameStamp* _framestamp;
291 * Update the various queues maintained by the tilemagr (private
292 * internal function, do not call directly.)
294 void FGTileMgr::update_queues()
296 SceneryPager* pager = FGScenery::getPagerSingleton();
297 for_each(tile_cache.begin(), tile_cache.end(),
299 globals->get_renderer()->getViewer()->getFrameStamp(),
300 globals->get_scenery()->get_terrain_branch()));
304 // given the current lon/lat (in degrees), fill in the array of local
305 // chunks. If the chunk isn't already in the cache, then read it from
307 int FGTileMgr::update( double visibility_meters )
309 SGLocation *location = globals->get_current_view()->getSGLocation();
310 return update( location, visibility_meters );
314 int FGTileMgr::update( SGLocation *location, double visibility_meters )
316 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
318 longitude = location->getLongitude_deg();
319 latitude = location->getLatitude_deg();
320 // add 1.0m to the max altitude to give a little leeway to the
321 // ground reaction code.
322 altitude_m = location->getAltitudeASL_ft() * SG_FEET_TO_METER + 1.0;
324 // if current altitude is apparently not initialized, set max
325 // altitude to something big.
326 if ( altitude_m < -1000 ) {
329 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
330 // << longitude << " " << latatitude );
332 current_bucket.set_bucket( longitude, latitude );
333 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
334 // << current_bucket );
335 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
337 // do tile load scheduling.
338 // Note that we need keep track of both viewer buckets and fdm buckets.
339 if ( state == Running ) {
340 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
341 if (current_bucket != previous_bucket) {
342 // We've moved to a new bucket, we need to schedule any
343 // needed tiles for loading.
344 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
345 schedule_needed(visibility_meters, current_bucket);
347 } else if ( state == Start || state == Inited ) {
348 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
349 // initialize_queue();
351 if (current_bucket != previous_bucket
352 && current_bucket.get_chunk_lon() != -1000) {
353 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
354 schedule_needed(visibility_meters, current_bucket);
361 previous_bucket = current_bucket;
366 void FGTileMgr::prep_ssg_nodes(float vis) {
368 // traverse the potentially viewable tile list and update range
369 // selector and transform
372 tile_cache.reset_traversal();
374 while ( ! tile_cache.at_end() ) {
375 // cout << "processing a tile" << endl;
376 if ( (e = tile_cache.get_current()) ) {
377 e->prep_ssg_node(vis);
379 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
385 bool FGTileMgr::scenery_available(double lat, double lon, double range_m)
387 // sanity check (unfortunately needed!)
388 if ( lon <= -180.0 || lon >= 180.0 || lat <= -90.0 || lat >= 90.0 )
391 SGBucket bucket(lon, lat);
392 FGTileEntry *te = tile_cache.get_tile(bucket);
393 if (!te || !te->is_loaded())
396 // Traverse all tiles required to be there for the given visibility.
397 // This uses exactly the same algorithm like the tile scheduler.
398 double tile_width = bucket.get_width_m();
399 double tile_height = bucket.get_height_m();
401 int xrange = (int)fabs(range_m / tile_width) + 1;
402 int yrange = (int)fabs(range_m / tile_height) + 1;
404 for ( int x = -xrange; x <= xrange; ++x ) {
405 for ( int y = -yrange; y <= yrange; ++y ) {
406 // We have already checked for the center tile.
407 if ( x != 0 || y != 0 ) {
408 SGBucket b = sgBucketOffset( lon, lat, x, y );
409 FGTileEntry *te = tile_cache.get_tile(b);
410 if (!te || !te->is_loaded())
416 // Survived all tests.
422 struct IsTileLoaded :
423 public std::unary_function<FGNewCache::tile_map::value_type, bool>
425 bool operator()(const FGNewCache::tile_map::value_type& tilePair) const
427 return tilePair.second->is_loaded();
432 bool FGTileMgr::isSceneryLoaded()
434 return (std::find_if(tile_cache.begin(), tile_cache.end(),
435 std::not1(IsTileLoaded()))
436 == tile_cache.end());