1 // terrasync.cxx -- scenery fetcher
3 // Started by Curtis Olson, November 2002.
5 // Copyright (C) 2002 Curtis L. Olson - http://www.flightgear.org/~curt
6 // Copyright (C) 2008 Alexander R. Perry <alex.perry@ieee.org>
7 // Copyright (C) 2011 Thorsten Brehm <brehmt@gmail.com>
9 // This program is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU General Public License as
11 // published by the Free Software Foundation; either version 2 of the
12 // License, or (at your option) any later version.
14 // This program is distributed in the hope that it will be useful, but
15 // WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // General Public License for more details.
19 // You should have received a copy of the GNU General Public License
20 // along with this program; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 # include <simgear_config.h>
29 #include <simgear/compiler.h>
38 #elif defined(_MSC_VER)
44 #include <stdlib.h> // atoi() atof() abs() system()
45 #include <signal.h> // signal()
53 #include <simgear/compiler.h>
55 #include "terrasync.hxx"
57 #include <simgear/bucket/newbucket.hxx>
58 #include <simgear/misc/sg_path.hxx>
59 #include <simgear/misc/strutils.hxx>
60 #include <simgear/threads/SGQueue.hxx>
61 #include <simgear/misc/sg_dir.hxx>
62 #include <simgear/debug/BufferedLogCallback.hxx>
63 #include <simgear/props/props_io.hxx>
64 #include <simgear/io/HTTPClient.hxx>
65 #include <simgear/io/SVNRepository.hxx>
66 #include <simgear/structure/exception.hxx>
68 static const bool svn_built_in_available = true;
70 using namespace simgear;
73 const char* rsync_cmd =
74 "rsync --verbose --archive --delete --perms --owner --group";
76 const char* svn_options =
79 namespace UpdateInterval
81 // interval in seconds to allow an update to repeat after a successful update (=daily)
82 static const double SuccessfulAttempt = 24*60*60;
83 // interval in seconds to allow another update after a failed attempt (10 minutes)
84 static const double FailedAttempt = 10*60;
87 typedef map<string,time_t> CompletedTiles;
89 ///////////////////////////////////////////////////////////////////////////////
90 // helper functions ///////////////////////////////////////////////////////////
91 ///////////////////////////////////////////////////////////////////////////////
92 string stripPath(string path)
94 // svn doesn't like trailing white-spaces or path separators - strip them!
95 path = simgear::strutils::strip(path);
96 size_t slen = path.length();
98 ((path[slen-1]=='/')||(path[slen-1]=='\\')))
102 return path.substr(0,slen);
105 bool hasWhitespace(string path)
107 return path.find(' ')!=string::npos;
110 ///////////////////////////////////////////////////////////////////////////////
111 // WaitingSyncItem ////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
113 class WaitingSyncItem
118 Stop = 0, ///< special item indicating to stop the SVNThread
127 _refreshScenery(false)
131 WaitingSyncItem(string dir, Type ty) :
134 _refreshScenery(false)
138 { _refreshScenery = true; }
142 bool _refreshScenery;
145 ///////////////////////////////////////////////////////////////////////////////
148 * @brief SyncSlot encapsulates a queue of sync items we will fetch
149 * serially. Multiple slots exist to sync different types of item in
156 isNewDirectory(false),
160 WaitingSyncItem currentItem;
162 std::queue<WaitingSyncItem> queue;
163 std::auto_ptr<SVNRepository> repository;
165 bool busy; ///< is the slot working or idle
167 unsigned int nextWarnTimeout;
170 static const int SYNC_SLOT_TILES = 0; ///< Terrain and Objects sync
171 static const int SYNC_SLOT_SHARED_DATA = 1; /// shared Models and Airport data
172 static const int NUM_SYNC_SLOTS = 2;
175 * @brief translate a sync item type into one of the available slots.
176 * This provides the scheduling / balancing / prioritising between slots.
178 static unsigned int syncSlotForType(WaitingSyncItem::Type ty)
181 case WaitingSyncItem::Tile: return SYNC_SLOT_TILES;
182 case WaitingSyncItem::SharedModels:
183 case WaitingSyncItem::AirportData:
184 return SYNC_SLOT_SHARED_DATA;
186 return SYNC_SLOT_SHARED_DATA;
191 ///////////////////////////////////////////////////////////////////////////////
192 // SGTerraSync::SvnThread /////////////////////////////////////////////////////
193 ///////////////////////////////////////////////////////////////////////////////
194 class SGTerraSync::SvnThread : public SGThread
198 virtual ~SvnThread( ) { stop(); }
203 bool isIdle() {return waitingTiles.empty();}
204 void request(const WaitingSyncItem& dir) {waitingTiles.push_front(dir);}
205 bool isDirty() { bool r = _is_dirty;_is_dirty = false;return r;}
206 bool hasNewTiles() { return !_freshTiles.empty();}
207 WaitingSyncItem getNewTile() { return _freshTiles.pop_front();}
209 void setSvnServer(string server) { _svn_server = stripPath(server);}
210 void setExtSvnUtility(string svn_util) { _svn_command = simgear::strutils::strip(svn_util);}
211 void setRsyncServer(string server) { _rsync_server = simgear::strutils::strip(server);}
212 void setLocalDir(string dir) { _local_dir = stripPath(dir);}
213 string getLocalDir() { return _local_dir;}
214 void setUseSvn(bool use_svn) { _use_svn = use_svn;}
215 void setAllowedErrorCount(int errors) {_allowed_errors = errors;}
217 void setCachePath(const SGPath& p) {_persistentCachePath = p;}
218 void setCacheHits(unsigned int hits) {_cache_hits = hits;}
219 void setUseBuiltin(bool built_in) { _use_built_in = built_in;}
221 volatile bool _active;
222 volatile bool _running;
224 volatile bool _stalled;
225 volatile int _fail_count;
226 volatile int _updated_tile_count;
227 volatile int _success_count;
228 volatile int _consecutive_errors;
229 volatile int _allowed_errors;
230 volatile int _cache_hits;
231 volatile int _transfer_rate;
235 // external model run and helpers
237 void syncPathExternal(const WaitingSyncItem& next);
238 bool runExternalSyncCommand(const char* dir);
240 // internal mode run and helpers
242 void updateSyncSlot(SyncSlot& slot);
244 // commond helpers between both internal and external models
246 bool isPathCached(const WaitingSyncItem& next) const;
247 void initCompletedTilesPersistentCache();
248 void writeCompletedTilesPersistentCache() const;
249 void updated(const WaitingSyncItem& item, bool isNewDirectory);
250 void fail(const WaitingSyncItem& failedItem);
254 SyncSlot _syncSlots[NUM_SYNC_SLOTS];
256 volatile bool _is_dirty;
258 SGBlockingDeque <WaitingSyncItem> waitingTiles;
259 CompletedTiles _completedTiles;
260 SGBlockingDeque <WaitingSyncItem> _freshTiles;
264 string _rsync_server;
266 SGPath _persistentCachePath;
269 SGTerraSync::SvnThread::SvnThread() :
275 _updated_tile_count(0),
277 _consecutive_errors(0),
288 void SGTerraSync::SvnThread::stop()
290 // drop any pending requests
291 waitingTiles.clear();
296 // set stop flag and wake up the thread with an empty request
298 WaitingSyncItem w(string(), WaitingSyncItem::Stop);
304 bool SGTerraSync::SvnThread::start()
311 SG_LOG(SG_TERRAIN,SG_ALERT,
312 "Cannot start scenery download. Local cache directory is undefined.");
318 SGPath path(_local_dir);
321 SG_LOG(SG_TERRAIN,SG_ALERT,
322 "Cannot start scenery download. Directory '" << _local_dir <<
323 "' does not exist. Set correct directory path or create directory folder.");
329 path.append("version");
332 SG_LOG(SG_TERRAIN,SG_ALERT,
333 "Cannot start scenery download. Directory '" << _local_dir <<
334 "' contains the base package. Use a separate directory.");
340 _use_svn |= _use_built_in;
342 if ((_use_svn)&&(_svn_server==""))
344 SG_LOG(SG_TERRAIN,SG_ALERT,
345 "Cannot start scenery download. Subversion scenery server is undefined.");
350 if ((!_use_svn)&&(_rsync_server==""))
352 SG_LOG(SG_TERRAIN,SG_ALERT,
353 "Cannot start scenery download. Rsync scenery server is undefined.");
360 _updated_tile_count = 0;
362 _consecutive_errors = 0;
369 if (_use_svn && _use_built_in)
370 status = "Using built-in SVN support. ";
373 status = "Using external SVN utility '";
374 status += _svn_command;
379 status = "Using RSYNC. ";
382 // not really an alert - but we want to (always) see this message, so user is
383 // aware we're downloading scenery (and using bandwidth).
384 SG_LOG(SG_TERRAIN,SG_ALERT,
385 "Starting automatic scenery download/synchronization. "
387 << "Directory: '" << _local_dir << "'.");
393 bool SGTerraSync::SvnThread::runExternalSyncCommand(const char* dir)
396 SGPath localPath( _local_dir );
397 localPath.append( dir );
401 buf << "\"" << _svn_command << "\" "
402 << svn_options << " "
403 << "\"" << _svn_server << "/" << dir << "\" "
404 << "\"" << localPath.str_native() << "\"";
406 buf << rsync_cmd << " "
407 << "\"" << _rsync_server << "/" << dir << "/\" "
408 << "\"" << localPath.str_native() << "/\"";
413 // windows command line parsing is just lovely...
414 // to allow white spaces, the system call needs this:
415 // ""C:\Program Files\something.exe" somearg "some other arg""
416 // Note: whitespace strings quoted by a pair of "" _and_ the
417 // entire string needs to be wrapped by "" too.
418 // The svn url needs forward slashes (/) as a path separator while
419 // the local path needs windows-native backslash as a path separator.
420 command = "\"" + buf.str() + "\"";
424 SG_LOG(SG_TERRAIN,SG_DEBUG, "sync command '" << command << "'");
427 // tbd: does Windows support "popen"?
428 int rc = system( command.c_str() );
430 FILE* pipe = popen( command.c_str(), "r");
432 // wait for external process to finish
439 SG_LOG(SG_TERRAIN,SG_ALERT,
440 "Failed to synchronize directory '" << dir << "', " <<
441 "error code= " << rc);
447 void SGTerraSync::SvnThread::run()
450 initCompletedTilesPersistentCache();
464 void SGTerraSync::SvnThread::runExternal()
468 WaitingSyncItem next = waitingTiles.pop_front();
472 if (isPathCached(next)) {
474 SG_LOG(SG_TERRAIN, SG_DEBUG,
475 "Cache hit for: '" << next._dir << "'");
479 syncPathExternal(next);
481 if ((_allowed_errors >= 0)&&
482 (_consecutive_errors >= _allowed_errors))
487 } // of thread running loop
490 void SGTerraSync::SvnThread::syncPathExternal(const WaitingSyncItem& next)
493 SGPath path( _local_dir );
494 path.append( next._dir );
495 bool isNewDirectory = !path.exists();
498 if (isNewDirectory) {
499 int rc = path.create_dir( 0755 );
501 SG_LOG(SG_TERRAIN,SG_ALERT,
502 "Cannot create directory '" << path << "', return code = " << rc );
503 throw sg_exception("Cannot create directory for terrasync", path.str());
507 if (!runExternalSyncCommand(next._dir.c_str())) {
508 throw sg_exception("Running external sync command failed");
510 } catch (sg_exception& e) {
516 updated(next, isNewDirectory);
520 void SGTerraSync::SvnThread::updateSyncSlot(SyncSlot &slot)
522 if (slot.repository.get()) {
523 if (slot.repository->isDoingSync()) {
525 if (slot.stamp.elapsedMSec() > slot.nextWarnTimeout) {
526 SG_LOG(SG_IO, SG_INFO, "sync taking a long time:" << slot.currentItem._dir << " taken " << slot.stamp.elapsedMSec());
527 SG_LOG(SG_IO, SG_INFO, "HTTP status:" << _http.hasActiveRequests());
528 slot.nextWarnTimeout += 10000;
531 return; // easy, still working
535 SVNRepository::ResultCode res = slot.repository->failure();
536 if (res == SVNRepository::SVN_ERROR_NOT_FOUND) {
537 // this is fine, but maybe we should use a different return code
538 // in the future to higher layers can distinguish this case
539 } else if (res != SVNRepository::SVN_NO_ERROR) {
540 fail(slot.currentItem);
542 updated(slot.currentItem, slot.isNewDirectory);
543 SG_LOG(SG_IO, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " finished ("
544 << slot.stamp.elapsedMSec() << " msec");
547 // whatever happened, we're done with this repository instance
549 slot.repository.reset();
552 // init and start sync of the next repository
553 if (!slot.queue.empty()) {
554 slot.currentItem = slot.queue.front();
557 SGPath path(_local_dir);
558 path.append(slot.currentItem._dir);
559 slot.isNewDirectory = !path.exists();
560 if (slot.isNewDirectory) {
561 int rc = path.create_dir( 0755 );
563 SG_LOG(SG_TERRAIN,SG_ALERT,
564 "Cannot create directory '" << path << "', return code = " << rc );
565 fail(slot.currentItem);
568 } // of creating directory step
570 slot.repository.reset(new SVNRepository(path, &_http));
571 slot.repository->setBaseUrl(_svn_server + "/" + slot.currentItem._dir);
572 slot.repository->update();
574 slot.nextWarnTimeout = 20000;
577 SG_LOG(SG_IO, SG_DEBUG, "sync of " << slot.repository->baseUrl() << " started, queue size is " << slot.queue.size());
581 void SGTerraSync::SvnThread::runInternal()
585 _transfer_rate = _http.transferRateBytesPerSec();
589 // drain the waiting tiles queue into the sync slot queues.
590 while (!waitingTiles.empty()) {
591 WaitingSyncItem next = waitingTiles.pop_front();
592 if (isPathCached(next)) {
594 SG_LOG(SG_TERRAIN, SG_DEBUG,
595 "Cache hit for: '" << next._dir << "'");
599 unsigned int slot = syncSlotForType(next._type);
600 _syncSlots[slot].queue.push(next);
603 bool anySlotBusy = false;
604 // update each sync slot in turn
605 for (unsigned int slot=0; slot < NUM_SYNC_SLOTS; ++slot) {
606 updateSyncSlot(_syncSlots[slot]);
607 anySlotBusy |= _syncSlots[slot].busy;
611 } // of thread running loop
614 bool SGTerraSync::SvnThread::isPathCached(const WaitingSyncItem& next) const
616 CompletedTiles::const_iterator ii = _completedTiles.find( next._dir );
617 if (ii == _completedTiles.end()) {
621 // check if the path still physically exists
622 SGPath p(_local_dir);
628 time_t now = time(0);
629 return (ii->second > now);
632 void SGTerraSync::SvnThread::fail(const WaitingSyncItem& failedItem)
634 time_t now = time(0);
635 _consecutive_errors++;
637 _completedTiles[ failedItem._dir ] = now + UpdateInterval::FailedAttempt;
640 void SGTerraSync::SvnThread::updated(const WaitingSyncItem& item, bool isNewDirectory)
642 time_t now = time(0);
643 _consecutive_errors = 0;
645 SG_LOG(SG_TERRAIN,SG_INFO,
646 "Successfully synchronized directory '" << item._dir << "'");
647 if (item._refreshScenery) {
649 _updated_tile_count++;
652 // for now only report new directories to refresh display
653 // (i.e. only when ocean needs to be replaced with actual data)
654 _freshTiles.push_back(item);
659 _completedTiles[ item._dir ] = now + UpdateInterval::SuccessfulAttempt;
660 writeCompletedTilesPersistentCache();
663 void SGTerraSync::SvnThread::initCompletedTilesPersistentCache()
665 if (!_persistentCachePath.exists()) {
669 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
670 time_t now = time(0);
672 readProperties(_persistentCachePath.str(), cacheRoot);
673 for (int i=0; i<cacheRoot->nChildren(); ++i) {
674 SGPropertyNode* entry = cacheRoot->getChild(i);
675 string tileName = entry->getStringValue("path");
676 time_t stamp = entry->getIntValue("stamp");
681 _completedTiles[tileName] = stamp;
685 void SGTerraSync::SvnThread::writeCompletedTilesPersistentCache() const
688 if (_persistentCachePath.isNull()) {
692 std::ofstream f(_persistentCachePath.c_str(), std::ios::trunc);
697 SGPropertyNode_ptr cacheRoot(new SGPropertyNode);
698 CompletedTiles::const_iterator it = _completedTiles.begin();
699 for (; it != _completedTiles.end(); ++it) {
700 SGPropertyNode* entry = cacheRoot->addChild("entry");
701 entry->setStringValue("path", it->first);
702 entry->setIntValue("stamp", it->second);
705 writeProperties(f, cacheRoot, true /* write_all */);
709 ///////////////////////////////////////////////////////////////////////////////
710 // SGTerraSync ////////////////////////////////////////////////////////////////
711 ///////////////////////////////////////////////////////////////////////////////
712 SGTerraSync::SGTerraSync(SGPropertyNode_ptr root) :
716 _terraRoot(root->getNode("/sim/terrasync",true)),
722 _svnThread = new SvnThread();
723 _log = new BufferedLogCallback(SG_TERRAIN, SG_INFO);
724 _log->truncateAt(255);
726 sglog().addCallback(_log);
729 SGTerraSync::~SGTerraSync()
731 _tiedProperties.Untie();
734 sglog().removeCallback(_log);
738 void SGTerraSync::init()
745 _refreshDisplay = _terraRoot->getNode("refresh-display",true);
746 _terraRoot->setBoolValue("built-in-svn-available",svn_built_in_available);
751 void SGTerraSync::reinit()
753 // do not reinit when enabled and we're already up and running
754 if ((_terraRoot->getBoolValue("enabled",false))&&
755 (_svnThread->_active && _svnThread->_running))
762 if (_terraRoot->getBoolValue("enabled",false))
764 _svnThread->setSvnServer(_terraRoot->getStringValue("svn-server",""));
765 _svnThread->setRsyncServer(_terraRoot->getStringValue("rsync-server",""));
766 _svnThread->setLocalDir(_terraRoot->getStringValue("scenery-dir",""));
767 _svnThread->setAllowedErrorCount(_terraRoot->getIntValue("max-errors",5));
768 _svnThread->setUseBuiltin(_terraRoot->getBoolValue("use-built-in-svn",true));
769 _svnThread->setCachePath(SGPath(_terraRoot->getStringValue("cache-path","")));
770 _svnThread->setCacheHits(_terraRoot->getIntValue("cache-hit", 0));
771 _svnThread->setUseSvn(_terraRoot->getBoolValue("use-svn",true));
772 _svnThread->setExtSvnUtility(_terraRoot->getStringValue("ext-svn-utility","svn"));
774 if (_svnThread->start())
776 syncAirportsModels();
777 if (last_lat != NOWHERE && last_lon != NOWHERE)
779 // reschedule most recent position
784 schedulePosition(lat, lon);
789 _stalledNode->setBoolValue(_svnThread->_stalled);
792 void SGTerraSync::bind()
799 _tiedProperties.Tie( _terraRoot->getNode("busy", true), (bool*) &_svnThread->_busy );
800 _tiedProperties.Tie( _terraRoot->getNode("active", true), (bool*) &_svnThread->_active );
801 _tiedProperties.Tie( _terraRoot->getNode("update-count", true), (int*) &_svnThread->_success_count );
802 _tiedProperties.Tie( _terraRoot->getNode("error-count", true), (int*) &_svnThread->_fail_count );
803 _tiedProperties.Tie( _terraRoot->getNode("tile-count", true), (int*) &_svnThread->_updated_tile_count );
804 _tiedProperties.Tie( _terraRoot->getNode("cache-hits", true), (int*) &_svnThread->_cache_hits );
805 _tiedProperties.Tie( _terraRoot->getNode("transfer-rate-bytes-sec", true), (int*) &_svnThread->_transfer_rate );
807 _terraRoot->getNode("busy", true)->setAttribute(SGPropertyNode::WRITE,false);
808 _terraRoot->getNode("active", true)->setAttribute(SGPropertyNode::WRITE,false);
809 _terraRoot->getNode("update-count", true)->setAttribute(SGPropertyNode::WRITE,false);
810 _terraRoot->getNode("error-count", true)->setAttribute(SGPropertyNode::WRITE,false);
811 _terraRoot->getNode("tile-count", true)->setAttribute(SGPropertyNode::WRITE,false);
812 _terraRoot->getNode("use-built-in-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
813 _terraRoot->getNode("use-svn", true)->setAttribute(SGPropertyNode::USERARCHIVE,false);
814 // stalled is used as a signal handler (to connect listeners triggering GUI pop-ups)
815 _stalledNode = _terraRoot->getNode("stalled", true);
816 _stalledNode->setBoolValue(_svnThread->_stalled);
817 _stalledNode->setAttribute(SGPropertyNode::PRESERVE,true);
820 void SGTerraSync::unbind()
823 _tiedProperties.Untie();
828 void SGTerraSync::update(double)
830 static SGBucket bucket;
831 if (_svnThread->isDirty())
833 if (!_svnThread->_active)
835 if (_svnThread->_stalled)
837 SG_LOG(SG_TERRAIN,SG_ALERT,
838 "Automatic scenery download/synchronization stalled. Too many errors.");
842 // not really an alert - just always show this message
843 SG_LOG(SG_TERRAIN,SG_ALERT,
844 "Automatic scenery download/synchronization has stopped.");
846 _stalledNode->setBoolValue(_svnThread->_stalled);
849 if (!_refreshDisplay->getBoolValue())
852 while (_svnThread->hasNewTiles())
854 WaitingSyncItem next = _svnThread->getNewTile();
855 if (next._refreshScenery)
857 refreshScenery(_svnThread->getLocalDir(),next._dir);
863 void SGTerraSync::refreshScenery(SGPath path,const string& relativeDir)
865 // find tiles to be refreshed
868 path.append(relativeDir);
871 simgear::Dir dir(path);
872 //TODO need to be smarter here. only update tiles which actually
873 // changed recently. May also be possible to use information from the
874 // built-in SVN client directly (instead of checking directory contents).
875 PathList tileList = dir.children(simgear::Dir::TYPE_FILE, ".stg");
876 for (unsigned int i=0; i<tileList.size(); ++i)
878 // reload scenery tile
879 long index = atoi(tileList[i].file().c_str());
880 _refreshCb(_userCbData, index);
886 bool SGTerraSync::isIdle() {return _svnThread->isIdle();}
888 void SGTerraSync::setTileRefreshCb(SGTerraSyncCallback refreshCb, void* userCbData)
890 _refreshCb = refreshCb;
891 _userCbData = userCbData;
894 void SGTerraSync::syncAirportsModels()
896 static const char* bounds = "MZAJKL"; // airport sync order: K-L, A-J, M-Z
897 // note "request" method uses LIFO order, i.e. processes most recent request first
898 for( unsigned i = 0; i < strlen(bounds)/2; i++ )
900 for ( char synced_other = bounds[2*i]; synced_other <= bounds[2*i+1]; synced_other++ )
903 dir << "Airports/" << synced_other;
904 WaitingSyncItem w(dir.str(), WaitingSyncItem::AirportData);
905 _svnThread->request( w );
909 WaitingSyncItem w("Models", WaitingSyncItem::SharedModels);
910 _svnThread->request( w );
914 void SGTerraSync::syncArea( int lat, int lon )
916 if ( lat < -90 || lat > 90 || lon < -180 || lon > 180 )
919 int baselat, baselon;
922 int base = (int)(lat / 10);
923 if ( lat == base * 10 ) {
926 baselat = (base - 1) * 10;
930 baselat = (int)(lat / 10) * 10;
934 int base = (int)(lon / 10);
935 if ( lon == base * 10 ) {
938 baselon = (base - 1) * 10;
942 baselon = (int)(lon / 10) * 10;
946 const char* terrainobjects[3] = { "Terrain", "Objects", 0 };
948 for (const char** tree = &terrainobjects[0]; *tree; tree++)
951 dir << *tree << "/" << setfill('0')
952 << EW << setw(3) << abs(baselon) << NS << setw(2) << abs(baselat) << "/"
953 << EW << setw(3) << abs(lon) << NS << setw(2) << abs(lat);
955 WaitingSyncItem w(dir.str(), WaitingSyncItem::Tile);
960 _svnThread->request( w );
966 void SGTerraSync::syncAreas( int lat, int lon, int lat_dir, int lon_dir )
968 if ( lat_dir == 0 && lon_dir == 0 ) {
969 // do surrounding 8 1x1 degree areas.
970 for ( int i = lat - 1; i <= lat + 1; ++i ) {
971 for ( int j = lon - 1; j <= lon + 1; ++j ) {
972 if ( i != lat || j != lon ) {
978 if ( lat_dir != 0 ) {
979 syncArea( lat + lat_dir, lon - 1 );
980 syncArea( lat + lat_dir, lon + 1 );
981 syncArea( lat + lat_dir, lon );
983 if ( lon_dir != 0 ) {
984 syncArea( lat - 1, lon + lon_dir );
985 syncArea( lat + 1, lon + lon_dir );
986 syncArea( lat, lon + lon_dir );
990 // do current 1x1 degree area first
991 syncArea( lat, lon );
995 bool SGTerraSync::schedulePosition(int lat, int lon)
999 // Ignore messages where the location does not change
1000 if ( lat != last_lat || lon != last_lon )
1002 if (_svnThread->_running)
1004 SG_LOG(SG_TERRAIN,SG_DEBUG, "Requesting scenery update for position " <<
1008 if ( last_lat != NOWHERE && last_lon != NOWHERE )
1010 int dist = lat - last_lat;
1013 lat_dir = dist / abs(dist);
1019 dist = lon - last_lon;
1022 lon_dir = dist / abs(dist);
1029 SG_LOG(SG_TERRAIN,SG_DEBUG, "Scenery update for " <<
1030 "lat = " << lat << ", lon = " << lon <<
1031 ", lat_dir = " << lat_dir << ", " <<
1032 "lon_dir = " << lon_dir);
1034 syncAreas( lat, lon, lat_dir, lon_dir );