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