]> git.mxchange.org Git - flightgear.git/blob - src/Scenery/tilemgr.cxx
Clean-up: move autosave.xml loading code to proper method
[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 <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
58 FGTileMgr::FGTileMgr():
59     state( Start ),
60     last_state( Running ),
61     vis( 16000 ),
62     _terra_sync(NULL)
63 {
64     _maxTileRangeM = fgGetNode("/sim/rendering/static-lod/bare", true);
65 }
66
67
68 FGTileMgr::~FGTileMgr()
69 {
70     // remove all nodes we might have left behind
71     osg::Group* group = globals->get_scenery()->get_terrain_branch();
72     group->removeChildren(0, group->getNumChildren());
73     // clear OSG cache
74     osgDB::Registry::instance()->clearObjectCache();
75 }
76
77
78 // Initialize the Tile Manager subsystem
79 void FGTileMgr::init() {
80     SG_LOG( SG_TERRAIN, SG_INFO, "Initializing Tile Manager subsystem." );
81
82     _options = new simgear::SGReaderWriterOptions;
83     _options->setMaterialLib(globals->get_matlib());
84     _options->setPropertyNode(globals->get_props());
85
86     osgDB::FilePathList &fp = _options->getDatabasePathList();
87     const string_list &sc = globals->get_fg_scenery();
88     fp.clear();
89     std::copy(sc.begin(), sc.end(), back_inserter(fp));
90
91     TileEntry::setModelLoadHelper(this);
92     
93     _visibilityMeters = fgGetNode("/environment/visibility-m", true);
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     // remove all old scenery nodes from scenegraph and clear cache
106     osg::Group* group = globals->get_scenery()->get_terrain_branch();
107     group->removeChildren(0, group->getNumChildren());
108     tile_cache.init();
109     
110     // clear OSG cache, except on initial start-up
111     if (state != Start)
112     {
113         osgDB::Registry::instance()->clearObjectCache();
114     }
115     
116     state = Inited;
117     
118     previous_bucket.make_bad();
119     current_bucket.make_bad();
120     longitude = latitude = -1000.0;
121
122     _terra_sync = (simgear::SGTerraSync*) globals->get_subsystem("terrasync");
123     if (_terra_sync)
124         _terra_sync->setTileRefreshCb(&refresh_tile, this);
125
126     // force an update now
127     update(0.0);
128 }
129
130 /* schedule a tile for loading, keep request for given amount of time.
131  * Returns true if tile is already loaded. */
132 bool FGTileMgr::sched_tile( const SGBucket& b, double priority, bool current_view, double duration)
133 {
134     // see if tile already exists in the cache
135     TileEntry *t = tile_cache.get_tile( b );
136     if (!t)
137     {
138         // create a new entry
139         t = new TileEntry( b );
140         // insert the tile into the cache, update will generate load request
141         if ( tile_cache.insert_tile( t ) )
142         {
143             // Attach to scene graph
144
145             t->addToSceneGraph(globals->get_scenery()->get_terrain_branch());
146         } else
147         {
148             // insert failed (cache full with no available entries to
149             // delete.)  Try again later
150             delete t;
151             return false;
152         }
153
154         SG_LOG( SG_TERRAIN, SG_DEBUG, "  New tile cache size " << (int)tile_cache.get_size() );
155     }
156
157     // update tile's properties
158     tile_cache.request_tile(t,priority,current_view,duration);
159
160     return t->is_loaded();
161 }
162
163 /* schedule needed buckets for the current view position for loading,
164  * keep request for given amount of time */
165 void FGTileMgr::schedule_needed(const SGBucket& curr_bucket, double vis)
166 {
167     // sanity check (unfortunately needed!)
168     if ( longitude < -180.0 || longitude > 180.0 
169          || latitude < -90.0 || latitude > 90.0 )
170     {
171         SG_LOG( SG_TERRAIN, SG_ALERT,
172                 "Attempting to schedule tiles for bogus lon and lat  = ("
173                 << longitude << "," << latitude << ")" );
174         return;
175     }
176
177     SG_LOG( SG_TERRAIN, SG_INFO,
178             "scheduling needed tiles for " << longitude << " " << latitude );
179
180     double tile_width = curr_bucket.get_width_m();
181     double tile_height = curr_bucket.get_height_m();
182     // cout << "tile width = " << tile_width << "  tile_height = "
183     //      << tile_height << endl;
184
185     double tileRangeM = std::min(vis,_maxTileRangeM->getDoubleValue());
186     xrange = (int)(tileRangeM / tile_width) + 1;
187     yrange = (int)(tileRangeM / tile_height) + 1;
188     if ( xrange < 1 ) { xrange = 1; }
189     if ( yrange < 1 ) { yrange = 1; }
190
191     // make the cache twice as large to avoid losing terrain when switching
192     // between aircraft and tower views
193     tile_cache.set_max_cache_size( (2*xrange + 2) * (2*yrange + 2) * 2 );
194     // cout << "xrange = " << xrange << "  yrange = " << yrange << endl;
195     // cout << "max cache size = " << tile_cache.get_max_cache_size()
196     //      << " current cache size = " << tile_cache.get_size() << endl;
197
198     // clear flags of all tiles belonging to the previous view set 
199     tile_cache.clear_current_view();
200
201     // update timestamps, so all tiles scheduled now are *newer* than any tile previously loaded
202     osg::FrameStamp* framestamp
203             = globals->get_renderer()->getViewer()->getFrameStamp();
204     tile_cache.set_current_time(framestamp->getReferenceTime());
205
206     SGBucket b;
207
208     int x, y;
209
210     /* schedule all tiles, use distance-based loading priority,
211      * so tiles are loaded in innermost-to-outermost sequence. */
212     for ( x = -xrange; x <= xrange; ++x )
213     {
214         for ( y = -yrange; y <= yrange; ++y )
215         {
216             SGBucket b = sgBucketOffset( longitude, latitude, x, y );
217             float priority = (-1.0) * (x*x+y*y);
218             sched_tile( b, priority, true, 0.0 );
219         }
220     }
221 }
222
223 osg::Node*
224 FGTileMgr::loadTileModel(const string& modelPath, bool cacheModel)
225 {
226     SGPath fullPath = modelPath;
227     if ((fullPath.isRelative())&&
228         (fgGetBool("/sim/paths/use-custom-scenery-data") == true)) {
229         string_list sc = globals->get_fg_scenery();
230
231         for (string_list_iterator it = sc.begin(); it != sc.end(); ++it) {
232             // fg_senery contains empty strings as "markers" (see FGGlobals::set_fg_scenery)
233             if (!it->empty()) {
234                 SGPath tmpPath(*it);
235                 tmpPath.append(modelPath);
236                 if (tmpPath.exists()) {
237                     fullPath = tmpPath;
238                     break;
239                 }
240             }
241         }
242     }
243     osg::Node* result = 0;
244     try {
245         if(cacheModel)
246             result =
247                 SGModelLib::loadModel(fullPath.str(), globals->get_props(),
248                                       new FGNasalModelData);
249         else
250         {
251             /* TODO FGNasalModelData's callback "modelLoaded" isn't thread-safe.
252              * But deferred (or paged) OSG loading runs in a separate thread, which would
253              * trigger the FGNasalModelData::modelLoaded callback. We're easily doomed
254              * when this happens and the model actually contains a Nasal "load" hook - which
255              * would run the Nasal parser and Nasal script execution in a separate thread...
256              * => Disabling the callback for now, to test if all Nasal related segfaults are
257              * gone. Proper resolution is TBD. We'll need to somehow decouple the OSG callback,
258              * so we can run the Nasal stuff in the main thread.
259              */
260             result=
261                 SGModelLib::loadDeferredModel(fullPath.str(), globals->get_props()/*,
262                                              new FGNasalModelData*/);
263         }
264     } catch (const sg_io_exception& exc) {
265         string m(exc.getMessage());
266         m += " ";
267         m += exc.getLocation().asString();
268         SG_LOG( SG_TERRAIN, SG_ALERT, m );
269     } catch (const sg_exception& exc) { // XXX may be redundant
270         SG_LOG( SG_TERRAIN, SG_ALERT, exc.getMessage());
271     }
272     return result;
273 }
274
275 /**
276  * Update the various queues maintained by the tilemagr (private
277  * internal function, do not call directly.)
278  */
279 void FGTileMgr::update_queues()
280 {
281     SceneryPager* pager = FGScenery::getPagerSingleton();
282     osg::FrameStamp* framestamp
283         = globals->get_renderer()->getViewer()->getFrameStamp();
284     double current_time = framestamp->getReferenceTime();
285     double vis = _visibilityMeters->getDoubleValue();
286     TileEntry *e;
287     int loading=0;
288     int sz=0;
289
290     tile_cache.set_current_time( current_time );
291     tile_cache.reset_traversal();
292
293     while ( ! tile_cache.at_end() )
294     {
295         e = tile_cache.get_current();
296         // cout << "processing a tile" << endl;
297         if ( e )
298         {
299             // Prepare the ssg nodes corresponding to each tile.
300             // Set the ssg transform and update it's range selector
301             // based on current visibilty
302             e->prep_ssg_node(vis);
303
304             if (( !e->is_loaded() )&&
305                 ((!e->is_expired(current_time))||
306                   e->is_current_view() ))
307             {
308                 // schedule tile for loading with osg pager
309                 pager->queueRequest(e->tileFileName,
310                                     e->getNode(),
311                                     e->get_priority(),
312                                     framestamp,
313                                     e->getDatabaseRequest(),
314                                     _options.get());
315                 loading++;
316             }
317         } else
318         {
319             SG_LOG(SG_TERRAIN, SG_ALERT, "Warning: empty tile in cache!");
320         }
321         tile_cache.next();
322         sz++;
323     }
324
325     int drop_count = sz - tile_cache.get_max_cache_size();
326     if (( drop_count > 0 )&&
327          ((loading==0)||(drop_count > 10)))
328     {
329         long drop_index = tile_cache.get_drop_tile();
330         while ( drop_index > -1 )
331         {
332             // schedule tile for deletion with osg pager
333             TileEntry* old = tile_cache.get_tile(drop_index);
334             tile_cache.clear_entry(drop_index);
335             
336             osg::ref_ptr<osg::Object> subgraph = old->getNode();
337             old->removeFromSceneGraph();
338             delete old;
339             // zeros out subgraph ref_ptr, so subgraph is owned by
340             // the pager and will be deleted in the pager thread.
341             pager->queueDeleteRequest(subgraph);
342             
343             if (--drop_count > 0)
344                 drop_index = tile_cache.get_drop_tile();
345             else
346                 drop_index = -1;
347         }
348     }
349 }
350
351 // given the current lon/lat (in degrees), fill in the array of local
352 // chunks.  If the chunk isn't already in the cache, then read it from
353 // disk.
354 void FGTileMgr::update(double)
355 {
356     SGVec3d viewPos = globals->get_current_view()->get_view_pos();
357     double vis = _visibilityMeters->getDoubleValue();
358     schedule_tiles_at(SGGeod::fromCart(viewPos), vis);
359
360     update_queues();
361 }
362
363 // schedule tiles for the viewer bucket (FDM/AI/groundcache/... use
364 // "schedule_scenery" instead
365 int FGTileMgr::schedule_tiles_at(const SGGeod& location, double range_m)
366 {
367     longitude = location.getLongitudeDeg();
368     latitude = location.getLatitudeDeg();
369
370     // SG_LOG( SG_TERRAIN, SG_DEBUG, "FGTileMgr::update() for "
371     //         << longitude << " " << latatitude );
372
373     current_bucket.set_bucket( location );
374
375     // schedule more tiles when visibility increased considerably
376     // TODO Calculate tile size - instead of using fixed value (5000m)
377     if (range_m-scheduled_visibility > 5000.0)
378         previous_bucket.make_bad();
379
380     // SG_LOG( SG_TERRAIN, SG_DEBUG, "Updating tile list for "
381     //         << current_bucket );
382     fgSetInt( "/environment/current-tile-id", current_bucket.gen_index() );
383
384     // do tile load scheduling.
385     // Note that we need keep track of both viewer buckets and fdm buckets.
386     if ( state == Running ) {
387         if (last_state != state)
388         {
389             SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Running" );
390         }
391         if (current_bucket != previous_bucket) {
392             // We've moved to a new bucket, we need to schedule any
393             // needed tiles for loading.
394             SG_LOG( SG_TERRAIN, SG_INFO, "FGTileMgr::update()" );
395             scheduled_visibility = range_m;
396             schedule_needed(current_bucket, range_m);
397             if (_terra_sync)
398                 _terra_sync->schedulePosition(latitude,longitude);
399         }
400         // save bucket
401         previous_bucket = current_bucket;
402     } else if ( state == Start || state == Inited ) {
403         SG_LOG( SG_TERRAIN, SG_DEBUG, "State == Start || Inited" );
404         // do not update bucket yet (position not valid in initial loop)
405         state = Running;
406         previous_bucket.make_bad();
407     }
408     last_state = state;
409
410     return 1;
411 }
412
413 /** Schedules scenery for given position. Load request remains valid for given duration
414  * (duration=0.0 => nothing is loaded).
415  * Used for FDM/AI/groundcache/... requests. Viewer uses "schedule_tiles_at" instead.
416  * Returns true when all tiles for the given position are already loaded, false otherwise.
417  */
418 bool FGTileMgr::schedule_scenery(const SGGeod& position, double range_m, double duration)
419 {
420     const float priority = 0.0;
421     double current_longitude = position.getLongitudeDeg();
422     double current_latitude = position.getLatitudeDeg();
423     bool available = true;
424     
425     // sanity check (unfortunately needed!)
426     if (current_longitude < -180 || current_longitude > 180 ||
427         current_latitude < -90 || current_latitude > 90)
428         return false;
429   
430     SGBucket bucket(position);
431     available = sched_tile( bucket, priority, false, duration );
432   
433     if ((!available)&&(duration==0.0))
434         return false;
435
436     SGVec3d cartPos = SGVec3d::fromGeod(position);
437
438     // Traverse all tiles required to be there for the given visibility.
439     double tile_width = bucket.get_width_m();
440     double tile_height = bucket.get_height_m();
441     double tile_r = 0.5*sqrt(tile_width*tile_width + tile_height*tile_height);
442     double max_dist = tile_r + range_m;
443     double max_dist2 = max_dist*max_dist;
444     
445     int xrange = (int)fabs(range_m / tile_width) + 1;
446     int yrange = (int)fabs(range_m / tile_height) + 1;
447
448     for ( int x = -xrange; x <= xrange; ++x )
449     {
450         for ( int y = -yrange; y <= yrange; ++y )
451         {
452             // We have already checked for the center tile.
453             if ( x != 0 || y != 0 )
454             {
455                 SGBucket b = sgBucketOffset( current_longitude,
456                                              current_latitude, x, y );
457                 double distance2 = distSqr(cartPos, SGVec3d::fromGeod(b.get_center()));
458                 // Do not ask if it is just the next tile but way out of range.
459                 if (distance2 <= max_dist2)
460                 {
461                     available &= sched_tile( b, priority, false, duration );
462                     if ((!available)&&(duration==0.0))
463                         return false;
464                 }
465             }
466         }
467     }
468
469     return available;
470 }
471
472 // Returns true if tiles around current view position have been loaded
473 bool FGTileMgr::isSceneryLoaded()
474 {
475     double range_m = 100.0;
476     if (scheduled_visibility < range_m)
477         range_m = scheduled_visibility;
478
479     return schedule_scenery(SGGeod::fromDeg(longitude, latitude), range_m, 0.0);
480 }