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