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;
52 using simgear::TileEntry;
53 using simgear::TileCache;
56 FGTileMgr::FGTileMgr():
58 last_state( Running ),
61 _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
62 _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
63 _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true))
68 FGTileMgr::~FGTileMgr()
70 // remove all nodes we might have left behind
71 osg::Group* group = globals->get_scenery()->get_terrain_branch();
72 group->removeChildren(0, group->getNumChildren());
74 osgDB::Registry::instance()->clearObjectCache();
78 // Initialize the Tile Manager subsystem
79 void FGTileMgr::init() {
80 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
82 _options = new simgear::SGReaderWriterOptions;
83 _options->setMaterialLib(globals->get_matlib());
84 _options->setPropertyNode(globals->get_props());
86 osgDB::FilePathList &fp = _options->getDatabasePathList();
87 const string_list &sc = globals->get_fg_scenery();
89 std::copy(sc.begin(), sc.end(), back_inserter(fp));
90 _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
91 if (!_disableNasalHooks->getBoolValue())
92 _options->setModelData(new FGNasalModelDataProxy);
97 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
99 ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
102 void FGTileMgr::reinit()
104 // remove all old scenery nodes from scenegraph and clear cache
105 osg::Group* group = globals->get_scenery()->get_terrain_branch();
106 group->removeChildren(0, group->getNumChildren());
109 // clear OSG cache, except on initial start-up
112 osgDB::Registry::instance()->clearObjectCache();
117 previous_bucket.make_bad();
118 current_bucket.make_bad();
119 longitude = latitude = -1000.0;
121 _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
123 _terra_sync->setTileRefreshCb(&refresh_tile, this);
125 // force an update now
129 /* schedule a tile for loading, keep request for given amount of time.
130 * Returns true if tile is already loaded. */
131 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
133 // see if tile already exists in the cache
134 TileEntry *t = tile_cache.get_tile( b );
137 // create a new entry
138 t = new TileEntry( b );
139 // insert the tile into the cache, update will generate load request
140 if ( tile_cache.insert_tile( t ) )
142 // Attach to scene graph
144 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
147 // insert failed (cache full with no available entries to
148 // delete.) Try again later
153 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
156 // update tile's properties
157 tile_cache.request_tile(t,priority,current_view,duration);
159 return t->is_loaded();
162 /* schedule needed buckets for the current view position for loading,
163 * keep request for given amount of time */
164 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
166 // sanity check (unfortunately needed!)
167 if ( longitude < -180.0 || longitude > 180.0
168 || latitude < -90.0 || latitude > 90.0 )
170 SG_LOG( SG_TERRAIN, SG_ALERT,
171 "Attempting to schedule tiles for bogus lon and lat = ("
172 << longitude << "," << latitude << ")" );
176 SG_LOG( SG_TERRAIN, SG_INFO,
177 "scheduling needed tiles for " << longitude << " " << latitude );
179 double tile_width = curr_bucket.get_width_m();
180 double tile_height = curr_bucket.get_height_m();
181 // cout << "tile width = " << tile_width << " tile_height = "
182 // << tile_height << endl;
184 double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
185 xrange = (int)(tileRangeM / tile_width) + 1;
186 yrange = (int)(tileRangeM / tile_height) + 1;
187 if ( xrange < 1 ) { xrange = 1; }
188 if ( yrange < 1 ) { yrange = 1; }
190 // make the cache twice as large to avoid losing terrain when switching
191 // between aircraft and tower views
192 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
193 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
194 // cout << "max cache size = " << tile_cache.get_max_cache_size()
195 // << " current cache size = " << tile_cache.get_size() << endl;
197 // clear flags of all tiles belonging to the previous view set
198 tile_cache.clear_current_view();
200 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
201 osg::FrameStamp* framestamp
202 = globals->get_renderer()->getViewer()->getFrameStamp();
203 tile_cache.set_current_time(framestamp->getReferenceTime());
209 /* schedule all tiles, use distance-based loading priority,
210 * so tiles are loaded in innermost-to-outermost sequence. */
211 for ( x = -xrange; x <= xrange; ++x )
213 for ( y = -yrange; y <= yrange; ++y )
215 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
216 float priority = (-1.0) * (x*x+y*y);
217 sched_tile( b, priority, true, 0.0 );
223 * Update the various queues maintained by the tilemagr (private
224 * internal function, do not call directly.)
226 void FGTileMgr::update_queues()
228 SceneryPager* pager = FGScenery::getPagerSingleton();
229 osg::FrameStamp* framestamp
230 = globals->get_renderer()->getViewer()->getFrameStamp();
231 double current_time = framestamp->getReferenceTime();
232 double vis = _visibilityMeters->getDoubleValue();
237 tile_cache.set_current_time( current_time );
238 tile_cache.reset_traversal();
240 while ( ! tile_cache.at_end() )
242 e = tile_cache.get_current();
243 // cout << "processing a tile" << endl;
246 // Prepare the ssg nodes corresponding to each tile.
247 // Set the ssg transform and update it's range selector
248 // based on current visibilty
249 e->prep_ssg_node(vis);
251 if (( !e->is_loaded() )&&
252 ((!e->is_expired(current_time))||
253 e->is_current_view() ))
255 // schedule tile for loading with osg pager
256 pager->queueRequest(e->tileFileName,
260 e->getDatabaseRequest(),
266 SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
272 int drop_count = sz - tile_cache.get_max_cache_size();
273 if (( drop_count > 0 )&&
274 ((loading==0)||(drop_count > 10)))
276 long drop_index = tile_cache.get_drop_tile();
277 while ( drop_index > -1 )
279 // schedule tile for deletion with osg pager
280 TileEntry* old = tile_cache.get_tile(drop_index);
281 tile_cache.clear_entry(drop_index);
283 osg::ref_ptr<osg::Object> subgraph = old->getNode();
284 old->removeFromSceneGraph();
286 // zeros out subgraph ref_ptr, so subgraph is owned by
287 // the pager and will be deleted in the pager thread.
288 pager->queueDeleteRequest(subgraph);
290 if (--drop_count > 0)
291 drop_index = tile_cache.get_drop_tile();
298 // given the current lon/lat (in degrees), fill in the array of local
299 // chunks. If the chunk isn't already in the cache, then read it from
301 void FGTileMgr::update(double)
303 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
304 double vis = _visibilityMeters->getDoubleValue();
305 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
310 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
311 // "schedule_scenery" instead
312 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
314 longitude = location.getLongitudeDeg();
315 latitude = location.getLatitudeDeg();
317 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
318 // << longitude << " " << latatitude );
320 current_bucket.set_bucket( location );
322 // schedule more tiles when visibility increased considerably
323 // TODO Calculate tile size - instead of using fixed value (5000m)
324 if (range_m-scheduled_visibility > 5000.0)
325 previous_bucket.make_bad();
327 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
328 // << current_bucket );
329 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
331 // do tile load scheduling.
332 // Note that we need keep track of both viewer buckets and fdm buckets.
333 if ( state == Running ) {
334 if (last_state != state)
336 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
338 if (current_bucket != previous_bucket) {
339 // We've moved to a new bucket, we need to schedule any
340 // needed tiles for loading.
341 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
342 scheduled_visibility = range_m;
343 schedule_needed(current_bucket, range_m);
345 _terra_sync->schedulePosition(latitude,longitude);
348 previous_bucket = current_bucket;
349 } else if ( state == Start || state == Inited ) {
350 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
351 // do not update bucket yet (position not valid in initial loop)
353 previous_bucket.make_bad();
360 /** Schedules scenery for given position. Load request remains valid for given duration
361 * (duration=0.0 => nothing is loaded).
362 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
363 * Returns true when all tiles for the given position are already loaded, false otherwise.
365 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
367 const float priority = 0.0;
368 double current_longitude = position.getLongitudeDeg();
369 double current_latitude = position.getLatitudeDeg();
370 bool available = true;
372 // sanity check (unfortunately needed!)
373 if (current_longitude < -180 || current_longitude > 180 ||
374 current_latitude < -90 || current_latitude > 90)
377 SGBucket bucket(position);
378 available = sched_tile( bucket, priority, false, duration );
380 if ((!available)&&(duration==0.0))
383 SGVec3d cartPos = SGVec3d::fromGeod(position);
385 // Traverse all tiles required to be there for the given visibility.
386 double tile_width = bucket.get_width_m();
387 double tile_height = bucket.get_height_m();
388 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
389 double max_dist = tile_r + range_m;
390 double max_dist2 = max_dist*max_dist;
392 int xrange = (int)fabs(range_m / tile_width) + 1;
393 int yrange = (int)fabs(range_m / tile_height) + 1;
395 for ( int x = -xrange; x <= xrange; ++x )
397 for ( int y = -yrange; y <= yrange; ++y )
399 // We have already checked for the center tile.
400 if ( x != 0 || y != 0 )
402 SGBucket b = sgBucketOffset( current_longitude,
403 current_latitude, x, y );
404 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
405 // Do not ask if it is just the next tile but way out of range.
406 if (distance2 <= max_dist2)
408 available &= sched_tile( b, priority, false, duration );
409 if ((!available)&&(duration==0.0))
419 // Returns true if tiles around current view position have been loaded
420 bool FGTileMgr::isSceneryLoaded()
422 double range_m = 100.0;
423 if (scheduled_visibility < range_m)
424 range_m = scheduled_visibility;
426 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);