From 366ecf9dfd38d612c0685f3fbf8b3a95b9900697 Mon Sep 17 00:00:00 2001 From: madmaxoft Date: Tue, 10 Jun 2014 18:25:53 +0200 Subject: [PATCH] Fixed a race condition when adding a player to a world. --- src/ChunkMap.cpp | 24 ++++++++++++++++++++++++ src/ChunkMap.h | 4 ++++ src/World.cpp | 5 +---- 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 0a8164b47..dba6f3f41 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -1665,6 +1665,30 @@ void cChunkMap::AddEntity(cEntity * a_Entity) +void cChunkMap::AddEntityIfNotPresent(cEntity * a_Entity) +{ + cCSLock Lock(m_CSLayers); + cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), ZERO_CHUNK_Y, a_Entity->GetChunkZ()); + if ( + (Chunk == NULL) || // Chunk not present at all + (!Chunk->IsValid() && !a_Entity->IsPlayer()) // Chunk present, but no valid data; players need to spawn in such chunks (#953) + ) + { + LOGWARNING("Entity at %p (%s, ID %d) spawning in a non-existent chunk, the entity is lost.", + a_Entity, a_Entity->GetClass(), a_Entity->GetUniqueID() + ); + return; + } + if (!Chunk->HasEntity(a_Entity->GetUniqueID())) + { + Chunk->AddEntity(a_Entity); + } +} + + + + + bool cChunkMap::HasEntity(int a_UniqueID) { cCSLock Lock(m_CSLayers); diff --git a/src/ChunkMap.h b/src/ChunkMap.h index 8786d7016..7e85bb6f1 100644 --- a/src/ChunkMap.h +++ b/src/ChunkMap.h @@ -199,6 +199,10 @@ public: /** Adds the entity to its appropriate chunk, takes ownership of the entity pointer */ void AddEntity(cEntity * a_Entity); + /** Adds the entity to its appropriate chunk, if the entity is not already added. + Takes ownership of the entity pointer */ + void AddEntityIfNotPresent(cEntity * a_Entity); + /** Returns true if the entity with specified ID is present in the chunks */ bool HasEntity(int a_EntityID); diff --git a/src/World.cpp b/src/World.cpp index ebe6b53e6..6bcd1391a 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -3148,10 +3148,7 @@ void cWorld::AddQueuedPlayers(void) (*itr)->SetWorld(this); // Add to chunkmap, if not already there (Spawn vs MoveToWorld): - if (!m_ChunkMap->HasEntity((*itr)->GetUniqueID())) - { - m_ChunkMap->AddEntity(*itr); - } + m_ChunkMap->AddEntityIfNotPresent(*itr); } // for itr - PlayersToAdd[] } // Lock(m_CSPlayers)