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/structure/exception.hxx>
36 #include <simgear/scene/model/modellib.hxx>
37 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
39 #include <Main/globals.hxx>
40 #include <Main/fg_props.hxx>
41 #include <Main/renderer.hxx>
42 #include <Main/viewer.hxx>
43 #include <Scripting/NasalSys.hxx>
45 #include "scenery.hxx"
46 #include "SceneryPager.hxx"
47 #include "tilemgr.hxx"
50 using flightgear::SceneryPager;
51 using simgear::SGModelLib;
52 using simgear::TileEntry;
53 using simgear::TileCache;
55 FGTileMgr::FGTileMgr():
62 FGTileMgr::~FGTileMgr() {
63 // remove all nodes we might have left behind
64 osg::Group* group = globals->get_scenery()->get_terrain_branch();
65 group->removeChildren(0, group->getNumChildren());
69 // Initialize the Tile Manager subsystem
70 void FGTileMgr::init() {
71 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
73 _options = new SGReaderWriterBTGOptions;
74 _options->setMatlib(globals->get_matlib());
75 _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
76 _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
77 osgDB::FilePathList &fp = _options->getDatabasePathList();
78 const string_list &sc = globals->get_fg_scenery();
80 std::copy(sc.begin(), sc.end(), back_inserter(fp));
82 TileEntry::setModelLoadHelper(this);
84 _visibilityMeters = fgGetNode("/environment/visibility-m", true);
90 void FGTileMgr::reinit()
96 previous_bucket.make_bad();
97 current_bucket.make_bad();
98 longitude = latitude = -1000.0;
100 // force an update now
105 /* schedule a tile for loading, keep request for given amount of time.
106 * Returns true if tile is already loaded. */
107 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
109 // see if tile already exists in the cache
110 TileEntry *t = tile_cache.get_tile( b );
113 // create a new entry
114 t = new TileEntry( b );
115 // insert the tile into the cache, update will generate load request
116 if ( tile_cache.insert_tile( t ) )
118 // Attach to scene graph
119 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
122 // insert failed (cache full with no available entries to
123 // delete.) Try again later
128 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
131 // update tile's properties
132 tile_cache.request_tile(t,priority,current_view,duration);
134 return t->is_loaded();
137 /* schedule needed buckets for the current view position for loading,
138 * keep request for given amount of time */
139 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
141 // sanity check (unfortunately needed!)
142 if ( longitude < -180.0 || longitude > 180.0
143 || latitude < -90.0 || latitude > 90.0 )
145 SG_LOG( SG_TERRAIN, SG_ALERT,
146 "Attempting to schedule tiles for bogus lon and lat = ("
147 << longitude << "," << latitude << ")" );
149 SG_LOG( SG_TERRAIN, SG_ALERT,
150 "This is a FATAL error. Exiting!" );
154 SG_LOG( SG_TERRAIN, SG_INFO,
155 "scheduling needed tiles for " << longitude << " " << latitude );
157 double tile_width = curr_bucket.get_width_m();
158 double tile_height = curr_bucket.get_height_m();
159 // cout << "tile width = " << tile_width << " tile_height = "
160 // << tile_height << endl;
162 xrange = (int)(vis / tile_width) + 1;
163 yrange = (int)(vis / tile_height) + 1;
164 if ( xrange < 1 ) { xrange = 1; }
165 if ( yrange < 1 ) { yrange = 1; }
167 // make the cache twice as large to avoid losing terrain when switching
168 // between aircraft and tower views
169 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
170 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
171 // cout << "max cache size = " << tile_cache.get_max_cache_size()
172 // << " current cache size = " << tile_cache.get_size() << endl;
174 // clear flags of all tiles belonging to the previous view set
175 tile_cache.clear_current_view();
177 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
178 osg::FrameStamp* framestamp
179 = globals->get_renderer()->getViewer()->getFrameStamp();
180 tile_cache.set_current_time(framestamp->getReferenceTime());
186 /* schedule all tiles, use distance-based loading priority,
187 * so tiles are loaded in innermost-to-outermost sequence. */
188 for ( x = -xrange; x <= xrange; ++x )
190 for ( y = -yrange; y <= yrange; ++y )
192 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
193 float priority = (-1.0) * (x*x+y*y);
194 sched_tile( b, priority, true, 0.0 );
200 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
203 if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
204 string_list sc = globals->get_fg_scenery();
206 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
208 tmpPath.append(modelPath);
209 if (tmpPath.exists()) {
215 fullPath.append(modelPath);
217 osg::Node* result = 0;
221 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
222 new FGNasalModelData);
225 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
226 new FGNasalModelData);
227 } catch (const sg_io_exception& exc) {
228 string m(exc.getMessage());
230 m += exc.getLocation().asString();
231 SG_LOG( SG_ALL, SG_ALERT, m );
232 } catch (const sg_exception& exc) { // XXX may be redundant
233 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
239 * Update the various queues maintained by the tilemagr (private
240 * internal function, do not call directly.)
242 void FGTileMgr::update_queues()
244 SceneryPager* pager = FGScenery::getPagerSingleton();
245 osg::FrameStamp* framestamp
246 = globals->get_renderer()->getViewer()->getFrameStamp();
247 double current_time = framestamp->getReferenceTime();
248 double vis = _visibilityMeters->getDoubleValue();
253 tile_cache.set_current_time( current_time );
254 tile_cache.reset_traversal();
256 while ( ! tile_cache.at_end() )
258 e = tile_cache.get_current();
259 // cout << "processing a tile" << endl;
262 // Prepare the ssg nodes corresponding to each tile.
263 // Set the ssg transform and update it's range selector
264 // based on current visibilty
265 e->prep_ssg_node(vis);
267 if (( !e->is_loaded() )&&
268 ( !e->is_expired(current_time) ))
270 // schedule tile for loading with osg pager
271 pager->queueRequest(e->tileFileName,
275 e->getDatabaseRequest(),
281 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
287 int drop_count = sz - tile_cache.get_max_cache_size();
288 if (( drop_count > 0 )&&
289 ((loading==0)||(drop_count > 10)))
291 long drop_index = tile_cache.get_drop_tile();
292 while ( drop_index > -1 )
294 // schedule tile for deletion with osg pager
295 TileEntry* old = tile_cache.get_tile(drop_index);
296 tile_cache.clear_entry(drop_index);
298 osg::ref_ptr<osg::Object> subgraph = old->getNode();
299 old->removeFromSceneGraph();
301 // zeros out subgraph ref_ptr, so subgraph is owned by
302 // the pager and will be deleted in the pager thread.
303 pager->queueDeleteRequest(subgraph);
305 if (--drop_count > 0)
306 drop_index = tile_cache.get_drop_tile();
313 // given the current lon/lat (in degrees), fill in the array of local
314 // chunks. If the chunk isn't already in the cache, then read it from
316 void FGTileMgr::update(double)
318 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
319 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
320 double vis = _visibilityMeters->getDoubleValue();
321 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
326 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
327 // "schedule_scenery" instead
328 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
330 longitude = location.getLongitudeDeg();
331 latitude = location.getLatitudeDeg();
333 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
334 // << longitude << " " << latatitude );
336 current_bucket.set_bucket( location );
338 // schedule more tiles when visibility increased considerably
339 // TODO Calculate tile size - instead of using fixed value (5000m)
340 if (range_m-scheduled_visibility > 5000.0)
341 previous_bucket.make_bad();
343 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
344 // << current_bucket );
345 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
347 // do tile load scheduling.
348 // Note that we need keep track of both viewer buckets and fdm buckets.
349 if ( state == Running ) {
350 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
351 if (current_bucket != previous_bucket) {
352 // We've moved to a new bucket, we need to schedule any
353 // needed tiles for loading.
354 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
355 scheduled_visibility = range_m;
356 schedule_needed(current_bucket, range_m);
359 previous_bucket = current_bucket;
360 } else if ( state == Start || state == Inited ) {
361 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
362 // do not update bucket yet (position not valid in initial loop)
364 previous_bucket.make_bad();
370 /** Schedules scenery for given position. Load request remains valid for given duration
371 * (duration=0.0 => nothing is loaded).
372 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
373 * Returns true when all tiles for the given position are already loaded, false otherwise.
375 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
377 const float priority = 0.0;
378 double current_longitude = position.getLongitudeDeg();
379 double current_latitude = position.getLatitudeDeg();
380 bool available = true;
382 // sanity check (unfortunately needed!)
383 if (current_longitude < -180 || current_longitude > 180 ||
384 current_latitude < -90 || current_latitude > 90)
387 SGBucket bucket(position);
388 available = sched_tile( bucket, priority, false, duration );
390 if ((!available)&&(duration==0.0))
393 SGVec3d cartPos = SGVec3d::fromGeod(position);
395 // Traverse all tiles required to be there for the given visibility.
396 double tile_width = bucket.get_width_m();
397 double tile_height = bucket.get_height_m();
398 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
399 double max_dist = tile_r + range_m;
400 double max_dist2 = max_dist*max_dist;
402 int xrange = (int)fabs(range_m / tile_width) + 1;
403 int yrange = (int)fabs(range_m / tile_height) + 1;
405 for ( int x = -xrange; x <= xrange; ++x )
407 for ( int y = -yrange; y <= yrange; ++y )
409 // We have already checked for the center tile.
410 if ( x != 0 || y != 0 )
412 SGBucket b = sgBucketOffset( current_longitude,
413 current_latitude, x, y );
414 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
415 // Do not ask if it is just the next tile but way out of range.
416 if (distance2 <= max_dist2)
418 available &= sched_tile( b, priority, false, duration );
419 if ((!available)&&(duration==0.0))
429 // Returns true if tiles around current view position have been loaded
430 bool FGTileMgr::isSceneryLoaded()
432 double range_m = 100.0;
433 if (scheduled_visibility < range_m)
434 range_m = scheduled_visibility;
436 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);