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>
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"
51 using flightgear::SceneryPager;
54 FGTileMgr::FGTileMgr():
56 last_state( Running ),
59 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
60 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
61 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true))
66 FGTileMgr::~FGTileMgr()
68 // remove all nodes we might have left behind
69 osg::Group* group = globals->get_scenery()->get_terrain_branch();
70 group->removeChildren(0, group->getNumChildren());
72 osgDB::Registry::instance()->clearObjectCache();
76 // Initialize the Tile Manager subsystem
77 void FGTileMgr::init() {
78 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
80 _options = new simgear::SGReaderWriterOptions;
81 _options->setMaterialLib(globals->get_matlib());
82 _options->setPropertyNode(globals->get_props());
84 osgDB::FilePathList &fp = _options->getDatabasePathList();
85 const string_list &sc = globals->get_fg_scenery();
87 std::copy(sc.begin(), sc.end(), back_inserter(fp));
88 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
89 if (!_disableNasalHooks->getBoolValue())
90 _options->setModelData(new FGNasalModelDataProxy);
95 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
97 ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
100 void FGTileMgr::reinit()
102 // remove all old scenery nodes from scenegraph and clear cache
103 osg::Group* group = globals->get_scenery()->get_terrain_branch();
104 group->removeChildren(0, group->getNumChildren());
107 // clear OSG cache, except on initial start-up
110 osgDB::Registry::instance()->clearObjectCache();
115 previous_bucket.make_bad();
116 current_bucket.make_bad();
117 longitude = latitude = -1000.0;
119 _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
121 _terra_sync->setTileRefreshCb(&refresh_tile, this);
123 // force an update now
127 /* schedule a tile for loading, keep request for given amount of time.
128 * Returns true if tile is already loaded. */
129 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
131 // see if tile already exists in the cache
132 TileEntry *t = tile_cache.get_tile( b );
135 // create a new entry
136 t = new TileEntry( b );
137 // insert the tile into the cache, update will generate load request
138 if ( tile_cache.insert_tile( t ) )
140 // Attach to scene graph
142 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
145 // insert failed (cache full with no available entries to
146 // delete.) Try again later
151 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
154 // update tile's properties
155 tile_cache.request_tile(t,priority,current_view,duration);
157 return t->is_loaded();
160 /* schedule needed buckets for the current view position for loading,
161 * keep request for given amount of time */
162 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
164 // sanity check (unfortunately needed!)
165 if ( longitude < -180.0 || longitude > 180.0
166 || latitude < -90.0 || latitude > 90.0 )
168 SG_LOG( SG_TERRAIN, SG_ALERT,
169 "Attempting to schedule tiles for bogus lon and lat = ("
170 << longitude << "," << latitude << ")" );
174 SG_LOG( SG_TERRAIN, SG_INFO,
175 "scheduling needed tiles for " << longitude << " " << latitude );
177 double tile_width = curr_bucket.get_width_m();
178 double tile_height = curr_bucket.get_height_m();
179 // cout << "tile width = " << tile_width << " tile_height = "
180 // << tile_height << endl;
182 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
183 xrange = (int)(tileRangeM / tile_width) + 1;
184 yrange = (int)(tileRangeM / tile_height) + 1;
185 if ( xrange < 1 ) { xrange = 1; }
186 if ( yrange < 1 ) { yrange = 1; }
188 // make the cache twice as large to avoid losing terrain when switching
189 // between aircraft and tower views
190 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
191 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
192 // cout << "max cache size = " << tile_cache.get_max_cache_size()
193 // << " current cache size = " << tile_cache.get_size() << endl;
195 // clear flags of all tiles belonging to the previous view set
196 tile_cache.clear_current_view();
198 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
199 osg::FrameStamp* framestamp
200 = globals->get_renderer()->getViewer()->getFrameStamp();
201 tile_cache.set_current_time(framestamp->getReferenceTime());
207 /* schedule all tiles, use distance-based loading priority,
208 * so tiles are loaded in innermost-to-outermost sequence. */
209 for ( x = -xrange; x <= xrange; ++x )
211 for ( y = -yrange; y <= yrange; ++y )
213 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
214 float priority = (-1.0) * (x*x+y*y);
215 sched_tile( b, priority, true, 0.0 );
221 * Update the various queues maintained by the tilemagr (private
222 * internal function, do not call directly.)
224 void FGTileMgr::update_queues()
226 SceneryPager* pager = FGScenery::getPagerSingleton();
227 osg::FrameStamp* framestamp
228 = globals->get_renderer()->getViewer()->getFrameStamp();
229 double current_time = framestamp->getReferenceTime();
230 double vis = _visibilityMeters->getDoubleValue();
235 tile_cache.set_current_time( current_time );
236 tile_cache.reset_traversal();
238 while ( ! tile_cache.at_end() )
240 e = tile_cache.get_current();
241 // cout << "processing a tile" << endl;
244 // Prepare the ssg nodes corresponding to each tile.
245 // Set the ssg transform and update it's range selector
246 // based on current visibilty
247 e->prep_ssg_node(vis);
249 if (( !e->is_loaded() )&&
250 ((!e->is_expired(current_time))||
251 e->is_current_view() ))
253 // schedule tile for loading with osg pager
254 pager->queueRequest(e->tileFileName,
258 e->getDatabaseRequest(),
264 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
270 int drop_count = sz - tile_cache.get_max_cache_size();
271 if (( drop_count > 0 )&&
272 ((loading==0)||(drop_count > 10)))
274 long drop_index = tile_cache.get_drop_tile();
275 while ( drop_index > -1 )
277 // schedule tile for deletion with osg pager
278 TileEntry* old = tile_cache.get_tile(drop_index);
279 tile_cache.clear_entry(drop_index);
281 osg::ref_ptr<osg::Object> subgraph = old->getNode();
282 old->removeFromSceneGraph();
284 // zeros out subgraph ref_ptr, so subgraph is owned by
285 // the pager and will be deleted in the pager thread.
286 pager->queueDeleteRequest(subgraph);
288 if (--drop_count > 0)
289 drop_index = tile_cache.get_drop_tile();
296 // given the current lon/lat (in degrees), fill in the array of local
297 // chunks. If the chunk isn't already in the cache, then read it from
299 void FGTileMgr::update(double)
301 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
302 double vis = _visibilityMeters->getDoubleValue();
303 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
308 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
309 // "schedule_scenery" instead
310 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
312 longitude = location.getLongitudeDeg();
313 latitude = location.getLatitudeDeg();
315 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
316 // << longitude << " " << latatitude );
318 current_bucket.set_bucket( location );
320 // schedule more tiles when visibility increased considerably
321 // TODO Calculate tile size - instead of using fixed value (5000m)
322 if (range_m-scheduled_visibility > 5000.0)
323 previous_bucket.make_bad();
325 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
326 // << current_bucket );
327 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
329 // do tile load scheduling.
330 // Note that we need keep track of both viewer buckets and fdm buckets.
331 if ( state == Running ) {
332 if (last_state != state)
334 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
336 if (current_bucket != previous_bucket) {
337 // We've moved to a new bucket, we need to schedule any
338 // needed tiles for loading.
339 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
340 scheduled_visibility = range_m;
341 schedule_needed(current_bucket, range_m);
343 _terra_sync->schedulePosition(latitude,longitude);
346 previous_bucket = current_bucket;
347 } else if ( state == Start || state == Inited ) {
348 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
349 // do not update bucket yet (position not valid in initial loop)
351 previous_bucket.make_bad();
358 /** Schedules scenery for given position. Load request remains valid for given duration
359 * (duration=0.0 => nothing is loaded).
360 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
361 * Returns true when all tiles for the given position are already loaded, false otherwise.
363 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
365 const float priority = 0.0;
366 double current_longitude = position.getLongitudeDeg();
367 double current_latitude = position.getLatitudeDeg();
368 bool available = true;
370 // sanity check (unfortunately needed!)
371 if (current_longitude < -180 || current_longitude > 180 ||
372 current_latitude < -90 || current_latitude > 90)
375 SGBucket bucket(position);
376 available = sched_tile( bucket, priority, false, duration );
378 if ((!available)&&(duration==0.0))
381 SGVec3d cartPos = SGVec3d::fromGeod(position);
383 // Traverse all tiles required to be there for the given visibility.
384 double tile_width = bucket.get_width_m();
385 double tile_height = bucket.get_height_m();
386 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
387 double max_dist = tile_r + range_m;
388 double max_dist2 = max_dist*max_dist;
390 int xrange = (int)fabs(range_m / tile_width) + 1;
391 int yrange = (int)fabs(range_m / tile_height) + 1;
393 for ( int x = -xrange; x <= xrange; ++x )
395 for ( int y = -yrange; y <= yrange; ++y )
397 // We have already checked for the center tile.
398 if ( x != 0 || y != 0 )
400 SGBucket b = sgBucketOffset( current_longitude,
401 current_latitude, x, y );
402 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
403 // Do not ask if it is just the next tile but way out of range.
404 if (distance2 <= max_dist2)
406 available &= sched_tile( b, priority, false, duration );
407 if ((!available)&&(duration==0.0))
417 // Returns true if tiles around current view position have been loaded
418 bool FGTileMgr::isSceneryLoaded()
420 double range_m = 100.0;
421 if (scheduled_visibility < range_m)
422 range_m = scheduled_visibility;
424 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);