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;
56 // helper: listen to property changes affecting tile loading
57 class LoaderPropertyWatcher : public SGPropertyChangeListener
60 LoaderPropertyWatcher(FGTileMgr* pTileMgr) :
65 virtual void valueChanged(SGPropertyNode*)
67 _pTileMgr->configChanged();
75 FGTileMgr::FGTileMgr():
78 _propListener(new LoaderPropertyWatcher(this))
80 _randomObjects = fgGetNode("/sim/rendering/random-objects", true);
81 _randomVegetation = fgGetNode("/sim/rendering/random-vegetation", true);
85 FGTileMgr::~FGTileMgr() {
86 // remove all nodes we might have left behind
87 osg::Group* group = globals->get_scenery()->get_terrain_branch();
88 group->removeChildren(0, group->getNumChildren());
94 // Initialize the Tile Manager subsystem
95 void FGTileMgr::init() {
96 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
98 _options = new SGReaderWriterBTGOptions;
99 _options->setMatlib(globals->get_matlib());
101 _randomObjects.get()->addChangeListener(_propListener, false);
102 _randomVegetation.get()->addChangeListener(_propListener, false);
105 osgDB::FilePathList &fp = _options->getDatabasePathList();
106 const string_list &sc = globals->get_fg_scenery();
108 std::copy(sc.begin(), sc.end(), back_inserter(fp));
110 TileEntry::setModelLoadHelper(this);
112 _visibilityMeters = fgGetNode("/environment/visibility-m", true);
118 void FGTileMgr::reinit()
124 previous_bucket.make_bad();
125 current_bucket.make_bad();
126 longitude = latitude = -1000.0;
128 // force an update now
132 void FGTileMgr::configChanged()
134 _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
135 _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
138 /* schedule a tile for loading, keep request for given amount of time.
139 * Returns true if tile is already loaded. */
140 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
142 // see if tile already exists in the cache
143 TileEntry *t = tile_cache.get_tile( b );
146 // create a new entry
147 t = new TileEntry( b );
148 // insert the tile into the cache, update will generate load request
149 if ( tile_cache.insert_tile( t ) )
151 // Attach to scene graph
152 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
155 // insert failed (cache full with no available entries to
156 // delete.) Try again later
161 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
164 // update tile's properties
165 tile_cache.request_tile(t,priority,current_view,duration);
167 return t->is_loaded();
170 /* schedule needed buckets for the current view position for loading,
171 * keep request for given amount of time */
172 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
174 // sanity check (unfortunately needed!)
175 if ( longitude < -180.0 || longitude > 180.0
176 || latitude < -90.0 || latitude > 90.0 )
178 SG_LOG( SG_TERRAIN, SG_ALERT,
179 "Attempting to schedule tiles for bogus lon and lat = ("
180 << longitude << "," << latitude << ")" );
182 SG_LOG( SG_TERRAIN, SG_ALERT,
183 "This is a FATAL error. Exiting!" );
187 SG_LOG( SG_TERRAIN, SG_INFO,
188 "scheduling needed tiles for " << longitude << " " << latitude );
190 double tile_width = curr_bucket.get_width_m();
191 double tile_height = curr_bucket.get_height_m();
192 // cout << "tile width = " << tile_width << " tile_height = "
193 // << tile_height << endl;
195 xrange = (int)(vis / tile_width) + 1;
196 yrange = (int)(vis / tile_height) + 1;
197 if ( xrange < 1 ) { xrange = 1; }
198 if ( yrange < 1 ) { yrange = 1; }
200 // make the cache twice as large to avoid losing terrain when switching
201 // between aircraft and tower views
202 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
203 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
204 // cout << "max cache size = " << tile_cache.get_max_cache_size()
205 // << " current cache size = " << tile_cache.get_size() << endl;
207 // clear flags of all tiles belonging to the previous view set
208 tile_cache.clear_current_view();
210 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
211 osg::FrameStamp* framestamp
212 = globals->get_renderer()->getViewer()->getFrameStamp();
213 tile_cache.set_current_time(framestamp->getReferenceTime());
219 /* schedule all tiles, use distance-based loading priority,
220 * so tiles are loaded in innermost-to-outermost sequence. */
221 for ( x = -xrange; x <= xrange; ++x )
223 for ( y = -yrange; y <= yrange; ++y )
225 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
226 float priority = (-1.0) * (x*x+y*y);
227 sched_tile( b, priority, true, 0.0 );
233 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
236 if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
237 string_list sc = globals->get_fg_scenery();
239 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
241 tmpPath.append(modelPath);
242 if (tmpPath.exists()) {
248 fullPath.append(modelPath);
250 osg::Node* result = 0;
254 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
255 new FGNasalModelData);
258 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
259 new FGNasalModelData);
260 } catch (const sg_io_exception& exc) {
261 string m(exc.getMessage());
263 m += exc.getLocation().asString();
264 SG_LOG( SG_ALL, SG_ALERT, m );
265 } catch (const sg_exception& exc) { // XXX may be redundant
266 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
272 * Update the various queues maintained by the tilemagr (private
273 * internal function, do not call directly.)
275 void FGTileMgr::update_queues()
277 SceneryPager* pager = FGScenery::getPagerSingleton();
278 osg::FrameStamp* framestamp
279 = globals->get_renderer()->getViewer()->getFrameStamp();
280 double current_time = framestamp->getReferenceTime();
281 double vis = _visibilityMeters->getDoubleValue();
286 tile_cache.set_current_time( current_time );
287 tile_cache.reset_traversal();
289 while ( ! tile_cache.at_end() )
291 e = tile_cache.get_current();
292 // cout << "processing a tile" << endl;
295 // Prepare the ssg nodes corresponding to each tile.
296 // Set the ssg transform and update it's range selector
297 // based on current visibilty
298 e->prep_ssg_node(vis);
300 if (( !e->is_loaded() )&&
301 ( !e->is_expired(current_time) ))
303 // schedule tile for loading with osg pager
304 pager->queueRequest(e->tileFileName,
308 e->getDatabaseRequest(),
314 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
320 int drop_count = sz - tile_cache.get_max_cache_size();
321 if (( drop_count > 0 )&&
322 ((loading==0)||(drop_count > 10)))
324 long drop_index = tile_cache.get_drop_tile();
325 while ( drop_index > -1 )
327 // schedule tile for deletion with osg pager
328 TileEntry* old = tile_cache.get_tile(drop_index);
329 tile_cache.clear_entry(drop_index);
331 osg::ref_ptr<osg::Object> subgraph = old->getNode();
332 old->removeFromSceneGraph();
334 // zeros out subgraph ref_ptr, so subgraph is owned by
335 // the pager and will be deleted in the pager thread.
336 pager->queueDeleteRequest(subgraph);
338 if (--drop_count > 0)
339 drop_index = tile_cache.get_drop_tile();
346 // given the current lon/lat (in degrees), fill in the array of local
347 // chunks. If the chunk isn't already in the cache, then read it from
349 void FGTileMgr::update(double)
351 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
352 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
353 double vis = _visibilityMeters->getDoubleValue();
354 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
359 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
360 // "schedule_scenery" instead
361 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
363 longitude = location.getLongitudeDeg();
364 latitude = location.getLatitudeDeg();
366 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
367 // << longitude << " " << latatitude );
369 current_bucket.set_bucket( location );
371 // schedule more tiles when visibility increased considerably
372 // TODO Calculate tile size - instead of using fixed value (5000m)
373 if (range_m-scheduled_visibility > 5000.0)
374 previous_bucket.make_bad();
376 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
377 // << current_bucket );
378 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
380 // do tile load scheduling.
381 // Note that we need keep track of both viewer buckets and fdm buckets.
382 if ( state == Running ) {
383 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
384 if (current_bucket != previous_bucket) {
385 // We've moved to a new bucket, we need to schedule any
386 // needed tiles for loading.
387 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
388 scheduled_visibility = range_m;
389 schedule_needed(current_bucket, range_m);
392 previous_bucket = current_bucket;
393 } else if ( state == Start || state == Inited ) {
394 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
395 // do not update bucket yet (position not valid in initial loop)
397 previous_bucket.make_bad();
403 /** Schedules scenery for given position. Load request remains valid for given duration
404 * (duration=0.0 => nothing is loaded).
405 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
406 * Returns true when all tiles for the given position are already loaded, false otherwise.
408 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
410 const float priority = 0.0;
411 double current_longitude = position.getLongitudeDeg();
412 double current_latitude = position.getLatitudeDeg();
413 bool available = true;
415 // sanity check (unfortunately needed!)
416 if (current_longitude < -180 || current_longitude > 180 ||
417 current_latitude < -90 || current_latitude > 90)
420 SGBucket bucket(position);
421 available = sched_tile( bucket, priority, false, duration );
423 if ((!available)&&(duration==0.0))
426 SGVec3d cartPos = SGVec3d::fromGeod(position);
428 // Traverse all tiles required to be there for the given visibility.
429 double tile_width = bucket.get_width_m();
430 double tile_height = bucket.get_height_m();
431 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
432 double max_dist = tile_r + range_m;
433 double max_dist2 = max_dist*max_dist;
435 int xrange = (int)fabs(range_m / tile_width) + 1;
436 int yrange = (int)fabs(range_m / tile_height) + 1;
438 for ( int x = -xrange; x <= xrange; ++x )
440 for ( int y = -yrange; y <= yrange; ++y )
442 // We have already checked for the center tile.
443 if ( x != 0 || y != 0 )
445 SGBucket b = sgBucketOffset( current_longitude,
446 current_latitude, x, y );
447 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
448 // Do not ask if it is just the next tile but way out of range.
449 if (distance2 <= max_dist2)
451 available &= sched_tile( b, priority, false, duration );
452 if ((!available)&&(duration==0.0))
462 // Returns true if tiles around current view position have been loaded
463 bool FGTileMgr::isSceneryLoaded()
465 double range_m = 100.0;
466 if (scheduled_visibility < range_m)
467 range_m = scheduled_visibility;
469 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);