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());
92 osgDB::Registry::instance()->clearObjectCache();
96 // Initialize the Tile Manager subsystem
97 void FGTileMgr::init() {
98 SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
100 _options = new SGReaderWriterBTGOptions;
101 _options->setMatlib(globals->get_matlib());
103 _randomObjects.get()->addChangeListener(_propListener, false);
104 _randomVegetation.get()->addChangeListener(_propListener, false);
107 osgDB::FilePathList &fp = _options->getDatabasePathList();
108 const string_list &sc = globals->get_fg_scenery();
110 std::copy(sc.begin(), sc.end(), back_inserter(fp));
112 TileEntry::setModelLoadHelper(this);
114 _visibilityMeters = fgGetNode("/environment/visibility-m", true);
120 void FGTileMgr::reinit()
122 // remove all old scenery nodes from scenegraph and clear cache
123 osg::Group* group = globals->get_scenery()->get_terrain_branch();
124 group->removeChildren(0, group->getNumChildren());
127 // clear OSG cache, except on initial start-up
130 osgDB::Registry::instance()->clearObjectCache();
135 previous_bucket.make_bad();
136 current_bucket.make_bad();
137 longitude = latitude = -1000.0;
139 // force an update now
143 void FGTileMgr::configChanged()
145 _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
146 _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
149 /* schedule a tile for loading, keep request for given amount of time.
150 * Returns true if tile is already loaded. */
151 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
153 // see if tile already exists in the cache
154 TileEntry *t = tile_cache.get_tile( b );
157 // create a new entry
158 t = new TileEntry( b );
159 // insert the tile into the cache, update will generate load request
160 if ( tile_cache.insert_tile( t ) )
162 // Attach to scene graph
164 t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
167 // insert failed (cache full with no available entries to
168 // delete.) Try again later
173 SG_LOG( SG_TERRAIN, SG_DEBUG, " New tile cache size " << (int)tile_cache.get_size() );
176 // update tile's properties
177 tile_cache.request_tile(t,priority,current_view,duration);
179 return t->is_loaded();
182 /* schedule needed buckets for the current view position for loading,
183 * keep request for given amount of time */
184 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
186 // sanity check (unfortunately needed!)
187 if ( longitude < -180.0 || longitude > 180.0
188 || latitude < -90.0 || latitude > 90.0 )
190 SG_LOG( SG_TERRAIN, SG_ALERT,
191 "Attempting to schedule tiles for bogus lon and lat = ("
192 << longitude << "," << latitude << ")" );
194 SG_LOG( SG_TERRAIN, SG_ALERT,
195 "This is a FATAL error. Exiting!" );
199 SG_LOG( SG_TERRAIN, SG_INFO,
200 "scheduling needed tiles for " << longitude << " " << latitude );
202 double tile_width = curr_bucket.get_width_m();
203 double tile_height = curr_bucket.get_height_m();
204 // cout << "tile width = " << tile_width << " tile_height = "
205 // << tile_height << endl;
207 xrange = (int)(vis / tile_width) + 1;
208 yrange = (int)(vis / tile_height) + 1;
209 if ( xrange < 1 ) { xrange = 1; }
210 if ( yrange < 1 ) { yrange = 1; }
212 // make the cache twice as large to avoid losing terrain when switching
213 // between aircraft and tower views
214 tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
215 // cout << "xrange = " << xrange << " yrange = " << yrange << endl;
216 // cout << "max cache size = " << tile_cache.get_max_cache_size()
217 // << " current cache size = " << tile_cache.get_size() << endl;
219 // clear flags of all tiles belonging to the previous view set
220 tile_cache.clear_current_view();
222 // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
223 osg::FrameStamp* framestamp
224 = globals->get_renderer()->getViewer()->getFrameStamp();
225 tile_cache.set_current_time(framestamp->getReferenceTime());
231 /* schedule all tiles, use distance-based loading priority,
232 * so tiles are loaded in innermost-to-outermost sequence. */
233 for ( x = -xrange; x <= xrange; ++x )
235 for ( y = -yrange; y <= yrange; ++y )
237 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
238 float priority = (-1.0) * (x*x+y*y);
239 sched_tile( b, priority, true, 0.0 );
245 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
248 if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
249 string_list sc = globals->get_fg_scenery();
251 for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
253 tmpPath.append(modelPath);
254 if (tmpPath.exists()) {
260 fullPath.append(modelPath);
262 osg::Node* result = 0;
266 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
267 new FGNasalModelData);
270 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
271 new FGNasalModelData);
272 } catch (const sg_io_exception& exc) {
273 string m(exc.getMessage());
275 m += exc.getLocation().asString();
276 SG_LOG( SG_ALL, SG_ALERT, m );
277 } catch (const sg_exception& exc) { // XXX may be redundant
278 SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
284 * Update the various queues maintained by the tilemagr (private
285 * internal function, do not call directly.)
287 void FGTileMgr::update_queues()
289 SceneryPager* pager = FGScenery::getPagerSingleton();
290 osg::FrameStamp* framestamp
291 = globals->get_renderer()->getViewer()->getFrameStamp();
292 double current_time = framestamp->getReferenceTime();
293 double vis = _visibilityMeters->getDoubleValue();
298 tile_cache.set_current_time( current_time );
299 tile_cache.reset_traversal();
301 while ( ! tile_cache.at_end() )
303 e = tile_cache.get_current();
304 // cout << "processing a tile" << endl;
307 // Prepare the ssg nodes corresponding to each tile.
308 // Set the ssg transform and update it's range selector
309 // based on current visibilty
310 e->prep_ssg_node(vis);
312 if (( !e->is_loaded() )&&
313 ( !e->is_expired(current_time) ))
315 // schedule tile for loading with osg pager
316 pager->queueRequest(e->tileFileName,
320 e->getDatabaseRequest(),
326 SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
332 int drop_count = sz - tile_cache.get_max_cache_size();
333 if (( drop_count > 0 )&&
334 ((loading==0)||(drop_count > 10)))
336 long drop_index = tile_cache.get_drop_tile();
337 while ( drop_index > -1 )
339 // schedule tile for deletion with osg pager
340 TileEntry* old = tile_cache.get_tile(drop_index);
341 tile_cache.clear_entry(drop_index);
343 osg::ref_ptr<osg::Object> subgraph = old->getNode();
344 old->removeFromSceneGraph();
346 // zeros out subgraph ref_ptr, so subgraph is owned by
347 // the pager and will be deleted in the pager thread.
348 pager->queueDeleteRequest(subgraph);
350 if (--drop_count > 0)
351 drop_index = tile_cache.get_drop_tile();
358 // given the current lon/lat (in degrees), fill in the array of local
359 // chunks. If the chunk isn't already in the cache, then read it from
361 void FGTileMgr::update(double)
363 SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
364 SGVec3d viewPos = globals->get_current_view()->get_view_pos();
365 double vis = _visibilityMeters->getDoubleValue();
366 schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
371 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
372 // "schedule_scenery" instead
373 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
375 longitude = location.getLongitudeDeg();
376 latitude = location.getLatitudeDeg();
378 // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
379 // << longitude << " " << latatitude );
381 current_bucket.set_bucket( location );
383 // schedule more tiles when visibility increased considerably
384 // TODO Calculate tile size - instead of using fixed value (5000m)
385 if (range_m-scheduled_visibility > 5000.0)
386 previous_bucket.make_bad();
388 // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
389 // << current_bucket );
390 fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
392 // do tile load scheduling.
393 // Note that we need keep track of both viewer buckets and fdm buckets.
394 if ( state == Running ) {
395 SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
396 if (current_bucket != previous_bucket) {
397 // We've moved to a new bucket, we need to schedule any
398 // needed tiles for loading.
399 SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
400 scheduled_visibility = range_m;
401 schedule_needed(current_bucket, range_m);
404 previous_bucket = current_bucket;
405 } else if ( state == Start || state == Inited ) {
406 SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
407 // do not update bucket yet (position not valid in initial loop)
409 previous_bucket.make_bad();
415 /** Schedules scenery for given position. Load request remains valid for given duration
416 * (duration=0.0 => nothing is loaded).
417 * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
418 * Returns true when all tiles for the given position are already loaded, false otherwise.
420 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
422 const float priority = 0.0;
423 double current_longitude = position.getLongitudeDeg();
424 double current_latitude = position.getLatitudeDeg();
425 bool available = true;
427 // sanity check (unfortunately needed!)
428 if (current_longitude < -180 || current_longitude > 180 ||
429 current_latitude < -90 || current_latitude > 90)
432 SGBucket bucket(position);
433 available = sched_tile( bucket, priority, false, duration );
435 if ((!available)&&(duration==0.0))
438 SGVec3d cartPos = SGVec3d::fromGeod(position);
440 // Traverse all tiles required to be there for the given visibility.
441 double tile_width = bucket.get_width_m();
442 double tile_height = bucket.get_height_m();
443 double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
444 double max_dist = tile_r + range_m;
445 double max_dist2 = max_dist*max_dist;
447 int xrange = (int)fabs(range_m / tile_width) + 1;
448 int yrange = (int)fabs(range_m / tile_height) + 1;
450 for ( int x = -xrange; x <= xrange; ++x )
452 for ( int y = -yrange; y <= yrange; ++y )
454 // We have already checked for the center tile.
455 if ( x != 0 || y != 0 )
457 SGBucket b = sgBucketOffset( current_longitude,
458 current_latitude, x, y );
459 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
460 // Do not ask if it is just the next tile but way out of range.
461 if (distance2 <= max_dist2)
463 available &= sched_tile( b, priority, false, duration );
464 if ((!available)&&(duration==0.0))
474 // Returns true if tiles around current view position have been loaded
475 bool FGTileMgr::isSceneryLoaded()
477 double range_m = 100.0;
478 if (scheduled_visibility < range_m)
479 range_m = scheduled_visibility;
481 return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);