]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Merge branch 'next' into durk-atc
[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
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>
38
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>
44
45 #include "scenery.hxx"
46 #include "SceneryPager.hxx"
47 #include "tilemgr.hxx"
48
49 using std::for_each;
50 using flightgear::SceneryPager;
51 using simgear::SGModelLib;
52 using simgear::TileEntry;
53 using simgear::TileCache;
54
55
56 // helper: listen to property changes affecting tile loading
57 class LoaderPropertyWatcher : public SGPropertyChangeListener
58 {
59 public:
60     LoaderPropertyWatcher(FGTileMgr* pTileMgr) :
61         _pTileMgr(pTileMgr)
62     {
63     }
64
65     virtual void valueChanged(SGPropertyNode*)
66     {
67         _pTileMgr->configChanged();
68     }
69
70 private:
71     FGTileMgr* _pTileMgr;
72 };
73
74
75 FGTileMgr::FGTileMgr():
76     state( Start ),
77     vis( 16000 ),
78     _propListener(new LoaderPropertyWatcher(this))
79 {
80     _randomObjects = fgGetNode("/sim/rendering/random-objects", true);
81     _randomVegetation = fgGetNode("/sim/rendering/random-vegetation", true);
82 }
83
84
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());
89     delete _propListener;
90     _propListener = NULL;
91     // clear OSG cache
92     osgDB::Registry::instance()->clearObjectCache();
93 }
94
95
96 // Initialize the Tile Manager subsystem
97 void FGTileMgr::init() {
98     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
99
100     _options = new SGReaderWriterBTGOptions;
101     _options->setMatlib(globals->get_matlib());
102
103     _randomObjects.get()->addChangeListener(_propListener, false);
104     _randomVegetation.get()->addChangeListener(_propListener, false);
105     configChanged();
106
107     osgDB::FilePathList &fp = _options->getDatabasePathList();
108     const string_list &sc = globals->get_fg_scenery();
109     fp.clear();
110     std::copy(sc.begin(), sc.end(), back_inserter(fp));
111
112     TileEntry::setModelLoadHelper(this);
113     
114     _visibilityMeters = fgGetNode("/environment/visibility-m", true);
115
116     reinit();
117 }
118
119
120 void FGTileMgr::reinit()
121 {
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());
125     tile_cache.init();
126     
127     // clear OSG cache, except on initial start-up
128     if (state != Start)
129     {
130         osgDB::Registry::instance()->clearObjectCache();
131     }
132     
133     state = Inited;
134     
135     previous_bucket.make_bad();
136     current_bucket.make_bad();
137     longitude = latitude = -1000.0;
138     
139     // force an update now
140     update(0.0);
141 }
142
143 void FGTileMgr::configChanged()
144 {
145     _options->setUseRandomObjects(_randomObjects.get()->getBoolValue());
146     _options->setUseRandomVegetation(_randomVegetation.get()->getBoolValue());
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;         // FIXME
194         SG_LOG( SG_TERRAIN, SG_ALERT,
195                 "This is a FATAL error.  Exiting!" );
196         exit(-1);
197     }
198
199     SG_LOG( SG_TERRAIN, SG_INFO,
200             "scheduling needed tiles for " << longitude << " " << latitude );
201
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;
206
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; }
211
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;
218
219     // clear flags of all tiles belonging to the previous view set 
220     tile_cache.clear_current_view();
221
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());
226
227     SGBucket b;
228
229     int x, y;
230
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 )
234     {
235         for ( y = -yrange; y <= yrange; ++y )
236         {
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 );
240         }
241     }
242 }
243
244 osg::Node*
245 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
246 {
247     SGPath fullPath;
248     if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
249         string_list sc = globals->get_fg_scenery();
250
251         for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
252             SGPath tmpPath(*it);
253             tmpPath.append(modelPath);
254             if (tmpPath.exists()) {
255                 fullPath = tmpPath;
256                 break;
257             } 
258         }
259     } else {
260          fullPath.append(modelPath);
261     }
262     osg::Node* result = 0;
263     try {
264         if(cacheModel)
265             result =
266                 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
267                                       new FGNasalModelData);
268         else
269             result=
270                 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
271                                            new FGNasalModelData);
272     } catch (const sg_io_exception& exc) {
273         string m(exc.getMessage());
274         m += " ";
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());
279     }
280     return result;
281 }
282
283 /**
284  * Update the various queues maintained by the tilemagr (private
285  * internal function, do not call directly.)
286  */
287 void FGTileMgr::update_queues()
288 {
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();
294     TileEntry *e;
295     int loading=0;
296     int sz=0;
297
298     tile_cache.set_current_time( current_time );
299     tile_cache.reset_traversal();
300
301     while ( ! tile_cache.at_end() )
302     {
303         e = tile_cache.get_current();
304         // cout << "processing a tile" << endl;
305         if ( e )
306         {
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);
311
312             if (( !e->is_loaded() )&&
313                 ( !e->is_expired(current_time) ))
314             {
315                 // schedule tile for loading with osg pager
316                 pager->queueRequest(e->tileFileName,
317                                     e->getNode(),
318                                     e->get_priority(),
319                                     framestamp,
320                                     e->getDatabaseRequest(),
321                                     _options.get());
322                 loading++;
323             }
324         } else
325         {
326             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
327         }
328         tile_cache.next();
329         sz++;
330     }
331
332     int drop_count = sz - tile_cache.get_max_cache_size();
333     if (( drop_count > 0 )&&
334          ((loading==0)||(drop_count > 10)))
335     {
336         long drop_index = tile_cache.get_drop_tile();
337         while ( drop_index > -1 )
338         {
339             // schedule tile for deletion with osg pager
340             TileEntry* old = tile_cache.get_tile(drop_index);
341             tile_cache.clear_entry(drop_index);
342             
343             osg::ref_ptr<osg::Object> subgraph = old->getNode();
344             old->removeFromSceneGraph();
345             delete old;
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);
349             
350             if (--drop_count > 0)
351                 drop_index = tile_cache.get_drop_tile();
352             else
353                 drop_index = -1;
354         }
355     }
356 }
357
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
360 // disk.
361 void FGTileMgr::update(double)
362 {
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);
367
368     update_queues();
369 }
370
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)
374 {
375     longitude = location.getLongitudeDeg();
376     latitude = location.getLatitudeDeg();
377
378     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
379     //         << longitude << " " << latatitude );
380
381     current_bucket.set_bucket( location );
382
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();
387
388     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
389     //         << current_bucket );
390     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
391
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);
402         }
403         // save bucket
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)
408         state = Running;
409         previous_bucket.make_bad();
410     }
411
412     return 1;
413 }
414
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.
419  */
420 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
421 {
422     const float priority = 0.0;
423     double current_longitude = position.getLongitudeDeg();
424     double current_latitude = position.getLatitudeDeg();
425     bool available = true;
426     
427     // sanity check (unfortunately needed!)
428     if (current_longitude < -180 || current_longitude > 180 ||
429         current_latitude < -90 || current_latitude > 90)
430         return false;
431   
432     SGBucket bucket(position);
433     available = sched_tile( bucket, priority, false, duration );
434   
435     if ((!available)&&(duration==0.0))
436         return false;
437
438     SGVec3d cartPos = SGVec3d::fromGeod(position);
439
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;
446     
447     int xrange = (int)fabs(range_m / tile_width) + 1;
448     int yrange = (int)fabs(range_m / tile_height) + 1;
449
450     for ( int x = -xrange; x <= xrange; ++x )
451     {
452         for ( int y = -yrange; y <= yrange; ++y )
453         {
454             // We have already checked for the center tile.
455             if ( x != 0 || y != 0 )
456             {
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)
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(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
482 }