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