aboutsummaryrefslogtreecommitdiff
path: root/Minecraft.World/McRegionChunkStorage.cpp
blob: 344ff6c7c29c6db1ee197cc88459e4af76a94178 (plain)
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include "stdafx.h"
#include "net.minecraft.world.level.h"
#include "ConsoleSaveFileIO.h"
#include "LevelData.h"
#include "McRegionChunkStorage.h"

CRITICAL_SECTION		McRegionChunkStorage::cs_memory;

std::deque<DataOutputStream *> McRegionChunkStorage::s_chunkDataQueue;
int McRegionChunkStorage::s_runningThreadCount = 0;
C4JThread *McRegionChunkStorage::s_saveThreads[3];


McRegionChunkStorage::McRegionChunkStorage(ConsoleSaveFile *saveFile, const wstring &prefix) : m_prefix( prefix )
{
	m_saveFile = saveFile;

	// Make sure that if there are any files for regions to be created, that they are created in the order that suits us for making the initial level save work fast
	if( prefix == L"" )
	{
		m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.0.0.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM-1r.-1.0.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.0.0.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"DIM1/r.-1.0.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"r.-1.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"r.0.-1.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"r.0.0.mcr"));
		m_saveFile->createFile(ConsoleSavePath(L"r.-1.0.mcr"));
	}


#ifdef SPLIT_SAVES
	ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + wstring( L"entities.dat" ) );

	if(m_saveFile->doesFileExist(currentFile))
	{
		ConsoleSaveFileInputStream fis = ConsoleSaveFileInputStream( m_saveFile, currentFile );
		DataInputStream dis(&fis);

		int count = dis.readInt();

		for(int i = 0; i < count; ++i)
		{
			__int64 index = dis.readLong();
			CompoundTag *tag = NbtIo::read(&dis);

			ByteArrayOutputStream bos;
			DataOutputStream dos(&bos);
			NbtIo::write(tag, &dos);
			delete tag;

			byteArray savedData(bos.size());
			memcpy(savedData.data, bos.buf.data, bos.size());

			m_entityData[index] = savedData;
		}
	}
#endif
}

McRegionChunkStorage::~McRegionChunkStorage()
{
	for(auto& it : m_entityData)
	{
		delete it.second.data;
	}
}

LevelChunk *McRegionChunkStorage::load(Level *level, int x, int z)
{
	DataInputStream *regionChunkInputStream = RegionFileCache::getChunkDataInputStream(m_saveFile, m_prefix, x, z);

#ifdef SPLIT_SAVES
	// If we can't find the chunk in the save file, then we should remove any entities we might have for that chunk
	if(regionChunkInputStream == NULL)
	{
		__int64 index = ((__int64)(x) << 32) | (((__int64)(z))&0x00000000FFFFFFFF);

        auto it = m_entityData.find(index);
        if(it != m_entityData.end())
		{
			delete it->second.data;
			m_entityData.erase(it);
		}
	}
#endif

	LevelChunk *levelChunk = NULL;

	if(m_saveFile->getOriginalSaveVersion() >= SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE)
	{
		if (regionChunkInputStream != NULL)
		{
			MemSect(9);
			levelChunk = OldChunkStorage::load(level, regionChunkInputStream);
			loadEntities(level, levelChunk);
			MemSect(0);
			regionChunkInputStream->deleteChildStream();
			delete regionChunkInputStream;
		}
	}
	else
	{
		CompoundTag *chunkData;
		if (regionChunkInputStream != NULL)
		{
			MemSect(8);
			chunkData = NbtIo::read((DataInput *)regionChunkInputStream);
			MemSect(0);
		} else
		{
			return NULL;
		}

		regionChunkInputStream->deleteChildStream();
		delete regionChunkInputStream;

		if (!chunkData->contains(L"Level"))
		{
			char buf[256];
			sprintf(buf,"Chunk file at %d, %d is missing level data, skipping\n",x, z);
			app.DebugPrintf(buf);
			delete chunkData;
			return NULL;
		}
		if (!chunkData->getCompound(L"Level")->contains(L"Blocks"))
		{
			char buf[256];
			sprintf(buf,"Chunk file at %d, %d is missing block data, skipping\n",x, z);
			app.DebugPrintf(buf);
			delete chunkData;
			return NULL;
		}
		MemSect(9);
		levelChunk = OldChunkStorage::load(level, chunkData->getCompound(L"Level"));
		MemSect(0);
		if (!levelChunk->isAt(x, z))
		{
			char buf[256];
			sprintf(buf,"Chunk file at %d, %d is in the wrong location; relocating. Expected %d, %d, got %d, %d\n",
				x, z, x, z, levelChunk->x, levelChunk->z);
			app.DebugPrintf(buf);
			delete levelChunk;
			delete chunkData;
			return NULL;

			// 4J Stu - We delete the data within OldChunkStorage::load, so we can never reload from it
			//chunkData->putInt(L"xPos", x);
			//chunkData->putInt(L"zPos", z);
			//MemSect(10);
			//levelChunk = OldChunkStorage::load(level, chunkData->getCompound(L"Level"));
			//MemSect(0);
		}
#ifdef SPLIT_SAVES
		loadEntities(level, levelChunk);
#endif
		delete chunkData;
	}
#ifndef _CONTENT_PACKAGE
	if(levelChunk && app.DebugSettingsOn() && app.GetGameSettingsDebugMask(ProfileManager.GetPrimaryPad())&(1L<<eDebugSetting_EnableBiomeOverride))
	{
		// 4J Stu - This will force an update of the chunk's biome array
		levelChunk->reloadBiomes();
	}
#endif
	return levelChunk;

}

void McRegionChunkStorage::save(Level *level, LevelChunk *levelChunk)
{
	level->checkSession();

	// 4J - removed try/catch
//    try {

	// Note - have added use of a critical section round sections of code that do a lot of memory alloc/free operations. This is because
	// when we are running saves on multiple threads these sections have a lot of contention and thrash the memory system's critical sections
	// Better to let each thread have its turn at a higher level of granularity.
	MemSect(30);
	PIXBeginNamedEvent(0,"Getting output stream\n");
	DataOutputStream *output = RegionFileCache::getChunkDataOutputStream(m_saveFile, m_prefix, levelChunk->x, levelChunk->z);
	PIXEndNamedEvent();

	if(m_saveFile->getOriginalSaveVersion() >= SAVE_FILE_VERSION_COMPRESSED_CHUNK_STORAGE)
	{
		PIXBeginNamedEvent(0,"Writing chunk data");
		OldChunkStorage::save(levelChunk, level, output);
		PIXEndNamedEvent();

		PIXBeginNamedEvent(0,"Updating chunk queue");
		EnterCriticalSection(&cs_memory);
		s_chunkDataQueue.push_back(output);
		LeaveCriticalSection(&cs_memory);
		PIXEndNamedEvent();
	}
	else
	{
		EnterCriticalSection(&cs_memory);
		PIXBeginNamedEvent(0,"Creating tags\n");
		CompoundTag *tag = new CompoundTag();
		CompoundTag *levelData = new CompoundTag();
		tag->put(L"Level", levelData);
		OldChunkStorage::save(levelChunk, level, levelData);
		PIXEndNamedEvent();
		PIXBeginNamedEvent(0,"NbtIo writing\n");
		NbtIo::write(tag, output);
		PIXEndNamedEvent();
		LeaveCriticalSection(&cs_memory);
		PIXBeginNamedEvent(0,"Output closing\n");
		output->close();
		PIXEndNamedEvent();


		// 4J Stu - getChunkDataOutputStream makes a new DataOutputStream that points to a new ChunkBuffer( ByteArrayOutputStream )
		// We should clean these up when we are done
		EnterCriticalSection(&cs_memory);
		PIXBeginNamedEvent(0,"Cleaning up\n");
		output->deleteChildStream();
		delete output;
		delete tag;
		LeaveCriticalSection(&cs_memory);
		PIXEndNamedEvent();
	}
	MemSect(0);

	LevelData *levelInfo = level->getLevelData();

	// 4J Stu - Override this with our save file size to stop all the RegionFileCache lookups
	//levelInfo->setSizeOnDisk(levelInfo->getSizeOnDisk() + RegionFileCache::getSizeDelta(m_saveFile, m_prefix, levelChunk->x, levelChunk->z));
	levelInfo->setSizeOnDisk( this->m_saveFile->getSizeOnDisk() );
//    } catch (Exception e) {
//        e.printStackTrace();
//    }
}

void McRegionChunkStorage::saveEntities(Level *level, LevelChunk *levelChunk)
{
#ifdef SPLIT_SAVES
	PIXBeginNamedEvent(0,"Saving entities");
	__int64 index = ((__int64)(levelChunk->x) << 32) | (((__int64)(levelChunk->z))&0x00000000FFFFFFFF);

	delete m_entityData[index].data;

	CompoundTag *newTag = new CompoundTag();
	bool savedEntities = OldChunkStorage::saveEntities(levelChunk, level, newTag);

	if(savedEntities)
	{
		ByteArrayOutputStream bos;
		DataOutputStream dos(&bos);
		NbtIo::write(newTag, &dos);

		byteArray savedData(bos.size());
		memcpy(savedData.data, bos.buf.data, bos.size());

		m_entityData[index] = savedData;
	}
	else
	{
        auto it = m_entityData.find(index);
        if(it != m_entityData.end())
		{
			m_entityData.erase(it);
		}
	}
	delete newTag;
	PIXEndNamedEvent();
#endif
}

void McRegionChunkStorage::loadEntities(Level *level, LevelChunk *levelChunk)
{
#ifdef SPLIT_SAVES
	__int64 index = ((__int64)(levelChunk->x) << 32) | (((__int64)(levelChunk->z))&0x00000000FFFFFFFF);

    auto it = m_entityData.find(index);
    if(it != m_entityData.end())
	{
		ByteArrayInputStream bais(it->second);
		DataInputStream dis(&bais);
		CompoundTag *tag = NbtIo::read(&dis);
		OldChunkStorage::loadEntities(levelChunk, level, tag);
		bais.reset();
		delete tag;
	}
#endif
}

void McRegionChunkStorage::tick()
{
	m_saveFile->tick();
}

void McRegionChunkStorage::flush()
{
#ifdef SPLIT_SAVES
	PIXBeginNamedEvent(0, "Flushing entity data");
	ConsoleSavePath currentFile = ConsoleSavePath( m_prefix + wstring( L"entities.dat" ) );
	ConsoleSaveFileOutputStream fos = ConsoleSaveFileOutputStream( m_saveFile, currentFile );
	BufferedOutputStream bos(&fos, 1024*1024);
	DataOutputStream dos(&bos);

	PIXBeginNamedEvent(0,"Writing to stream");
	dos.writeInt(m_entityData.size());

	for(auto& it : m_entityData)
	{
		dos.writeLong(it.first);
		dos.write(it.second,0,it.second.length);
	}
	bos.flush();
	PIXEndNamedEvent();
	PIXEndNamedEvent();
#endif
}


void McRegionChunkStorage::staticCtor()
{
	InitializeCriticalSectionAndSpinCount(&cs_memory,5120);

	for(unsigned int i = 0; i < 3; ++i)
	{
		char threadName[256];
		sprintf(threadName,"McRegion Save thread %d\n",i);
		SetThreadName(0, threadName);

		//saveThreads[j] = CreateThread(NULL,0,runSaveThreadProc,&threadData[j],CREATE_SUSPENDED,&threadId[j]);
		s_saveThreads[i] = new C4JThread(runSaveThreadProc,NULL,threadName);


		//app.DebugPrintf("Created new thread: %s\n",threadName);

		// Threads 1,3 and 5 are generally idle so use them
		if(i == 0) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_A);
		else if(i == 1)
		{
			s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_B);
#ifdef __ORBIS__
			s_saveThreads[i]->SetPriority(THREAD_PRIORITY_BELOW_NORMAL);	// On Orbis, this core is also used for Matching 2, and that priority of that seems to be always at default no matter what we set it to. Prioritise this below Matching 2.
#endif
		}
		else if(i == 2) s_saveThreads[i]->SetProcessor(CPU_CORE_SAVE_THREAD_C);

		//ResumeThread( saveThreads[j] );
		s_saveThreads[i]->Run();
	}
}

int McRegionChunkStorage::runSaveThreadProc(LPVOID lpParam)
{
	Compression::CreateNewThreadStorage();

	bool running = true;
	size_t lastQueueSize = 0;

	DataOutputStream *dos = NULL;
	while(running)
	{
		if( TryEnterCriticalSection(&cs_memory) )
		{
			lastQueueSize = s_chunkDataQueue.size();
			if(lastQueueSize > 0)
			{
				dos = s_chunkDataQueue.front();
				s_chunkDataQueue.pop_front();
			}
			s_runningThreadCount++;
			LeaveCriticalSection(&cs_memory);

			if(dos)
			{
				PIXBeginNamedEvent(0,"Saving chunk");
				//app.DebugPrintf("Compressing chunk data (%d left)\n", lastQueueSize - 1);
				dos->close();
				dos->deleteChildStream();
				PIXEndNamedEvent();
			}
			delete dos;
			dos = NULL;

			EnterCriticalSection(&cs_memory);
			s_runningThreadCount--;
			LeaveCriticalSection(&cs_memory);
		}

		// If there was more than one thing in the queue last time we checked, then we want to spin round again soon
		// Otherwise wait a bit longer
		if( (lastQueueSize -1) > 0) Sleep(1); // Sleep 1 to yield
		else Sleep(100);
	}

	Compression::ReleaseThreadStorage();

	return 0;
}

void McRegionChunkStorage::WaitForAll()
{
	WaitForAllSaves();
}

void McRegionChunkStorage::WaitIfTooManyQueuedChunks()
{
	WaitForSaves();
}

// Static
void McRegionChunkStorage::WaitForAllSaves()
{
	// Wait for there to be no more tasks to be processed...
	EnterCriticalSection(&cs_memory);
	size_t queueSize = s_chunkDataQueue.size();
	LeaveCriticalSection(&cs_memory);

	while(queueSize > 0)
	{
		Sleep(10);

		EnterCriticalSection(&cs_memory);
		queueSize = s_chunkDataQueue.size();
		LeaveCriticalSection(&cs_memory);
	}

	// And then wait for there to be no running threads that are processing these tasks
	EnterCriticalSection(&cs_memory);
	int runningThreadCount = s_runningThreadCount;
	LeaveCriticalSection(&cs_memory);

	while(runningThreadCount > 0)
	{
		Sleep(10);

		EnterCriticalSection(&cs_memory);
		runningThreadCount = s_runningThreadCount;
		LeaveCriticalSection(&cs_memory);
	}
}

// Static
void McRegionChunkStorage::WaitForSaves()
{
	static const int MAX_QUEUE_SIZE = 12;
	static const int DESIRED_QUEUE_SIZE = 6;

	// Wait for the queue to reduce to a level where we should add more elements
	EnterCriticalSection(&cs_memory);
	size_t queueSize = s_chunkDataQueue.size();
	LeaveCriticalSection(&cs_memory);

	if( queueSize > MAX_QUEUE_SIZE )
	{
		while( queueSize > DESIRED_QUEUE_SIZE )
		{
			Sleep(10);

			EnterCriticalSection(&cs_memory);
			queueSize = s_chunkDataQueue.size();
			LeaveCriticalSection(&cs_memory);
		}
	}
}