]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Revert "Fix compilation problem with MSVC 2012"
[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 #include <osgDB/Registry>
33
34 #include <simgear/constants.h>
35 #include <simgear/debug/logstream.hxx>
36 #include <simgear/structure/exception.hxx>
37 #include <simgear/scene/model/modellib.hxx>
38 #include <simgear/scene/util/SGReaderWriterOptions.hxx>
39 #include <simgear/scene/tsync/terrasync.hxx>
40
41 #include <Main/globals.hxx>
42 #include <Main/fg_props.hxx>
43 #include <Viewer/renderer.hxx>
44 #include <Viewer/viewer.hxx>
45 #include <Scripting/NasalSys.hxx>
46
47 #include "scenery.hxx"
48 #include "SceneryPager.hxx"
49 #include "tilemgr.hxx"
50
51 using flightgear::SceneryPager;
52
53
54 FGTileMgr::FGTileMgr():
55     state( Start ),
56     last_state( Running ),
57     longitude(-1000.0),
58     latitude(-1000.0),
59     scheduled_visibility(100.0),
60     _terra_sync(NULL),
61     _visibilityMeters(fgGetNode("/environment/visibility-m", true)),
62     _maxTileRangeM(fgGetNode("/sim/rendering/static-lod/bare", true)),
63     _disableNasalHooks(fgGetNode("/sim/temp/disable-scenery-nasal", true)),
64     _pager(FGScenery::getPagerSingleton())
65 {
66 }
67
68
69 FGTileMgr::~FGTileMgr()
70 {
71     // remove all nodes we might have left behind
72     osg::Group* group = globals->get_scenery()->get_terrain_branch();
73     group->removeChildren(0, group->getNumChildren());
74     // clear OSG cache
75     osgDB::Registry::instance()->clearObjectCache();
76 }
77
78
79 // Initialize the Tile Manager subsystem
80 void FGTileMgr::init() {
81     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
82
83     _options = new simgear::SGReaderWriterOptions;
84     _options->setMaterialLib(globals->get_matlib());
85     _options->setPropertyNode(globals->get_props());
86
87     osgDB::FilePathList &fp = _options->getDatabasePathList();
88     const string_list &sc = globals->get_fg_scenery();
89     fp.clear();
90     std::copy(sc.begin(), sc.end(), back_inserter(fp));
91     _options->setPluginStringData("SimGear::FG_ROOT", globals->get_fg_root());
92     if (!_disableNasalHooks->getBoolValue())
93         _options->setModelData(new FGNasalModelDataProxy);
94
95     reinit();
96 }
97
98 void FGTileMgr::refresh_tile(void* tileMgr, long tileIndex)
99 {
100     ((FGTileMgr*) tileMgr)->tile_cache.refresh_tile(tileIndex);
101 }
102
103 void FGTileMgr::reinit()
104 {
105     // protect against multiple scenery reloads and properly reset flags,
106     // otherwise aircraft fall through the ground while reloading scenery
107     if (!fgGetBool("/sim/sceneryloaded",true))
108         return;
109     fgSetBool("/sim/sceneryloaded",false);
110     fgSetDouble("/sim/startup/splash-alpha", 1.0);
111     
112     // Reload the materials definitions
113     _options->setMaterialLib(globals->get_matlib());
114
115     // remove all old scenery nodes from scenegraph and clear cache
116     osg::Group* group = globals->get_scenery()->get_terrain_branch();
117     group->removeChildren(0, group->getNumChildren());
118     tile_cache.init();
119     
120     // clear OSG cache, except on initial start-up
121     if (state != Start)
122     {
123         osgDB::Registry::instance()->clearObjectCache();
124     }
125     
126     state = Inited;
127     
128     previous_bucket.make_bad();
129     current_bucket.make_bad();
130     longitude = latitude = -1000.0;
131     scheduled_visibility = 100.0;
132
133     _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
134     if (_terra_sync)
135         _terra_sync->setTileRefreshCb(&refresh_tile, this);
136
137     // force an update now
138     update(0.0);
139 }
140
141 /* schedule a tile for loading, keep request for given amount of time.
142  * Returns true if tile is already loaded. */
143 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
144 {
145     // see if tile already exists in the cache
146     TileEntry *t = tile_cache.get_tile( b );
147     if (!t)
148     {
149         // create a new entry
150         t = new TileEntry( b );
151         // insert the tile into the cache, update will generate load request
152         if ( tile_cache.insert_tile( t ) )
153         {
154             // Attach to scene graph
155
156             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
157         } else
158         {
159             // insert failed (cache full with no available entries to
160             // delete.)  Try again later
161             delete t;
162             return false;
163         }
164
165         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
166     }
167
168     // update tile's properties
169     tile_cache.request_tile(t,priority,current_view,duration);
170
171     return t->is_loaded();
172 }
173
174 /* schedule needed buckets for the current view position for loading,
175  * keep request for given amount of time */
176 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
177 {
178     // sanity check (unfortunately needed!)
179     if ( longitude < -180.0 || longitude > 180.0 
180          || latitude < -90.0 || latitude > 90.0 )
181     {
182         SG_LOG( SG_TERRAIN, SG_ALERT,
183                 "Attempting to schedule tiles for bogus lon and lat  = ("
184                 << longitude << "," << latitude << ")" );
185         return;
186     }
187
188     SG_LOG( SG_TERRAIN, SG_INFO,
189             "scheduling needed tiles for " << longitude << " " << latitude );
190
191     double tile_width = curr_bucket.get_width_m();
192     double tile_height = curr_bucket.get_height_m();
193     // cout << "tile width = " << tile_width << "  tile_height = "
194     //      << tile_height << endl;
195
196     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
197     int xrange = (int)(tileRangeM / tile_width) + 1;
198     int yrange = (int)(tileRangeM / tile_height) + 1;
199     if ( xrange < 1 ) { xrange = 1; }
200     if ( yrange < 1 ) { yrange = 1; }
201
202     // make the cache twice as large to avoid losing terrain when switching
203     // between aircraft and tower views
204     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
205     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
206     // cout << "max cache size = " << tile_cache.get_max_cache_size()
207     //      << " current cache size = " << tile_cache.get_size() << endl;
208
209     // clear flags of all tiles belonging to the previous view set 
210     tile_cache.clear_current_view();
211
212     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
213     osg::FrameStamp* framestamp
214             = globals->get_renderer()->getViewer()->getFrameStamp();
215     tile_cache.set_current_time(framestamp->getReferenceTime());
216
217     SGBucket b;
218
219     int x, y;
220
221     /* schedule all tiles, use distance-based loading priority,
222      * so tiles are loaded in innermost-to-outermost sequence. */
223     for ( x = -xrange; x <= xrange; ++x )
224     {
225         for ( y = -yrange; y <= yrange; ++y )
226         {
227             SGBucket b = sgBucketOffset( longitude, latitude, x, y );
228             float priority = (-1.0) * (x*x+y*y);
229             sched_tile( b, priority, true, 0.0 );
230         }
231     }
232 }
233
234 /**
235  * Update the various queues maintained by the tilemagr (private
236  * internal function, do not call directly.)
237  */
238 void FGTileMgr::update_queues()
239 {
240     osg::FrameStamp* framestamp
241         = globals->get_renderer()->getViewer()->getFrameStamp();
242     double current_time = framestamp->getReferenceTime();
243     double vis = _visibilityMeters->getDoubleValue();
244     TileEntry *e;
245     int loading=0;
246     int sz=0;
247
248     tile_cache.set_current_time( current_time );
249     tile_cache.reset_traversal();
250
251     while ( ! tile_cache.at_end() )
252     {
253         e = tile_cache.get_current();
254         // cout << "processing a tile" << endl;
255         if ( e )
256         {
257             // Prepare the ssg nodes corresponding to each tile.
258             // Set the ssg transform and update it's range selector
259             // based on current visibilty
260             e->prep_ssg_node(vis);
261
262             if (( !e->is_loaded() )&&
263                 ((!e->is_expired(current_time))||
264                   e->is_current_view() ))
265             {
266                 // schedule tile for loading with osg pager
267                 _pager->queueRequest(e->tileFileName,
268                                      e->getNode(),
269                                      e->get_priority(),
270                                      framestamp,
271                                      e->getDatabaseRequest(),
272                                      _options.get());
273                 loading++;
274             }
275         } else
276         {
277             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
278         }
279         tile_cache.next();
280         sz++;
281     }
282
283     int drop_count = sz - tile_cache.get_max_cache_size();
284     if (( drop_count > 0 )&&
285          ((loading==0)||(drop_count > 10)))
286     {
287         long drop_index = tile_cache.get_drop_tile();
288         while ( drop_index > -1 )
289         {
290             // schedule tile for deletion with osg pager
291             TileEntry* old = tile_cache.get_tile(drop_index);
292             tile_cache.clear_entry(drop_index);
293             
294             osg::ref_ptr<osg::Object> subgraph = old->getNode();
295             old->removeFromSceneGraph();
296             delete old;
297             // zeros out subgraph ref_ptr, so subgraph is owned by
298             // the pager and will be deleted in the pager thread.
299             _pager->queueDeleteRequest(subgraph);
300             
301             if (--drop_count > 0)
302                 drop_index = tile_cache.get_drop_tile();
303             else
304                 drop_index = -1;
305         }
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 void FGTileMgr::update(double)
313 {
314     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
315     double vis = _visibilityMeters->getDoubleValue();
316     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
317
318     update_queues();
319 }
320
321 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
322 // "schedule_scenery" instead
323 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
324 {
325     longitude = location.getLongitudeDeg();
326     latitude = location.getLatitudeDeg();
327
328     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
329     //         << longitude << " " << latatitude );
330
331     current_bucket.set_bucket( location );
332
333     // schedule more tiles when visibility increased considerably
334     // TODO Calculate tile size - instead of using fixed value (5000m)
335     if (range_m - scheduled_visibility > 5000.0)
336         previous_bucket.make_bad();
337
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         if (last_state != state)
346         {
347             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
348         }
349         if (current_bucket != previous_bucket) {
350             // We've moved to a new bucket, we need to schedule any
351             // needed tiles for loading.
352             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
353             scheduled_visibility = range_m;
354             schedule_needed(current_bucket, range_m);
355             if (_terra_sync)
356                 _terra_sync->schedulePosition(latitude,longitude);
357         }
358         // save bucket
359         previous_bucket = current_bucket;
360     } else if ( state == Start || state == Inited ) {
361         SG_LOG( SG_TERRAIN, SG_DEBUG, "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     last_state = state;
367
368     return 1;
369 }
370
371 /** Schedules scenery for given position. Load request remains valid for given duration
372  * (duration=0.0 => nothing is loaded).
373  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
374  * Returns true when all tiles for the given position are already loaded, false otherwise.
375  */
376 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
377 {
378     const float priority = 0.0;
379     double current_longitude = position.getLongitudeDeg();
380     double current_latitude = position.getLatitudeDeg();
381     bool available = true;
382     
383     // sanity check (unfortunately needed!)
384     if (current_longitude < -180 || current_longitude > 180 ||
385         current_latitude < -90 || current_latitude > 90)
386         return false;
387   
388     SGBucket bucket(position);
389     available = sched_tile( bucket, priority, false, duration );
390   
391     if ((!available)&&(duration==0.0))
392         return false;
393
394     SGVec3d cartPos = SGVec3d::fromGeod(position);
395
396     // Traverse all tiles required to be there for the given visibility.
397     double tile_width = bucket.get_width_m();
398     double tile_height = bucket.get_height_m();
399     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
400     double max_dist = tile_r + range_m;
401     double max_dist2 = max_dist*max_dist;
402     
403     int xrange = (int)fabs(range_m / tile_width) + 1;
404     int yrange = (int)fabs(range_m / tile_height) + 1;
405
406     for ( int x = -xrange; x <= xrange; ++x )
407     {
408         for ( int y = -yrange; y <= yrange; ++y )
409         {
410             // We have already checked for the center tile.
411             if ( x != 0 || y != 0 )
412             {
413                 SGBucket b = sgBucketOffset( current_longitude,
414                                              current_latitude, x, y );
415                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
416                 // Do not ask if it is just the next tile but way out of range.
417                 if (distance2 <= max_dist2)
418                 {
419                     available &= sched_tile( b, priority, false, duration );
420                     if ((!available)&&(duration==0.0))
421                         return false;
422                 }
423             }
424         }
425     }
426
427     return available;
428 }
429
430 // Returns true if tiles around current view position have been loaded
431 bool FGTileMgr::isSceneryLoaded()
432 {
433     double range_m = 100.0;
434     if (scheduled_visibility < range_m)
435         range_m = scheduled_visibility;
436
437     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
438 }