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