Cuberite
A lightweight, fast and extensible game server for Minecraft
ChunkSender.cpp
Go to the documentation of this file.
1 
2 // ChunkSender.cpp
3 
4 // Interfaces to the cChunkSender class representing the thread that waits for chunks becoming ready (loaded / generated) and sends them to clients
5 
6 
7 
8 
9 
10 #include "Globals.h"
11 #include "ChunkSender.h"
12 #include "World.h"
14 #include "ClientHandle.h"
15 #include "Chunk.h"
16 
17 
18 
19 
20 
22 // cNotifyChunkSender:
23 
24 
27  public cChunkCoordCallback
28 {
29  virtual void Call(cChunkCoords a_Coords, bool a_IsSuccess) override
30  {
31  cChunkSender & ChunkSender = m_ChunkSender;
33  a_Coords.m_ChunkX, a_Coords.m_ChunkZ,
34  [&ChunkSender] (cChunk & a_Chunk) -> bool
35  {
36  ChunkSender.QueueSendChunkTo(a_Chunk.GetPosX(), a_Chunk.GetPosZ(), cChunkSender::Priority::High, a_Chunk.GetAllClients());
37  return true;
38  }
39  );
40  }
41 
43 
45 
46 public:
47  cNotifyChunkSender(cChunkSender & a_ChunkSender, cWorld & a_World):
48  m_ChunkSender(a_ChunkSender),
49  m_World(a_World)
50  {
51  }
52 };
53 
54 
55 
56 
57 
59 // cChunkSender:
60 
62  Super("Chunk Sender"),
63  m_World(a_World),
64  m_Serializer(m_World.GetDimension())
65 {
66 }
67 
68 
69 
70 
71 
73 {
74  Stop();
75 }
76 
77 
78 
79 
80 
82 {
83  m_ShouldTerminate = true;
84  m_evtQueue.Set();
85  Super::Stop();
86 }
87 
88 
89 
90 
91 
92 void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, Priority a_Priority, cClientHandle * a_Client)
93 {
94  ASSERT(a_Client != nullptr);
95  {
96  cChunkCoords Chunk{a_ChunkX, a_ChunkZ};
97  cCSLock Lock(m_CS);
98  auto iter = m_ChunkInfo.find(Chunk);
99  if (iter != m_ChunkInfo.end())
100  {
101  auto & info = iter->second;
102  if (info.m_Priority < a_Priority) // Was the chunk's priority boosted?
103  {
104  m_SendChunks.push(sChunkQueue{a_Priority, Chunk});
105  info.m_Priority = a_Priority;
106  }
107  info.m_Clients.insert(a_Client->shared_from_this());
108  }
109  else
110  {
111  m_SendChunks.push(sChunkQueue{a_Priority, Chunk});
112  auto info = sSendChunk{Chunk, a_Priority};
113  info.m_Clients.insert(a_Client->shared_from_this());
114  m_ChunkInfo.emplace(Chunk, info);
115  }
116  }
117  m_evtQueue.Set();
118 }
119 
120 
121 
122 
123 
124 void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, Priority a_Priority, const std::vector<cClientHandle *> & a_Clients)
125 {
126  {
127  cChunkCoords Chunk{a_ChunkX, a_ChunkZ};
128  cCSLock Lock(m_CS);
129  auto iter = m_ChunkInfo.find(Chunk);
130  if (iter != m_ChunkInfo.end())
131  {
132  auto & info = iter->second;
133  if (info.m_Priority < a_Priority) // Was the chunk's priority boosted?
134  {
135  m_SendChunks.push(sChunkQueue{a_Priority, Chunk});
136  info.m_Priority = a_Priority;
137  }
138  for (const auto & Client : a_Clients)
139  {
140  info.m_Clients.insert(Client->shared_from_this());
141  }
142  }
143  else
144  {
145  m_SendChunks.push(sChunkQueue{a_Priority, Chunk});
146  auto info = sSendChunk{Chunk, a_Priority};
147  for (const auto & Client : a_Clients)
148  {
149  info.m_Clients.insert(Client->shared_from_this());
150  }
151  m_ChunkInfo.emplace(Chunk, info);
152  }
153  }
154  m_evtQueue.Set();
155 }
156 
157 
158 
159 
160 
162 {
163  while (!m_ShouldTerminate)
164  {
165  m_evtQueue.Wait();
166 
167  {
168  cCSLock Lock(m_CS);
169  while (!m_SendChunks.empty())
170  {
171  // Take one from the queue:
172  auto Chunk = m_SendChunks.top().m_Chunk;
173  m_SendChunks.pop();
174  auto itr = m_ChunkInfo.find(Chunk);
175  if (itr == m_ChunkInfo.end())
176  {
177  continue;
178  }
179 
180  auto clients = std::move(itr->second.m_Clients);
181  m_ChunkInfo.erase(itr);
182 
183  cCSUnlock Unlock(Lock);
184  SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, clients);
185  }
186  }
187  } // while (!m_ShouldTerminate)
188 }
189 
190 
191 
192 
193 
194 void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, const WeakClients & a_Clients)
195 {
196  // Contains strong pointers to clienthandles.
197  std::vector<std::shared_ptr<cClientHandle>> Clients;
198 
199  // Ask the client if it still wants the chunk:
200  for (const auto & WeakClient : a_Clients)
201  {
202  auto Client = WeakClient.lock();
203  if ((Client != nullptr) && Client->WantsSendChunk(a_ChunkX, a_ChunkZ))
204  {
205  Clients.push_back(std::move(Client));
206  }
207  }
208 
209  // Bail early if every requester disconnected:
210  if (Clients.empty())
211  {
212  return;
213  }
214 
215  // If the chunk has no clients, no need to packetize it:
216  if (!m_World.HasChunkAnyClients(a_ChunkX, a_ChunkZ))
217  {
218  return;
219  }
220 
221  // If the chunk is not valid, do nothing - whoever needs it has queued it for loading / generating
222  if (!m_World.IsChunkValid(a_ChunkX, a_ChunkZ))
223  {
224  return;
225  }
226 
227  // If the chunk is not lighted, queue it for relighting and get notified when it's ready:
228  if (!m_World.IsChunkLighted(a_ChunkX, a_ChunkZ))
229  {
230  m_World.QueueLightChunk(a_ChunkX, a_ChunkZ, std::make_unique<cNotifyChunkSender>(*this, m_World));
231  return;
232  }
233 
234  // Query and prepare chunk data:
235  if (!m_World.GetChunkData({a_ChunkX, a_ChunkZ}, *this))
236  {
237  return;
238  }
239 
240  // Send:
241  m_Serializer.SendToClients(a_ChunkX, a_ChunkZ, m_BlockData, m_LightData, m_BiomeMap, Clients);
242 
243  for (const auto & Client : Clients)
244  {
245  // Send block-entity packets:
246  for (const auto & Pos : m_BlockEntities)
247  {
248  m_World.SendBlockEntity(Pos.x, Pos.y, Pos.z, *Client);
249  } // for itr - m_Packets[]
250 
251  // Send entity packets:
252  for (const auto EntityID : m_EntityIDs)
253  {
254  m_World.DoWithEntityByID(EntityID, [Client](cEntity & a_Entity)
255  {
256  /*
257  // DEBUG:
258  LOGD("cChunkSender: Entity #%d (%s) at [%f, %f, %f] spawning for player \"%s\"",
259  a_Entity.GetUniqueID(), a_Entity.GetClass(),
260  a_Entity.GetPosition().x, a_Entity.GetPosition().y, a_Entity.GetPosition().z,
261  Client->GetUsername().c_str()
262  );
263  */
264 
265  /* This check looks highly suspect.
266  Its purpose is to check the client still has a valid player object associated,
267  since the player destroys itself when the client is destroyed.
268  It's done within the world lock to ensure correctness.
269  A better way involves fixing chunk sending (GH #3696) to obviate calling SpawnOn from this thread in the first place. */
270  if (!Client->IsDestroyed())
271  {
272  a_Entity.SpawnOn(*Client);
273  }
274 
275  return true;
276  });
277  }
278  }
279 
280  m_BlockEntities.clear();
281  m_EntityIDs.clear();
282 }
283 
284 
285 
286 
287 
289 {
290  m_BlockEntities.push_back(a_Entity->GetPos());
291 }
292 
293 
294 
295 
296 
298 {
299  m_EntityIDs.push_back(a_Entity->GetUniqueID());
300 }
301 
302 
303 
304 
305 
307 {
308  for (size_t i = 0; i < ARRAYCOUNT(m_BiomeMap); i++)
309  {
310  if (a_BiomeMap[i] < 255)
311  {
312  // Normal MC biome, copy as-is:
313  m_BiomeMap[i] = static_cast<unsigned char>(a_BiomeMap[i]);
314  }
315  else
316  {
317  // TODO: MCS-specific biome, need to map to some basic MC biome:
318  ASSERT(!"Unimplemented MCS-specific biome");
319  }
320  } // for i - m_BiomeMap[]
321 }
#define ARRAYCOUNT(X)
Evaluates to the number of elements in an array (compile-time!)
Definition: Globals.h:231
#define ASSERT(x)
Definition: Globals.h:276
Vector3i GetPos() const
Definition: BlockEntity.h:90
Definition: Chunk.h:36
Wraps the chunk coords into a single structure.
Definition: ChunkDef.h:57
int m_ChunkZ
Definition: ChunkDef.h:60
int m_ChunkX
Definition: ChunkDef.h:59
EMCSBiome BiomeMap[Width *Width]
The type used for any biomemap operations and storage inside Cuberite, using Cuberite biomes (need no...
Definition: ChunkDef.h:137
Interface class used as a callback for operations that involve chunk coords.
Definition: ChunkDef.h:467
Callback that can be used to notify chunk sender upon another chunkcoord notification.
Definition: ChunkSender.cpp:28
cChunkSender & m_ChunkSender
Definition: ChunkSender.cpp:42
cNotifyChunkSender(cChunkSender &a_ChunkSender, cWorld &a_World)
Definition: ChunkSender.cpp:47
virtual void Call(cChunkCoords a_Coords, bool a_IsSuccess) override
Called with the chunk's coords, and an optional operation status flag for operations that support it.
Definition: ChunkSender.cpp:29
virtual void BiomeMap(const cChunkDef::BiomeMap &a_BiomeMap) override
unsigned char m_BiomeMap[cChunkDef::Width *cChunkDef::Width]
Definition: ChunkSender.h:119
virtual void BlockEntity(cBlockEntity *a_Entity) override
virtual void Execute(void) override
This function, overloaded by the descendants, is called in the new thread.
std::set< std::weak_ptr< cClientHandle >, std::owner_less< std::weak_ptr< cClientHandle > >> WeakClients
Definition: ChunkSender.h:79
virtual ~cChunkSender() override
Definition: ChunkSender.cpp:72
void QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, Priority a_Priority, cClientHandle *a_Client)
Queues a chunk to be sent to a specific client.
Definition: ChunkSender.cpp:92
cCriticalSection m_CS
Definition: ChunkSender.h:112
void SendChunk(int a_ChunkX, int a_ChunkZ, const WeakClients &a_Clients)
Sends the specified chunk to all the specified clients.
std::vector< UInt32 > m_EntityIDs
Definition: ChunkSender.h:121
cChunkSender(cWorld &a_World)
Definition: ChunkSender.cpp:61
cChunkDataSerializer m_Serializer
An instance of a chunk serializer, held to maintain its internal cache.
Definition: ChunkSender.h:110
std::priority_queue< sChunkQueue > m_SendChunks
Definition: ChunkSender.h:113
std::unordered_map< cChunkCoords, sSendChunk, cChunkCoordsHash > m_ChunkInfo
Definition: ChunkSender.h:114
Priority
Tag indicating urgency of chunk to be sent.
Definition: ChunkSender.h:64
std::vector< Vector3i > m_BlockEntities
Definition: ChunkSender.h:120
cEvent m_evtQueue
Definition: ChunkSender.h:115
cWorld & m_World
Definition: ChunkSender.h:107
void Stop(void)
Definition: ChunkSender.cpp:81
virtual void Entity(cEntity *a_Entity) override
Used for sending chunks to specific clients.
Definition: ChunkSender.h:96
Definition: Entity.h:76
UInt32 GetUniqueID(void) const
Definition: Entity.h:253
RAII for cCriticalSection - locks the CS on creation, unlocks on destruction.
Temporary RAII unlock for a cCSLock.
void Wait(void)
Waits until the event has been set.
Definition: Event.cpp:23
void Set(void)
Sets the event - releases one thread that has been waiting in Wait().
Definition: Event.cpp:52
std::atomic< bool > m_ShouldTerminate
The overriden Execute() method should check this value periodically and terminate if this is true.
Definition: IsThread.h:45
void Stop(void)
Signals the thread to terminate and waits until it's finished.
Definition: IsThread.cpp:48
void SendToClients(int a_ChunkX, int a_ChunkZ, const ChunkBlockData &a_BlockData, const ChunkLightData &a_LightData, const unsigned char *a_BiomeMap, const ClientHandles &a_SendTo)
For each client, serializes the chunk into their protocol version and sends it.
Definition: World.h:53
void QueueLightChunk(int a_ChunkX, int a_ChunkZ, std::unique_ptr< cChunkCoordCallback > a_Callback={})
Queues a chunk for lighting; a_Callback is called after the chunk is lighted.
Definition: World.cpp:2676
bool DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback a_Callback)
Calls the callback for the chunk specified, with ChunkMapCS locked.
Definition: World.cpp:1451
bool GetChunkData(cChunkCoords a_Coords, cChunkDataCallback &a_Callback) const
Calls the callback with the chunk's data, if available (with ChunkCS locked).
Definition: World.cpp:2202
bool DoWithEntityByID(UInt32 a_UniqueID, cEntityCallback a_Callback)
Calls the callback if the entity with the specified ID is found, with the entity object as the callba...
Definition: World.cpp:2464
void SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle &a_Client)
If there is a block entity at the specified coords, sends it to the client specified.
Definition: World.cpp:2141
bool IsChunkValid(int a_ChunkX, int a_ChunkZ) const
Returns true iff the chunk is present and valid.
Definition: World.cpp:2220
bool HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) const
Definition: World.cpp:2229
bool IsChunkLighted(int a_ChunkX, int a_ChunkZ)
Definition: World.cpp:2685