]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Fix bug 191, uninitialised HUD color.
[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 FGTileMgr::FGTileMgr():
56     state( Start ),
57     vis( 16000 )
58 {
59 }
60
61
62 FGTileMgr::~FGTileMgr() {
63     // remove all nodes we might have left behind
64     osg::Group* group = globals->get_scenery()->get_terrain_branch();
65     group->removeChildren(0, group->getNumChildren());
66 }
67
68
69 // Initialize the Tile Manager subsystem
70 void FGTileMgr::init() {
71     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
72
73     _options = new SGReaderWriterBTGOptions;
74     _options->setMatlib(globals->get_matlib());
75     _options->setUseRandomObjects(fgGetBool("/sim/rendering/random-objects", true));
76     _options->setUseRandomVegetation(fgGetBool("/sim/rendering/random-vegetation", true));
77     osgDB::FilePathList &fp = _options->getDatabasePathList();
78     const string_list &sc = globals->get_fg_scenery();
79     fp.clear();
80     std::copy(sc.begin(), sc.end(), back_inserter(fp));
81
82     TileEntry::setModelLoadHelper(this);
83     
84     _visibilityMeters = fgGetNode("/environment/visibility-m", true);
85
86     reinit();
87 }
88
89
90 void FGTileMgr::reinit()
91 {
92     tile_cache.init();
93     
94     state = Inited;
95     
96     previous_bucket.make_bad();
97     current_bucket.make_bad();
98     longitude = latitude = -1000.0;
99     
100     // force an update now
101     update(0.0);
102 }
103
104
105 /* schedule a tile for loading, keep request for given amount of time.
106  * Returns true if tile is already loaded. */
107 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
108 {
109     // see if tile already exists in the cache
110     TileEntry *t = tile_cache.get_tile( b );
111     if (!t)
112     {
113         // create a new entry
114         t = new TileEntry( b );
115         // insert the tile into the cache, update will generate load request
116         if ( tile_cache.insert_tile( t ) )
117         {
118             // Attach to scene graph
119             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
120         } else
121         {
122             // insert failed (cache full with no available entries to
123             // delete.)  Try again later
124             delete t;
125             return false;
126         }
127
128         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
129     }
130
131     // update tile's properties
132     tile_cache.request_tile(t,priority,current_view,duration);
133
134     return t->is_loaded();
135 }
136
137 /* schedule needed buckets for the current view position for loading,
138  * keep request for given amount of time */
139 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
140 {
141     // sanity check (unfortunately needed!)
142     if ( longitude < -180.0 || longitude > 180.0 
143          || latitude < -90.0 || latitude > 90.0 )
144     {
145         SG_LOG( SG_TERRAIN, SG_ALERT,
146                 "Attempting to schedule tiles for bogus lon and lat  = ("
147                 << longitude << "," << latitude << ")" );
148         return;         // FIXME
149         SG_LOG( SG_TERRAIN, SG_ALERT,
150                 "This is a FATAL error.  Exiting!" );
151         exit(-1);
152     }
153
154     SG_LOG( SG_TERRAIN, SG_INFO,
155             "scheduling needed tiles for " << longitude << " " << latitude );
156
157     double tile_width = curr_bucket.get_width_m();
158     double tile_height = curr_bucket.get_height_m();
159     // cout << "tile width = " << tile_width << "  tile_height = "
160     //      << tile_height << endl;
161
162     xrange = (int)(vis / tile_width) + 1;
163     yrange = (int)(vis / tile_height) + 1;
164     if ( xrange < 1 ) { xrange = 1; }
165     if ( yrange < 1 ) { yrange = 1; }
166
167     // make the cache twice as large to avoid losing terrain when switching
168     // between aircraft and tower views
169     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
170     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
171     // cout << "max cache size = " << tile_cache.get_max_cache_size()
172     //      << " current cache size = " << tile_cache.get_size() << endl;
173
174     // clear flags of all tiles belonging to the previous view set 
175     tile_cache.clear_current_view();
176
177     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
178     osg::FrameStamp* framestamp
179             = globals->get_renderer()->getViewer()->getFrameStamp();
180     tile_cache.set_current_time(framestamp->getReferenceTime());
181
182     SGBucket b;
183
184     int x, y;
185
186     /* schedule all tiles, use distance-based loading priority,
187      * so tiles are loaded in innermost-to-outermost sequence. */
188     for ( x = -xrange; x <= xrange; ++x )
189     {
190         for ( y = -yrange; y <= yrange; ++y )
191         {
192             SGBucket b = sgBucketOffset( longitude, latitude, x, y );
193             float priority = (-1.0) * (x*x+y*y);
194             sched_tile( b, priority, true, 0.0 );
195         }
196     }
197 }
198
199 osg::Node*
200 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
201 {
202     SGPath fullPath;
203     if (fgGetBool("/sim/paths/use-custom-scenery-data") == true) {
204         string_list sc = globals->get_fg_scenery();
205
206         for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
207             SGPath tmpPath(*it);
208             tmpPath.append(modelPath);
209             if (tmpPath.exists()) {
210                 fullPath = tmpPath;
211                 break;
212             } 
213         }
214     } else {
215          fullPath.append(modelPath);
216     }
217     osg::Node* result = 0;
218     try {
219         if(cacheModel)
220             result =
221                 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
222                                       new FGNasalModelData);
223         else
224             result=
225                 SGModelLib::loadPagedModel(modelPath, globals->get_props(),
226                                            new FGNasalModelData);
227     } catch (const sg_io_exception& exc) {
228         string m(exc.getMessage());
229         m += " ";
230         m += exc.getLocation().asString();
231         SG_LOG( SG_ALL, SG_ALERT, m );
232     } catch (const sg_exception& exc) { // XXX may be redundant
233         SG_LOG( SG_ALL, SG_ALERT, exc.getMessage());
234     }
235     return result;
236 }
237
238 /**
239  * Update the various queues maintained by the tilemagr (private
240  * internal function, do not call directly.)
241  */
242 void FGTileMgr::update_queues()
243 {
244     SceneryPager* pager = FGScenery::getPagerSingleton();
245     osg::FrameStamp* framestamp
246         = globals->get_renderer()->getViewer()->getFrameStamp();
247     double current_time = framestamp->getReferenceTime();
248     double vis = _visibilityMeters->getDoubleValue();
249     TileEntry *e;
250     int loading=0;
251     int sz=0;
252
253     tile_cache.set_current_time( current_time );
254     tile_cache.reset_traversal();
255
256     while ( ! tile_cache.at_end() )
257     {
258         e = tile_cache.get_current();
259         // cout << "processing a tile" << endl;
260         if ( e )
261         {
262             // Prepare the ssg nodes corresponding to each tile.
263             // Set the ssg transform and update it's range selector
264             // based on current visibilty
265             e->prep_ssg_node(vis);
266
267             if (( !e->is_loaded() )&&
268                 ( !e->is_expired(current_time) ))
269             {
270                 // schedule tile for loading with osg pager
271                 pager->queueRequest(e->tileFileName,
272                                     e->getNode(),
273                                     e->get_priority(),
274                                     framestamp,
275                                     e->getDatabaseRequest(),
276                                     _options.get());
277                 loading++;
278             }
279         } else
280         {
281             SG_LOG(SG_INPUT, SG_ALERT, "warning ... empty tile in cache");
282         }
283         tile_cache.next();
284         sz++;
285     }
286
287     int drop_count = sz - tile_cache.get_max_cache_size();
288     if (( drop_count > 0 )&&
289          ((loading==0)||(drop_count > 10)))
290     {
291         long drop_index = tile_cache.get_drop_tile();
292         while ( drop_index > -1 )
293         {
294             // schedule tile for deletion with osg pager
295             TileEntry* old = tile_cache.get_tile(drop_index);
296             tile_cache.clear_entry(drop_index);
297             
298             osg::ref_ptr<osg::Object> subgraph = old->getNode();
299             old->removeFromSceneGraph();
300             delete old;
301             // zeros out subgraph ref_ptr, so subgraph is owned by
302             // the pager and will be deleted in the pager thread.
303             pager->queueDeleteRequest(subgraph);
304             
305             if (--drop_count > 0)
306                 drop_index = tile_cache.get_drop_tile();
307             else
308                 drop_index = -1;
309         }
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 void FGTileMgr::update(double)
317 {
318     SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update()" );
319     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
320     double vis = _visibilityMeters->getDoubleValue();
321     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
322
323     update_queues();
324 }
325
326 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
327 // "schedule_scenery" instead
328 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
329 {
330     longitude = location.getLongitudeDeg();
331     latitude = location.getLatitudeDeg();
332
333     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
334     //         << longitude << " " << latatitude );
335
336     current_bucket.set_bucket( location );
337
338     // schedule more tiles when visibility increased considerably
339     // TODO Calculate tile size - instead of using fixed value (5000m)
340     if (range_m-scheduled_visibility > 5000.0)
341         previous_bucket.make_bad();
342
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             scheduled_visibility = range_m;
356             schedule_needed(current_bucket, range_m);
357         }
358         // save bucket
359         previous_bucket = current_bucket;
360     } else if ( state == Start || state == Inited ) {
361         SG_LOG( SG_TERRAIN, SG_INFO, "State == Start || Inited" );
362         // do not update bucket yet (position not valid in initial loop)
363         state = Running;
364         previous_bucket.make_bad();
365     }
366
367     return 1;
368 }
369
370 /** Schedules scenery for given position. Load request remains valid for given duration
371  * (duration=0.0 => nothing is loaded).
372  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
373  * Returns true when all tiles for the given position are already loaded, false otherwise.
374  */
375 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
376 {
377     const float priority = 0.0;
378     double current_longitude = position.getLongitudeDeg();
379     double current_latitude = position.getLatitudeDeg();
380     bool available = true;
381     
382     // sanity check (unfortunately needed!)
383     if (current_longitude < -180 || current_longitude > 180 ||
384         current_latitude < -90 || current_latitude > 90)
385         return false;
386   
387     SGBucket bucket(position);
388     available = sched_tile( bucket, priority, false, duration );
389   
390     if ((!available)&&(duration==0.0))
391         return false;
392
393     SGVec3d cartPos = SGVec3d::fromGeod(position);
394
395     // Traverse all tiles required to be there for the given visibility.
396     double tile_width = bucket.get_width_m();
397     double tile_height = bucket.get_height_m();
398     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
399     double max_dist = tile_r + range_m;
400     double max_dist2 = max_dist*max_dist;
401     
402     int xrange = (int)fabs(range_m / tile_width) + 1;
403     int yrange = (int)fabs(range_m / tile_height) + 1;
404
405     for ( int x = -xrange; x <= xrange; ++x )
406     {
407         for ( int y = -yrange; y <= yrange; ++y )
408         {
409             // We have already checked for the center tile.
410             if ( x != 0 || y != 0 )
411             {
412                 SGBucket b = sgBucketOffset( current_longitude,
413                                              current_latitude, x, y );
414                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
415                 // Do not ask if it is just the next tile but way out of range.
416                 if (distance2 <= max_dist2)
417                 {
418                     available &= sched_tile( b, priority, false, duration );
419                     if ((!available)&&(duration==0.0))
420                         return false;
421                 }
422             }
423         }
424     }
425
426     return available;
427 }
428
429 // Returns true if tiles around current view position have been loaded
430 bool FGTileMgr::isSceneryLoaded()
431 {
432     double range_m = 100.0;
433     if (scheduled_visibility < range_m)
434         range_m = scheduled_visibility;
435
436     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
437 }