]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Merge branch 'jmt/gps'
[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/math/vector.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/tgdb/SGReaderWriterBTGOptions.hxx>
39
40 #include <Main/globals.hxx>
41 #include <Main/fg_props.hxx>
42 #include <Main/renderer.hxx>
43 #include <Main/viewer.hxx>
44 #include <Scripting/NasalSys.hxx>
45
46 #include "scenery.hxx"
47 #include "SceneryPager.hxx"
48 #include "tilemgr.hxx"
49
50 using std::for_each;
51 using flightgear::SceneryPager;
52 using simgear::SGModelLib;
53 using simgear::TileEntry;
54 using simgear::TileCache;
55
56 FGTileMgr::FGTileMgr():
57     state( Start ),
58     vis( 16000 )
59 {
60 }
61
62
63 FGTileMgr::~FGTileMgr() {
64     // remove all nodes we might have left behind
65     osg::Group* group = globals->get_scenery()->get_terrain_branch();
66     group->removeChildren(0, group->getNumChildren());
67 }
68
69
70 // Initialize the Tile Manager subsystem
71 int FGTileMgr::init() {
72     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
73
74     _options = new SGReaderWriterBTGOptions;
75     _options->setMatlib(globals->get_matlib());
76     _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
77     _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
78     osgDB::FilePathList &fp = _options->getDatabasePathList();
79     const string_list &sc = globals->get_fg_scenery();
80     fp.clear();
81     std::copy(sc.begin(), sc.end(), back_inserter(fp));
82
83     TileEntry::setModelLoadHelper(this);
84
85     tile_cache.init();
86
87     state = Inited;
88
89     previous_bucket.make_bad();
90     current_bucket.make_bad();
91
92     longitude = latitude = -1000.0;
93
94     return 1;
95 }
96
97 // schedule a tile for loading
98 void FGTileMgr::sched_tile( const SGBucket& b, const bool is_inner_ring ) {
99     // see if tile already exists in the cache
100     TileEntry *t = tile_cache.get_tile( b );
101
102     if ( !t ) {
103         // make space in the cache
104         SceneryPager* pager = FGScenery::getPagerSingleton();
105         while ( (int)tile_cache.get_size() > tile_cache.get_max_cache_size() ) {
106             long index = tile_cache.get_oldest_tile();
107             if ( index >= 0 ) {
108                 TileEntry *old = tile_cache.get_tile( index );
109                 tile_cache.clear_entry( index );
110                 osg::ref_ptr<osg::Object> subgraph = old->getNode();
111                 old->removeFromSceneGraph();
112                 delete old;
113                 // zeros out subgraph ref_ptr, so subgraph is owned by
114                 // the pager and will be deleted in the pager thread.
115                 pager->queueDeleteRequest(subgraph);
116             } else {
117                 // nothing to free ?!? forge ahead
118                 break;
119             }
120         }
121
122         // create a new entry
123         TileEntry *e = new TileEntry( b );
124
125         // insert the tile into the cache
126         if ( tile_cache.insert_tile( e ) ) {
127             // update_queues will generate load request
128         } else {
129             // insert failed (cache full with no available entries to
130             // delete.)  Try again later
131             delete e;
132         }
133         // Attach to scene graph
134         e->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
135     } else {
136         t->set_inner_ring( is_inner_ring );
137     }
138 }
139
140
141 // schedule a needed buckets for loading
142 void FGTileMgr::schedule_needed( double vis, const SGBucket& curr_bucket) {
143     // sanity check (unfortunately needed!)
144     if ( longitude < -180.0 || longitude > 180.0 
145          || latitude < -90.0 || latitude > 90.0 )
146     {
147         SG_LOG( SG_TERRAIN, SG_ALERT,
148                 "Attempting to schedule tiles for bogus lon and lat  = ("
149                 << longitude << "," << latitude << ")" );
150         return;         // FIXME
151         SG_LOG( SG_TERRAIN, SG_ALERT,
152                 "This is a FATAL error.  Exiting!" );
153         exit(-1);
154     }
155
156     SG_LOG( SG_TERRAIN, SG_INFO,
157             "scheduling needed tiles for " << longitude << " " << latitude );
158
159     // vis = fgGetDouble("/environment/visibility-m");
160
161     double tile_width = curr_bucket.get_width_m();
162     double tile_height = curr_bucket.get_height_m();
163     // cout << "tile width = " << tile_width << "  tile_height = "
164     //      << tile_height << endl;
165
166     xrange = (int)(vis / tile_width) + 1;
167     yrange = (int)(vis / tile_height) + 1;
168     if ( xrange < 1 ) { xrange = 1; }
169     if ( yrange < 1 ) { yrange = 1; }
170
171     // make the cache twice as large to avoid losing terrain when switching
172     // between aircraft and tower views
173     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
174     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
175     // cout << "max cache size = " << tile_cache.get_max_cache_size()
176     //      << " current cache size = " << tile_cache.get_size() << endl;
177
178     // clear the inner ring flags so we can set them below.  This
179     // prevents us from having "true" entries we aren't able to find
180     // to get rid of if we teleport a long ways away from the current
181     // location.
182     tile_cache.clear_inner_ring_flags();
183
184     SGBucket b;
185
186     // schedule center tile first so it can be loaded first
187     b = sgBucketOffset( longitude, latitude, 0, 0 );
188     sched_tile( b, true );
189
190     int x, y;
191
192     // schedule next ring of 8 tiles
193     for ( x = -1; x <= 1; ++x ) {
194         for ( y = -1; y <= 1; ++y ) {
195             if ( x != 0 || y != 0 ) {
196                 b = sgBucketOffset( longitude, latitude, x, y );
197                 sched_tile( b, true );
198             }
199         }
200     }
201
202     // schedule remaining tiles
203     for ( x = -xrange; x <= xrange; ++x ) {
204         for ( y = -yrange; y <= yrange; ++y ) {
205             if ( x < -1 || x > 1 || y < -1 || y > 1 ) {
206                 SGBucket b = sgBucketOffset( longitude, latitude, x, y );
207                 sched_tile( b, false );
208             }
209         }
210     }
211 }
212
213
214 void FGTileMgr::initialize_queue()
215 {
216     // First time through or we have teleported, initialize the
217     // system and load all relavant tiles
218
219     SG_LOG( SG_TERRAIN, SG_INFO, "Initialize_queue(): Updating Tile list for "
220             << current_bucket );
221     // cout << "tile cache size = " << tile_cache.get_size() << endl;
222
223     // wipe/initialize tile cache
224     // tile_cache.init();
225     previous_bucket.make_bad();
226
227     // build the local area list and schedule tiles for loading
228
229     // start with the center tile and work out in concentric
230     // "rings"
231
232     double visibility_meters = fgGetDouble("/environment/visibility-m");
233     schedule_needed(visibility_meters, current_bucket);
234 }
235
236 osg::Node*
237 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
238 {
239     SGPath fullPath;
240     if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
241         string_list sc = globals->get_fg_scenery();
242
243         for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
244             SGPath tmpPath(*it);
245             tmpPath.append(modelPath);
246             if (tmpPath.exists()) {
247                 fullPath = tmpPath;
248                 break;
249             } 
250         }
251     } else {
252          fullPath.append(modelPath);
253     }
254     osg::Node* result = 0;
255     try {
256         if(cacheModel)
257             result =
258                 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
259                                       new FGNasalModelData);
260         else
261             result=
262                 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
263                                            new FGNasalModelData);
264     } catch (const sg_io_exception& exc) {
265         string m(exc.getMessage());
266         m += " ";
267         m += exc.getLocation().asString();
268         SG_LOG( SG_ALL, SG_ALERT, m );
269     } catch (const sg_exception& exc) { // XXX may be redundant
270         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
271     }
272     return result;
273 }
274
275 // Helper class for STL fun
276 class TileLoad : public std::unary_function<TileCache::tile_map::value_type,
277                                             void>
278 {
279 public:
280     TileLoad(SceneryPager *pager, osg::FrameStamp* framestamp,
281              osg::Group* terrainBranch, osgDB::ReaderWriter::Options* options) :
282         _pager(pager), _framestamp(framestamp), _options(options) {}
283
284     TileLoad(const TileLoad& rhs) :
285         _pager(rhs._pager), _framestamp(rhs._framestamp),
286         _options(rhs._options) {}
287
288     void operator()(TileCache::tile_map::value_type& tilePair)
289     {
290         TileEntry* entry = tilePair.second;
291         if (entry->getNode()->getNumChildren() == 0) {
292             _pager->queueRequest(entry->tileFileName,
293                                  entry->getNode(),
294                                  entry->get_inner_ring() ? 10.0f : 1.0f,
295                                  _framestamp,
296                                  entry->getDatabaseRequest(),
297                                  _options);
298         }
299     }
300 private:
301     SceneryPager* _pager;
302     osg::FrameStamp* _framestamp;
303     osgDB::ReaderWriter::Options* _options;
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()
311 {
312     SceneryPager* pager = FGScenery::getPagerSingleton();
313     osg::FrameStamp* framestamp
314         = globals->get_renderer()->getViewer()->getFrameStamp();
315     tile_cache.set_current_time(framestamp->getReferenceTime());
316     for_each(tile_cache.begin(), tile_cache.end(),
317              TileLoad(pager,
318                       framestamp,
319                       globals->get_scenery()->get_terrain_branch(), _options.get()));
320 }
321
322
323 // given the current lon/lat (in degrees), fill in the array of local
324 // chunks.  If the chunk isn't already in the cache, then read it from
325 // disk.
326 int FGTileMgr::update( double visibility_meters )
327 {
328     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
329     return update(SGGeod::fromCart(viewPos), visibility_meters);
330 }
331
332 int FGTileMgr::update( const SGGeod& location, double visibility_meters)
333 {
334     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
335
336     longitude = location.getLongitudeDeg();
337     latitude = location.getLatitudeDeg();
338
339     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
340     //         << longitude << " " << latatitude );
341
342     current_bucket.set_bucket( location );
343     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
344     //         << current_bucket );
345     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
346
347     // do tile load scheduling. 
348     // Note that we need keep track of both viewer buckets and fdm buckets.
349     if ( state == Running ) {
350         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
351         if (current_bucket != previous_bucket) {
352             // We've moved to a new bucket, we need to schedule any
353             // needed tiles for loading.
354             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
355             schedule_needed(visibility_meters, current_bucket);
356         }
357     } else if ( state == Start || state == Inited ) {
358         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
359 //        initialize_queue();
360         state = Running;
361         if (current_bucket != previous_bucket
362             && current_bucket.get_chunk_lon() != -1000) {
363                SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
364                schedule_needed(visibility_meters, current_bucket);
365         }
366     }
367
368     update_queues();
369
370     // save bucket...
371     previous_bucket = current_bucket;
372
373     return 1;
374 }
375
376 void FGTileMgr::prep_ssg_nodes(float vis) {
377
378     // traverse the potentially viewable tile list and update range
379     // selector and transform
380
381     TileEntry *e;
382     tile_cache.reset_traversal();
383
384     while ( ! tile_cache.at_end() ) {
385         // cout << "processing a tile" << endl;
386         if ( (e = tile_cache.get_current()) ) {
387             e->prep_ssg_node(vis);
388         } else {
389             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
390         }
391         tile_cache.next();
392     }
393 }
394
395 bool FGTileMgr::scenery_available(const SGGeod& position, double range_m)
396 {
397   // sanity check (unfortunately needed!)
398   if (position.getLongitudeDeg() < -180 || position.getLongitudeDeg() > 180 ||
399       position.getLatitudeDeg() < -90 || position.getLatitudeDeg() > 90)
400     return false;
401   
402   SGBucket bucket(position);
403   TileEntry *te = tile_cache.get_tile(bucket);
404   if (!te || !te->is_loaded())
405     return false;
406
407   SGVec3d cartPos = SGVec3d::fromGeod(position);
408
409   // Traverse all tiles required to be there for the given visibility.
410   // This uses exactly the same algorithm like the tile scheduler.
411   double tile_width = bucket.get_width_m();
412   double tile_height = bucket.get_height_m();
413   double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
414   double max_dist = tile_r + range_m;
415   double max_dist2 = max_dist*max_dist;
416   
417   int xrange = (int)fabs(range_m / tile_width) + 1;
418   int yrange = (int)fabs(range_m / tile_height) + 1;
419   
420   for ( int x = -xrange; x <= xrange; ++x ) {
421     for ( int y = -yrange; y <= yrange; ++y ) {
422       // We have already checked for the center tile.
423       if ( x != 0 || y != 0 ) {
424         SGBucket b = sgBucketOffset( position.getLongitudeDeg(),
425                                      position.getLatitudeDeg(), x, y );
426         // Do not ask if it is just the next tile but way out of range.
427         if (max_dist2 < distSqr(cartPos, SGVec3d::fromGeod(b.get_center())))
428           continue;
429         TileEntry *te = tile_cache.get_tile(b);
430         if (!te || !te->is_loaded())
431           return false;
432       }
433     }
434   }
435
436   // Survived all tests.
437   return true;
438 }
439
440 namespace
441 {
442 struct IsTileLoaded :
443         public std::unary_function<TileCache::tile_map::value_type, bool>
444 {
445     bool operator()(const TileCache::tile_map::value_type& tilePair) const
446     {
447         return tilePair.second->is_loaded();
448     }
449 };
450 }
451
452 bool FGTileMgr::isSceneryLoaded()
453 {
454     return (std::find_if(tile_cache.begin(), tile_cache.end(),
455                          std::not1(IsTileLoaded()))
456             == tile_cache.end());
457 }