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