summaryrefslogtreecommitdiffstats
path: root/source/WorldStorage/WorldStorage.cpp
blob: 8b055b240506dea908051744ab90e0e53857d520 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400

// WorldStorage.cpp

// Implements the cWorldStorage class representing the chunk loading / saving thread

// To add a new storage schema, implement a cWSSchema descendant and add it to cWorldStorage::InitSchemas()

#include "Globals.h"
#include "WorldStorage.h"
#include "WSSCompact.h"
#include "WSSAnvil.h"
#include "../World.h"
#include "../Generating/ChunkGenerator.h"
#include "../Entity.h"
#include "../BlockEntities/BlockEntity.h"





/// If a chunk with this Y coord is de-queued, it is a signal to emit the saved-all message (cWorldStorage::QueueSavedMessage())
#define CHUNK_Y_MESSAGE 2





/// Example storage schema - forgets all chunks ;)
class cWSSForgetful :
	public cWSSchema
{
public:
	cWSSForgetful(cWorld * a_World) : cWSSchema(a_World) {}
	
protected:
	// cWSSchema overrides:
	virtual bool LoadChunk(const cChunkCoords & a_Chunk) override {return false; }
	virtual bool SaveChunk(const cChunkCoords & a_Chunk) override {return true; }
	virtual const AString GetName(void) const override {return "forgetful"; }
} ;





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cWorldStorage:

cWorldStorage::cWorldStorage(void) :
	super("cWorldStorage"),
	m_World(NULL),
	m_SaveSchema(NULL)
{
}





cWorldStorage::~cWorldStorage()
{
	for (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)
	{
		delete *itr;
	}  // for itr - m_Schemas[]
	m_LoadQueue.clear();
	m_SaveQueue.clear();
}





bool cWorldStorage::Start(cWorld * a_World, const AString & a_StorageSchemaName)
{
	m_World = a_World;
	m_StorageSchemaName = a_StorageSchemaName;
	InitSchemas();
	
	return super::Start();
}





void cWorldStorage::WaitForFinish(void)
{
	LOG("Waiting for the world storage to finish saving");
	
	{
		// Cancel all loading requests:
		cCSLock Lock(m_CSQueues);
		m_LoadQueue.clear();
	}
	
	// Wait for the saving to finish:
	WaitForQueuesEmpty();
	
	// Wait for the thread to finish:
	m_ShouldTerminate = true;
	m_Event.Set();
	m_evtRemoved.Set();  // Wake up anybody waiting in the WaitForQueuesEmpty() method
	super::Wait();
	LOG("World storage thread finished");
}





void cWorldStorage::WaitForQueuesEmpty(void)
{
	cCSLock Lock(m_CSQueues);
	while (!m_ShouldTerminate && (!m_LoadQueue.empty() || !m_SaveQueue.empty()))
	{
		cCSUnlock Unlock(Lock);
		m_evtRemoved.Wait();
	}
}





int cWorldStorage::GetLoadQueueLength(void)
{
	cCSLock Lock(m_CSQueues);
	return (int)m_LoadQueue.size();
}





int cWorldStorage::GetSaveQueueLength(void)
{
	cCSLock Lock(m_CSQueues);
	return (int)m_SaveQueue.size();
}





void cWorldStorage::QueueLoadChunk(int a_ChunkX, int a_ChunkY, int a_ChunkZ, bool a_Generate)
{
	// Queues the chunk for loading; if not loaded, the chunk will be generated
	{
		cCSLock Lock(m_CSQueues);
		
		// Check if already in the queue:
		for (sChunkLoadQueue::iterator itr = m_LoadQueue.begin(); itr != m_LoadQueue.end(); ++itr)
		{
			if ((itr->m_ChunkX == a_ChunkX) && (itr->m_ChunkY == a_ChunkY) && (itr->m_ChunkZ == a_ChunkZ) && (itr->m_Generate == a_Generate))
			{
				return;
			}
		}
		m_LoadQueue.push_back(sChunkLoad(a_ChunkX, a_ChunkY, a_ChunkZ, a_Generate));
	}
	
	m_Event.Set();
}





void cWorldStorage::QueueSaveChunk(int a_ChunkX, int a_ChunkY, int a_ChunkZ)
{
	{
		cCSLock Lock(m_CSQueues);
		m_SaveQueue.remove   (cChunkCoords(a_ChunkX, a_ChunkY, a_ChunkZ));  // Don't add twice
		m_SaveQueue.push_back(cChunkCoords(a_ChunkX, a_ChunkY, a_ChunkZ));
	}
	m_Event.Set();
}





void cWorldStorage::QueueSavedMessage(void)
{
	// Pushes a special coord pair into the queue, signalizing a message instead:
	{
		cCSLock Lock(m_CSQueues);
		m_SaveQueue.push_back(cChunkCoords(0, CHUNK_Y_MESSAGE, 0));
	}
	m_Event.Set();
}





void cWorldStorage::UnqueueLoad(int a_ChunkX, int a_ChunkY, int a_ChunkZ)
{
	cCSLock Lock(m_CSQueues);
	for (sChunkLoadQueue::iterator itr = m_LoadQueue.begin(); itr != m_LoadQueue.end(); ++itr)
	{
		if ((itr->m_ChunkX != a_ChunkX) || (itr->m_ChunkY != a_ChunkY) || (itr->m_ChunkZ != a_ChunkZ))
		{
			continue;
		}
		m_LoadQueue.erase(itr);
		Lock.Unlock();
		m_evtRemoved.Set();
		return;
	}  // for itr - m_LoadQueue[]
}





void cWorldStorage::UnqueueSave(const cChunkCoords & a_Chunk)
{
	{
		cCSLock Lock(m_CSQueues);
		m_SaveQueue.remove(a_Chunk);
	}
	m_evtRemoved.Set();
}





void cWorldStorage::InitSchemas(void)
{
	// The first schema added is considered the default
	m_Schemas.push_back(new cWSSAnvil    (m_World));
	m_Schemas.push_back(new cWSSCompact  (m_World));
	m_Schemas.push_back(new cWSSForgetful(m_World));
	// Add new schemas here
	
	if (NoCaseCompare(m_StorageSchemaName, "default") == 0)
	{
		m_SaveSchema = m_Schemas.front();
		return;
	}
	for (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)
	{
		if (NoCaseCompare((*itr)->GetName(), m_StorageSchemaName) == 0)
		{
			m_SaveSchema = *itr;
			return;
		}
	}  // for itr - m_Schemas[]
	
	// Unknown schema selected, let the admin know:
	LOGWARNING("Unknown storage schema name \"%s\". Using default (\"%s\"). Available schemas:", 
		m_StorageSchemaName.c_str(), m_SaveSchema->GetName().c_str()
	);
	for (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)
	{
		LOGWARNING("\t\"%s\"", (*itr)->GetName().c_str());
	}
	m_SaveSchema = m_Schemas.front();
}





void cWorldStorage::Execute(void)
{
	while (!m_ShouldTerminate)
	{
		m_Event.Wait();
		
		// Process both queues until they are empty again:
		bool HasMore;
		do
		{
			HasMore = false;
			if (m_ShouldTerminate)
			{
				return;
			}
			
			HasMore = LoadOneChunk();
			HasMore = HasMore | SaveOneChunk();
			m_evtRemoved.Set();
		} while (HasMore);
	}
}





bool cWorldStorage::LoadOneChunk(void)
{
	sChunkLoad ToLoad(0, 0, 0, false);
	bool HasMore;
	bool ShouldLoad = false;
	{
		cCSLock Lock(m_CSQueues);
		if (!m_LoadQueue.empty())
		{
			ToLoad = m_LoadQueue.front();
			m_LoadQueue.pop_front();
			ShouldLoad = true;
		}
		HasMore = !m_LoadQueue.empty();
	}
	
	if (ShouldLoad && !LoadChunk(ToLoad.m_ChunkX, ToLoad.m_ChunkY, ToLoad.m_ChunkZ))
	{
		if (ToLoad.m_Generate)
		{
			// The chunk couldn't be loaded, generate it:
			m_World->GetGenerator().QueueGenerateChunk(ToLoad.m_ChunkX, ToLoad.m_ChunkY, ToLoad.m_ChunkZ);
		}
		else
		{
			// TODO: Notify the world that the load has failed:
			// m_World->ChunkLoadFailed(ToLoad.m_ChunkX, ToLoad.m_ChunkY, ToLoad.m_ChunkZ);
		}
	}
	return HasMore;
}





bool cWorldStorage::SaveOneChunk(void)
{
	cChunkCoords Save(0, 0, 0);
	bool HasMore;
	bool ShouldSave = false;
	{
		cCSLock Lock(m_CSQueues);
		if (!m_SaveQueue.empty())
		{
			Save = m_SaveQueue.front();
			m_SaveQueue.pop_front();
			ShouldSave = true;
		}
		HasMore = !m_SaveQueue.empty();
	}
	if (Save.m_ChunkY == CHUNK_Y_MESSAGE)
	{
		LOGINFO("Saved all chunks in world %s", m_World->GetName().c_str());
		return HasMore;
	}
	if (ShouldSave && m_World->IsChunkValid(Save.m_ChunkX, Save.m_ChunkZ))
	{
		m_World->MarkChunkSaving(Save.m_ChunkX, Save.m_ChunkZ);
		if (m_SaveSchema->SaveChunk(Save))
		{
			m_World->MarkChunkSaved(Save.m_ChunkX, Save.m_ChunkZ);
		}
	}
	return HasMore;
}





bool cWorldStorage::LoadChunk(int a_ChunkX, int a_ChunkY, int a_ChunkZ)
{
	if (m_World->IsChunkValid(a_ChunkX, a_ChunkZ))
	{
		// Already loaded (can happen, since the queue is async)
		return true;
	}
	
	cChunkCoords Coords(a_ChunkX, a_ChunkY, a_ChunkZ);

	// First try the schema that is used for saving
	if (m_SaveSchema->LoadChunk(Coords))
	{
		return true;
	}
	
	// If it didn't have the chunk, try all the other schemas:
	for (cWSSchemaList::iterator itr = m_Schemas.begin(); itr != m_Schemas.end(); ++itr)
	{
		if (((*itr) != m_SaveSchema) && (*itr)->LoadChunk(Coords))
		{
			return true;
		}
	}
	
	// Notify the chunk owner that the chunk failed to load (sets cChunk::m_HasLoadFailed to true):
	m_World->ChunkLoadFailed(a_ChunkX, a_ChunkY, a_ChunkZ);
	
	return false;
}