]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Respect tile expiry time when cache is disabled.
[flightgear.git] / src / Scenery / tilemgr.cxx
1 // tilemgr.cxx -- routines to handle dynamic management of scenery tiles
2 //
3 // Written by Curtis Olson, started January 1998.
4 //
5 // Copyright (C) 1997  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
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.
11 //
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.
16 //
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.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <algorithm>
29 #include <functional>
30
31 #include <osgViewer/Viewer>
32 #include <osgDB/Registry>
33
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>
40 #include <simgear/misc/strutils.hxx>
41 #include <simgear/scene/material/matlib.hxx>
42
43 #include <Main/globals.hxx>
44 #include <Main/fg_props.hxx>
45 #include <Viewer/renderer.hxx>
46 #include <Viewer/splash.hxx>
47 #include <Scripting/NasalSys.hxx>
48 #include <Scripting/NasalModelData.hxx>
49
50 #include "scenery.hxx"
51 #include "SceneryPager.hxx"
52 #include "tilemgr.hxx"
53
54 using flightgear::SceneryPager;
55
56 class FGTileMgr::TileManagerListener : public SGPropertyChangeListener
57 {
58 public:
59     TileManagerListener(FGTileMgr* manager) :
60         _manager(manager),
61         _useVBOsProp(fgGetNode("/sim/rendering/use-vbos", true)),
62         _enableCacheProp(fgGetNode("/sim/tile-cache/enable", true)),
63         _pagedLODMaximumProp(fgGetNode("/sim/rendering/max-paged-lod", true))
64     {
65         _useVBOsProp->addChangeListener(this, true);
66       
67         _enableCacheProp->addChangeListener(this, true);
68         if (_enableCacheProp->getType() == simgear::props::NONE) {
69             _enableCacheProp->setBoolValue(true);
70         }
71       
72         if (_pagedLODMaximumProp->getType() == simgear::props::NONE) {
73             // not set, use OSG default / environment value variable
74             osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
75             int current = viewer->getDatabasePager()->getTargetMaximumNumberOfPageLOD();
76             _pagedLODMaximumProp->setIntValue(current);
77         }
78         _pagedLODMaximumProp->addChangeListener(this, true);
79     }
80     
81     ~TileManagerListener()
82     {
83         _useVBOsProp->removeChangeListener(this);
84         _enableCacheProp->removeChangeListener(this);
85         _pagedLODMaximumProp->removeChangeListener(this);
86     }
87     
88     virtual void valueChanged(SGPropertyNode* prop)
89     {
90         if (prop == _useVBOsProp) {
91             bool useVBOs = prop->getBoolValue();
92             _manager->_options->setPluginStringData("SimGear::USE_VBOS",
93                                                 useVBOs ? "ON" : "OFF");
94         } else if (prop == _enableCacheProp) {
95             _manager->_enableCache = prop->getBoolValue();
96         } else if (prop == _pagedLODMaximumProp) {
97           int v = prop->getIntValue();
98           osg::ref_ptr<osgViewer::Viewer> viewer(globals->get_renderer()->getViewer());
99           viewer->getDatabasePager()->setTargetMaximumNumberOfPageLOD(v);
100         }
101     }
102     
103 private:
104     FGTileMgr* _manager;
105     SGPropertyNode_ptr _useVBOsProp,
106       _enableCacheProp,
107       _pagedLODMaximumProp;
108 };
109
110 FGTileMgr::FGTileMgr():
111     state( Start ),
112     last_state( Running ),
113     scheduled_visibility(100.0),
114     _terra_sync(NULL),
115     _listener(NULL),
116     _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
117     _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
118     _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
119     _scenery_loaded(fgGetNode("/sim/sceneryloaded", true)),
120     _scenery_override(fgGetNode("/sim/sceneryloaded-override", true)),
121     _pager(FGScenery::getPagerSingleton()),
122     _enableCache(true)
123 {
124 }
125
126
127 FGTileMgr::~FGTileMgr()
128 {
129     delete _listener;
130     
131     // remove all nodes we might have left behind
132     osg::Group* group = globals->get_scenery()->get_terrain_branch();
133     group->removeChildren(0, group->getNumChildren());
134     // clear OSG cache
135     osgDB::Registry::instance()->clearObjectCache();
136 }
137
138
139 // Initialize the Tile Manager subsystem
140 void FGTileMgr::init() {
141     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
142
143     _options = new simgear::SGReaderWriterOptions;
144     _listener = new TileManagerListener(this);
145     
146     materialLibChanged();
147     _options->setPropertyNode(globals->get_props());
148
149     osgDB::FilePathList &fp = _options->getDatabasePathList();
150     const string_list &sc = globals->get_fg_scenery();
151     fp.clear();
152     std::copy(sc.begin(), sc.end(), back_inserter(fp));
153     _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
154     
155     if (globals->get_subsystem("terrasync")) {
156         _options->setPluginStringData("SimGear::TERRASYNC_ROOT", fgGetString("/sim/terrasync/scenery-dir"));
157     }
158     
159     if (!_disableNasalHooks->getBoolValue())
160         _options->setModelData(new FGNasalModelDataProxy);
161
162     reinit();
163 }
164
165 void FGTileMgr::reinit()
166 {
167     _terra_sync = static_cast<simgear::SGTerraSync*> (globals->get_subsystem("terrasync"));
168     
169     // protect against multiple scenery reloads and properly reset flags,
170     // otherwise aircraft fall through the ground while reloading scenery
171     if (!fgGetBool("/sim/sceneryloaded",true))
172         return;
173     fgSetBool("/sim/sceneryloaded",false);
174     fgSetDouble("/sim/startup/splash-alpha", 1.0);
175     
176     materialLibChanged();
177
178     // remove all old scenery nodes from scenegraph and clear cache
179     osg::Group* group = globals->get_scenery()->get_terrain_branch();
180     group->removeChildren(0, group->getNumChildren());
181     tile_cache.init();
182     
183     // clear OSG cache, except on initial start-up
184     if (state != Start)
185     {
186         osgDB::Registry::instance()->clearObjectCache();
187     }
188     
189     state = Inited;
190     
191     previous_bucket.make_bad();
192     current_bucket.make_bad();
193     scheduled_visibility = 100.0;
194
195     // force an update now
196     update(0.0);
197 }
198
199 void FGTileMgr::materialLibChanged()
200 {
201     _options->setMaterialLib(globals->get_matlib());
202     _options->getMaterialLib()->refreshActiveMaterials();
203 }
204
205 /* schedule a tile for loading, keep request for given amount of time.
206  * Returns true if tile is already loaded. */
207 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
208 {
209     // see if tile already exists in the cache
210     TileEntry *t = tile_cache.get_tile( b );
211     if (!t)
212     {
213         // create a new entry
214         t = new TileEntry( b );
215         // insert the tile into the cache, update will generate load request
216         if ( tile_cache.insert_tile( t ) )
217         {
218             // Attach to scene graph
219
220             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
221         } else
222         {
223             // insert failed (cache full with no available entries to
224             // delete.)  Try again later
225             delete t;
226             return false;
227         }
228
229         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
230     }
231
232     // update tile's properties
233     tile_cache.request_tile(t,priority,current_view,duration);
234
235     return t->is_loaded();
236 }
237
238 /* schedule needed buckets for the current view position for loading,
239  * keep request for given amount of time */
240 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
241 {
242     // sanity check (unfortunately needed!)
243     if (!curr_bucket.isValid() )
244     {
245         SG_LOG( SG_TERRAIN, SG_ALERT,
246                 "Attempting to schedule tiles for invalid bucket" );
247         return;
248     }
249
250     double tile_width = curr_bucket.get_width_m();
251     double tile_height = curr_bucket.get_height_m();
252     SG_LOG( SG_TERRAIN, SG_INFO,
253             "scheduling needed tiles for " << curr_bucket
254            << ", tile-width-m:" << tile_width << ", tile-height-m:" << tile_height);
255
256     
257     // cout << "tile width = " << tile_width << "  tile_height = "
258     //      << tile_height << endl;
259
260     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
261     int xrange = (int)(tileRangeM / tile_width) + 1;
262     int yrange = (int)(tileRangeM / tile_height) + 1;
263     if ( xrange < 1 ) { xrange = 1; }
264     if ( yrange < 1 ) { yrange = 1; }
265
266     // make the cache twice as large to avoid losing terrain when switching
267     // between aircraft and tower views
268     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
269     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
270     // cout << "max cache size = " << tile_cache.get_max_cache_size()
271     //      << " current cache size = " << tile_cache.get_size() << endl;
272
273     // clear flags of all tiles belonging to the previous view set 
274     tile_cache.clear_current_view();
275
276     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
277     osg::FrameStamp* framestamp
278             = globals->get_renderer()->getViewer()->getFrameStamp();
279     tile_cache.set_current_time(framestamp->getReferenceTime());
280
281     SGBucket b;
282
283     int x, y;
284
285     /* schedule all tiles, use distance-based loading priority,
286      * so tiles are loaded in innermost-to-outermost sequence. */
287     for ( x = -xrange; x <= xrange; ++x )
288     {
289         for ( y = -yrange; y <= yrange; ++y )
290         {
291             SGBucket b = curr_bucket.sibling(x, y);
292             if (!b.isValid()) {
293                 continue;
294             }
295             
296             float priority = (-1.0) * (x*x+y*y);
297             sched_tile( b, priority, true, 0.0 );
298             
299             if (_terra_sync) {
300                 _terra_sync->scheduleTile(b);
301             }
302         }
303     }
304 }
305
306 /**
307  * Update the various queues maintained by the tilemagr (private
308  * internal function, do not call directly.)
309  */
310 void FGTileMgr::update_queues(bool& isDownloadingScenery)
311 {
312     osg::FrameStamp* framestamp
313         = globals->get_renderer()->getViewer()->getFrameStamp();
314     double current_time = framestamp->getReferenceTime();
315     double vis = _visibilityMeters->getDoubleValue();
316     TileEntry *e;
317     int loading=0;
318     int sz=0;
319     bool didRefreshMaterialCache = false;
320     
321     tile_cache.set_current_time( current_time );
322     tile_cache.reset_traversal();
323
324     while ( ! tile_cache.at_end() )
325     {
326         e = tile_cache.get_current();
327         if ( e )
328         {
329             // Prepare the ssg nodes corresponding to each tile.
330             // Set the ssg transform and update it's range selector
331             // based on current visibilty
332             e->prep_ssg_node(vis);
333             
334             if (!e->is_loaded()) {
335                 if (!didRefreshMaterialCache) {
336                     didRefreshMaterialCache = true;
337                     globals->get_matlib()->refreshActiveMaterials();
338                 }
339                 
340                 bool nonExpiredOrCurrent = !e->is_expired(current_time) || e->is_current_view();
341                 bool downloading = isTileDirSyncing(e->tileFileName);
342                 isDownloadingScenery |= downloading;
343                 if ( !downloading && nonExpiredOrCurrent) {
344                     // schedule tile for loading with osg pager
345                     _pager->queueRequest(e->tileFileName,
346                                          e->getNode(),
347                                          e->get_priority(),
348                                          framestamp,
349                                          e->getDatabaseRequest(),
350                                          _options.get());
351                     loading++;
352                 }
353             } // of tile not loaded case
354         } else {
355             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
356         }
357         tile_cache.next();
358         sz++;
359     }
360
361     int drop_count = sz - tile_cache.get_max_cache_size();
362     bool dropTiles = false;
363     if (_enableCache) {
364       dropTiles = ( drop_count > 0 ) && ((loading==0)||(drop_count > 10));
365     } else {
366       dropTiles = true;
367       drop_count = sz; // no limit on tiles to drop
368     }
369   
370     if (dropTiles)
371     {
372         long drop_index = _enableCache ? tile_cache.get_drop_tile() :
373                                          tile_cache.get_first_expired_tile();
374         while ( drop_index > -1 )
375         {
376             // schedule tile for deletion with osg pager
377             TileEntry* old = tile_cache.get_tile(drop_index);
378             SG_LOG(SG_TERRAIN, SG_DEBUG, "Dropping:" << old->get_tile_bucket());
379
380             tile_cache.clear_entry(drop_index);
381             
382             osg::ref_ptr<osg::Object> subgraph = old->getNode();
383             old->removeFromSceneGraph();
384             delete old;
385             // zeros out subgraph ref_ptr, so subgraph is owned by
386             // the pager and will be deleted in the pager thread.
387             _pager->queueDeleteRequest(subgraph);
388           
389             if (!_enableCache)
390                 drop_index = tile_cache.get_first_expired_tile();
391             // limit tiles dropped to drop_count
392             else if (--drop_count > 0)
393                 drop_index = tile_cache.get_drop_tile();
394             else
395                drop_index = -1;
396         }
397     } // of dropping tiles loop
398 }
399
400 // given the current lon/lat (in degrees), fill in the array of local
401 // chunks.  If the chunk isn't already in the cache, then read it from
402 // disk.
403 void FGTileMgr::update(double)
404 {
405     double vis = _visibilityMeters->getDoubleValue();
406     schedule_tiles_at(globals->get_view_position(), vis);
407
408     bool waitingOnTerrasync = false;
409     update_queues(waitingOnTerrasync);
410
411     // scenery loading check, triggers after each sim (tile manager) reinit
412     if (!_scenery_loaded->getBoolValue())
413     {
414         bool fdmInited = fgGetBool("sim/fdm-initialized");
415         bool positionFinalized = fgGetBool("sim/position-finalized");
416         bool sceneryOverride = _scenery_override->getBoolValue();
417         
418         
419     // we are done if final position is set and the scenery & FDM are done.
420     // scenery-override can ignore the last two, but not position finalization.
421         if (positionFinalized && (sceneryOverride || (isSceneryLoaded() && fdmInited)))
422         {
423             _scenery_loaded->setBoolValue(true);
424             fgSplashProgress("");
425         }
426         else
427         {
428             if (!positionFinalized) {
429                 fgSplashProgress("finalize-position");
430             } else if (waitingOnTerrasync) {
431                 fgSplashProgress("downloading-scenery");
432             } else {
433                 fgSplashProgress("loading-scenery");
434             }
435             
436             // be nice to loader threads while waiting for initial scenery, reduce to 20fps
437             SGTimeStamp::sleepForMSec(50);
438         }
439     }
440 }
441
442 // schedule tiles for the viewer bucket
443 // (FDM/AI/groundcache/... should use "schedule_scenery" instead)
444 void FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
445 {
446     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
447     //         << longitude << " " << latitude );
448
449     current_bucket = SGBucket( location );
450
451     // schedule more tiles when visibility increased considerably
452     // TODO Calculate tile size - instead of using fixed value (5000m)
453     if (range_m - scheduled_visibility > 5000.0)
454         previous_bucket.make_bad();
455
456     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
457     //         << current_bucket );
458     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
459
460     // do tile load scheduling.
461     // Note that we need keep track of both viewer buckets and fdm buckets.
462     if ( state == Running ) {
463         if (last_state != state)
464         {
465             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
466         }
467         if (current_bucket != previous_bucket) {
468             // We've moved to a new bucket, we need to schedule any
469             // needed tiles for loading.
470             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr: at " << location << ", scheduling needed for:" << current_bucket
471                    << ", visbility=" << range_m);
472             scheduled_visibility = range_m;
473             schedule_needed(current_bucket, range_m);
474         }
475         
476         // save bucket
477         previous_bucket = current_bucket;
478     } else if ( state == Start || state == Inited ) {
479         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
480         // do not update bucket yet (position not valid in initial loop)
481         state = Running;
482         previous_bucket.make_bad();
483     }
484     last_state = state;
485 }
486
487 /** Schedules scenery for given position. Load request remains valid for given duration
488  * (duration=0.0 => nothing is loaded).
489  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
490  * Returns true when all tiles for the given position are already loaded, false otherwise.
491  */
492 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
493 {
494     // sanity check (unfortunately needed!)
495     if (!position.isValid())
496         return false;
497     const float priority = 0.0;
498     bool available = true;
499
500     SGBucket bucket(position);
501     available = sched_tile( bucket, priority, false, duration );
502   
503     if ((!available)&&(duration==0.0))
504         return false;
505
506     SGVec3d cartPos = SGVec3d::fromGeod(position);
507
508     // Traverse all tiles required to be there for the given visibility.
509     double tile_width = bucket.get_width_m();
510     double tile_height = bucket.get_height_m();
511     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
512     double max_dist = tile_r + range_m;
513     double max_dist2 = max_dist*max_dist;
514     
515     int xrange = (int)fabs(range_m / tile_width) + 1;
516     int yrange = (int)fabs(range_m / tile_height) + 1;
517
518     for ( int x = -xrange; x <= xrange; ++x )
519     {
520         for ( int y = -yrange; y <= yrange; ++y )
521         {
522             // We have already checked for the center tile.
523             if ( x != 0 || y != 0 )
524             {
525                 SGBucket b = bucket.sibling(x, y );
526                 if (!b.isValid()) {
527                     continue;
528                 }
529                 
530                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
531                 // Do not ask if it is just the next tile but way out of range.
532                 if (distance2 <= max_dist2)
533                 {
534                     available &= sched_tile( b, priority, false, duration );
535                     if ((!available)&&(duration==0.0))
536                         return false;
537                 }
538             }
539         }
540     }
541
542     return available;
543 }
544
545 // Returns true if tiles around current view position have been loaded
546 bool FGTileMgr::isSceneryLoaded()
547 {
548     double range_m = 100.0;
549     if (scheduled_visibility < range_m)
550         range_m = scheduled_visibility;
551
552     return schedule_scenery(globals->get_view_position(), range_m, 0.0);
553 }
554
555 bool FGTileMgr::isTileDirSyncing(const std::string& tileFileName) const
556 {
557     if (!_terra_sync) {
558         return false;
559     }
560     
561     std::string nameWithoutExtension = tileFileName.substr(0, tileFileName.size() - 4);
562     long int bucketIndex = simgear::strutils::to_int(nameWithoutExtension);
563     SGBucket bucket(bucketIndex);
564     
565     return _terra_sync->isTileDirPending(bucket.gen_base_path());
566 }
567