summaryrefslogblamecommitdiffstats
path: root/source/cChunk.cpp
blob: 489af5cc9bf84d9448a65129643801419e8d322e (plain) (tree)
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612




























                                                                                              
                       
                           











                                          

                                                                                 




 



























































































































































































































































































































































































































































































                                                                                                                                           






                                                                                                                              











































































                                                                                                                                              
                                                                                                                       













































































                                                                                                                               
                                                                                               
























































                                                                                                                                  
                                                                             
        









                                                                              





 
                                                                                  

                                                                                                                                         
                                                                                                         
        
                                                          




                                                    
                               



                                                                                                  

















                                                                                
         

































                                                                                                                  
                 

                                            
                         





                                                       

                         



























                                                                                                                                                    





 




























































































































































































































































































































































































































































































































































































































































































































































                                                                                                                                                                                                


                                                                
                                                                                                             
         
                       











                                          


                                                                     
                                                                                                                            
         
                       


















                                                                     
                                                                                                                            
         
                       


























                                                                                                 
                                                                                                                            
         
                       




























                                                                                                                                            
                                                                                                                            
         
                       



































































                                                                                                                                                    







































































































































































                                                                                                                         

#include "Globals.h"  // NOTE: MSVC stupidness requires this to be the same across all modules

#ifndef _WIN32
	#include <cstdlib>
#endif


#include "cChunk.h"
#include "cWorld.h"
#include "cWaterSimulator.h"
#include "cLavaSimulator.h"
#include "cClientHandle.h"
#include "cServer.h"
#include "zlib.h"
#include "Defines.h"
#include "cChestEntity.h"
#include "cFurnaceEntity.h"
#include "cSignEntity.h"
#include "cTorch.h"
#include "cLadder.h"
#include "cPickup.h"
#include "cRedstone.h"
#include "cItem.h"
#include "cNoise.h"
#include "cRoot.h"
#include "cBlockToPickup.h"
#include "MersenneTwister.h"
#include "cPlayer.h"
#include "cBlockArea.h"
#include "cPluginManager.h"

#include "packets/cPacket_DestroyEntity.h"
#include "packets/cPacket_PreChunk.h"
#include "packets/cPacket_BlockChange.h"
#include "packets/cPacket_MultiBlock.h"

#include <json/json.h>





// Leaves can be this many blocks that away (inclusive) from the log not to decay
#define LEAVES_CHECK_DISTANCE 5





extern bool g_bWaterPhysics;





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// sSetBlock:

sSetBlock::sSetBlock( int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta )  // absolute block position
	: x( a_BlockX )
	, y( a_BlockY )
	, z( a_BlockZ )
	, BlockType( a_BlockType )
	, BlockMeta( a_BlockMeta )
{
	cChunkDef::AbsoluteToRelative(x, y, z, ChunkX, ChunkZ);
}





///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// cChunk:

cChunk::cChunk(int a_ChunkX, int a_ChunkY, int a_ChunkZ, cChunkMap * a_ChunkMap, cWorld * a_World)
	: m_PosX( a_ChunkX )
	, m_PosY( a_ChunkY )
	, m_PosZ( a_ChunkZ )
	, m_BlockTickX( 0 )
	, m_BlockTickY( 0 )
	, m_BlockTickZ( 0 )
	, m_World( a_World )
	, m_ChunkMap(a_ChunkMap)
	, m_IsValid(false)
	, m_IsLightValid(false)
	, m_IsDirty(false)
	, m_IsSaving(false)
	, m_StayCount(0)
{
	// LOGINFO("### new cChunk (%i, %i) at %p, thread 0x%x ###", a_X, a_Z, this, GetCurrentThreadId());
}





cChunk::~cChunk()
{
	// LOGINFO("### delete cChunk() (%i, %i) from %p, thread 0x%x ###", m_PosX, m_PosZ, this, GetCurrentThreadId() );
	
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		delete *itr;
	}
	m_BlockEntities.clear();

	// Remove and destroy all entities that are not players:
	cEntityList Entities;
	for (cEntityList::const_iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
	{
		if ((*itr)->GetEntityType() != cEntity::eEntityType_Player)
		{
			Entities.push_back(*itr);
		}
	}
	for (cEntityList::iterator itr = Entities.begin(); itr != Entities.end(); ++itr)
	{
		(*itr)->RemoveFromChunk();
		(*itr)->Destroy();
	}
	m_Entities.clear();
}





void cChunk::SetValid(void)
{
	m_IsValid = true;
	
	m_World->GetChunkMap()->ChunkValidated();
}





void cChunk::MarkRegenerating(void)
{
	// Tell all clients attached to this chunk that they want this chunk:
	for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr)
	{
		(*itr)->AddWantedChunk(m_PosX, m_PosZ);
	}  // for itr - m_LoadedByClient[]
}





bool cChunk::CanUnload(void)
{
	return m_LoadedByClient.empty() && !m_IsDirty && (m_StayCount == 0);
}





void cChunk::MarkSaving(void)
{
	m_IsSaving = true;
}





void cChunk::MarkSaved(void)
{
	if (!m_IsSaving)
	{
		return;
	}
	m_IsDirty = false;
}





void cChunk::MarkLoaded(void)
{
	m_IsDirty = false;
	SetValid();
}





void cChunk::MarkLoadFailed(void)
{
	if (m_IsValid)
	{
		return;
	}
	
	m_HasLoadFailed = true;
}





void cChunk::GetAllData(cChunkDataCallback & a_Callback)
{
	a_Callback.HeightMap    (&m_HeightMap);
	a_Callback.BiomeData    (&m_BiomeMap);
	a_Callback.BlockTypes   (m_BlockTypes);
	a_Callback.BlockMeta    (m_BlockMeta);
	a_Callback.LightIsValid (m_IsLightValid);
	a_Callback.BlockLight   (m_BlockLight);
	a_Callback.BlockSkyLight(m_BlockSkyLight);
	
	for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
	{
		a_Callback.Entity(*itr);
	}
	
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		a_Callback.BlockEntity(*itr);
	}
}





void cChunk::SetAllData(
	const BLOCKTYPE *  a_BlockTypes, 
	const NIBBLETYPE * a_BlockMeta,
	const NIBBLETYPE * a_BlockLight,
	const NIBBLETYPE * a_BlockSkyLight,
	const HeightMap *  a_HeightMap,
	const BiomeMap &   a_BiomeMap,
	cEntityList & a_Entities, 
	cBlockEntityList & a_BlockEntities
)
{
	memcpy(m_BiomeMap, a_BiomeMap, sizeof(m_BiomeMap));
	
	if (a_HeightMap != NULL)
	{
		memcpy(m_HeightMap, a_HeightMap, sizeof(m_HeightMap));
	}
	
	memcpy(m_BlockTypes, a_BlockTypes, sizeof(m_BlockTypes));
	memcpy(m_BlockMeta,  a_BlockMeta,  sizeof(m_BlockMeta));
	if (a_BlockLight != NULL)
	{
		memcpy(m_BlockLight, a_BlockLight, sizeof(m_BlockLight));
	}
	if (a_BlockSkyLight != NULL)
	{
		memcpy(m_BlockSkyLight, a_BlockSkyLight, sizeof(m_BlockSkyLight));
	}
	
	m_IsLightValid = (a_BlockLight != NULL) && (a_BlockSkyLight != NULL);
	
	if (a_HeightMap == NULL)
	{
		CalculateHeightmap();
	}

	// Append entities to current entity list:
	m_Entities.splice(m_Entities.end(), a_Entities);
	
	// Clear the block entities present - either the loader / saver has better, or we'll create empty ones:
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		delete *itr;
	}
	std::swap(a_BlockEntities, m_BlockEntities);
	
	// Create block entities that the loader didn't load; fill them with defaults
	CreateBlockEntities();

	m_HasLoadFailed = false;
}





void cChunk::SetLight(
	const cChunkDef::BlockNibbles & a_BlockLight,
	const cChunkDef::BlockNibbles & a_SkyLight
)
{
	// TODO: We might get cases of wrong lighting when a chunk changes in the middle of a lighting calculation.
	// Postponing until we see how bad it is :)
	memcpy(m_BlockLight,    a_BlockLight, sizeof(m_BlockLight));
	memcpy(m_BlockSkyLight, a_SkyLight,   sizeof(m_BlockSkyLight));
	m_IsLightValid = true;
}





void cChunk::GetBlockTypes(BLOCKTYPE * a_BlockTypes)
{
	memcpy(a_BlockTypes, m_BlockTypes, NumBlocks);
}





void cChunk::GetBlockData(BLOCKTYPE * a_BlockData)
{
	memcpy(a_BlockData, m_BlockTypes, NumBlocks);
	memcpy(a_BlockData + MetaOffset,     m_BlockMeta,     NumBlocks / 2);
	memcpy(a_BlockData + LightOffset,    m_BlockLight,    NumBlocks / 2);
	memcpy(a_BlockData + SkyLightOffset, m_BlockSkyLight, NumBlocks / 2);
}





/// Returns true if there is a block entity at the coords specified
bool cChunk::HasBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ)
{
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		if (
			((*itr)->GetPosX() == a_BlockX) &&
			((*itr)->GetPosY() == a_BlockY) &&
			((*itr)->GetPosZ() == a_BlockZ)
		)
		{
			return true;
		}
	}  // for itr - m_BlockEntities[]
	return false;
}





/// Sets or resets the internal flag that prevents chunk from being unloaded
void cChunk::Stay(bool a_Stay)
{
	m_StayCount += (a_Stay ? 1 : -1);
	ASSERT(m_StayCount >= 0);
}





void cChunk::Tick(float a_Dt, MTRand & a_TickRandom)
{
	cCSLock Lock(m_CSBlockLists);
	unsigned int PendingSendBlocks = m_PendingSendBlocks.size();
	if( PendingSendBlocks > 1 )
	{
		cPacket_MultiBlock MultiBlock;
		MultiBlock.m_ChunkX = m_PosX;
		MultiBlock.m_ChunkZ = m_PosZ;
		MultiBlock.m_NumBlocks = (short)PendingSendBlocks;
		MultiBlock.m_Data = new cPacket_MultiBlock::sBlockChange[ PendingSendBlocks ];
		MultiBlock.m_DataSize = PendingSendBlocks * sizeof( cPacket_MultiBlock::sBlockChange );
		//LOG("Sending multiblock packet for %i blocks", PendingSendBlocks );
		for( unsigned int i = 0; i < PendingSendBlocks; i++)
		{
			unsigned int index = m_PendingSendBlocks[i];
			Vector3i BlockPos = IndexToCoordinate( index );

			unsigned int Coords = BlockPos.y | (BlockPos.z << 8) | (BlockPos.x << 12);
			unsigned int Blocks = GetNibble( m_BlockMeta, index ) | (m_BlockTypes[index] << 4);
			MultiBlock.m_Data[i].Data = Coords << 16 | Blocks;
		}
		m_PendingSendBlocks.clear();
		PendingSendBlocks = m_PendingSendBlocks.size();
		Broadcast( MultiBlock );
	}
	if( PendingSendBlocks > 0 )
	{
		for( unsigned int i = 0; i < PendingSendBlocks; i++)
		{
			unsigned int index = m_PendingSendBlocks[i];
			Vector3i WorldPos = PositionToWorldPosition( IndexToCoordinate( index ) );

			cPacket_BlockChange BlockChange;
			BlockChange.m_PosX = WorldPos.x;
			BlockChange.m_PosY = (unsigned char)WorldPos.y;
			BlockChange.m_PosZ = WorldPos.z;
			BlockChange.m_BlockType = m_BlockTypes[index];
			BlockChange.m_BlockMeta = GetNibble( m_BlockMeta, index );
			Broadcast( BlockChange );
		}
		m_PendingSendBlocks.clear();
	}
	Lock.Unlock();

	while ( !m_UnloadQuery.empty() )
	{
		cPacket_PreChunk UnloadPacket;
		UnloadPacket.m_PosX = GetPosX();
		UnloadPacket.m_PosZ = GetPosZ();
		UnloadPacket.m_bLoad = false; // Unload
		(*m_UnloadQuery.begin())->Send( UnloadPacket );
		m_UnloadQuery.remove( *m_UnloadQuery.begin() );
	}

	CheckBlocks();
	
	TickBlocks(a_TickRandom);

	// Tick block entities (furnaces)
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		if ((*itr)->GetBlockType() == E_BLOCK_FURNACE)
		{
			m_IsDirty = ((cFurnaceEntity *)(*itr))->Tick( a_Dt ) | m_IsDirty;
		}
	}
}





void cChunk::CheckBlocks(void)
{
	cCSLock Lock2(m_CSBlockLists);
	unsigned int NumTickBlocks = m_ToTickBlocks.size();
	Lock2.Unlock();

	if (NumTickBlocks == 0)
	{
		return;
	}
	
	Lock2.Lock();
	std::deque< unsigned int > ToTickBlocks = m_ToTickBlocks;
	m_ToTickBlocks.clear();
	Lock2.Unlock();
	
	for (std::deque< unsigned int >::const_iterator itr = ToTickBlocks.begin(); itr != ToTickBlocks.end(); ++itr)
	{
		unsigned int index = (*itr);
		Vector3i BlockPos = IndexToCoordinate(index);

		BLOCKTYPE  BlockType = GetBlock(index);
		NIBBLETYPE BlockMeta = GetMeta (index);
		switch (BlockType)
		{
			// Stuff that drops when block below is destroyed:
			case E_BLOCK_REDSTONE_REPEATER_OFF:
			case E_BLOCK_REDSTONE_REPEATER_ON:
			case E_BLOCK_REDSTONE_WIRE:
			case E_BLOCK_CACTUS:
			case E_BLOCK_REEDS:
			case E_BLOCK_WOODEN_PRESSURE_PLATE:
			case E_BLOCK_STONE_PRESSURE_PLATE:
			case E_BLOCK_MINECART_TRACKS:
			case E_BLOCK_SIGN_POST:
			case E_BLOCK_CROPS:
			case E_BLOCK_SAPLING:
			case E_BLOCK_YELLOW_FLOWER:
			case E_BLOCK_RED_ROSE:
			case E_BLOCK_RED_MUSHROOM:
			case E_BLOCK_BROWN_MUSHROOM:
			case E_BLOCK_SNOW:
			{
				if (GetBlock(BlockPos.x, BlockPos.y - 1, BlockPos.z) == E_BLOCK_AIR)
				{
					SetBlock( BlockPos, E_BLOCK_AIR, 0 );

					Vector3i WorldPos = PositionToWorldPosition( BlockPos );

					m_World->GetSimulatorManager()->WakeUp(WorldPos.x, WorldPos.y, WorldPos.z);
					
					cItems Pickups;
					cBlockToPickup::ToPickup(BlockType, BlockMeta, E_ITEM_EMPTY, Pickups);
					m_World->SpawnItemPickups(Pickups, WorldPos.x, WorldPos.y, WorldPos.z);
				}
				break;
			}

			case E_BLOCK_REDSTONE_TORCH_OFF:
			case E_BLOCK_REDSTONE_TORCH_ON:
			case E_BLOCK_TORCH:
			{
				char Dir = cTorch::MetaDataToDirection( GetNibble( m_BlockMeta, BlockPos ) );
				Vector3i WorldPos = PositionToWorldPosition( BlockPos );

				Vector3i AttachedTo = WorldPos;
				AddDirection( AttachedTo.x, AttachedTo.y, AttachedTo.z, Dir, true );
				if( m_World->GetBlock( AttachedTo ) == E_BLOCK_AIR )
				{
					SetBlock( BlockPos, E_BLOCK_AIR, 0 );

					m_World->GetSimulatorManager()->WakeUp(WorldPos.x, WorldPos.y, WorldPos.z);

					cItems Pickups;
					cBlockToPickup::ToPickup(BlockType, BlockMeta, E_ITEM_EMPTY, Pickups);
					m_World->SpawnItemPickups(Pickups, WorldPos.x, WorldPos.y, WorldPos.z);
				}
				break;
			}

			case E_BLOCK_LADDER:
			{
				char Dir = cLadder::MetaDataToDirection( GetNibble( m_BlockMeta, BlockPos ) );
				Vector3i WorldPos = PositionToWorldPosition( BlockPos );
				Vector3i AttachedTo = WorldPos;
				AddDirection( AttachedTo.x, AttachedTo.y, AttachedTo.z, Dir, true );
				if( m_World->GetBlock( AttachedTo ) == E_BLOCK_AIR )
				{
					SetBlock( BlockPos, E_BLOCK_AIR, 0 );
					cItems Pickups;
					cBlockToPickup::ToPickup(BlockType, BlockMeta, E_ITEM_EMPTY, Pickups);
					m_World->SpawnItemPickups(Pickups, WorldPos.x, WorldPos.y, WorldPos.z);
				}
				break;
			}
			
			// If anything next to a leaves block changes, set the leaves' "check for decay" bit (clear bit 0x08):
			case E_BLOCK_LEAVES:
			{
				cChunkDef::SetNibble(m_BlockMeta, index, BlockMeta & 0x07);
				break;
			}
		}  // switch (BlockType)
	}  // for itr - ToTickBlocks[]
}





void cChunk::TickBlocks(MTRand & a_TickRandom)
{
	// Tick dem blocks
	// _X: We must limit the random number or else we get a nasty int overflow bug ( http://forum.mc-server.org/showthread.php?tid=457 )
	int RandomX = a_TickRandom.randInt(0x00ffffff);
	int RandomY = a_TickRandom.randInt(0x00ffffff);
	int RandomZ = a_TickRandom.randInt(0x00ffffff);
	int TickX = m_BlockTickX;
	int TickY = m_BlockTickY;
	int TickZ = m_BlockTickZ;

	// This for loop looks disgusting, but it actually does a simple thing - first processes m_BlockTick, then adds random to it
	// This is so that SetNextBlockTick() works
	for (int i = 0; i < 50; i++,
	
		// This weird construct (*2, then /2) is needed,
		// otherwise the blocktick distribution is too biased towards even coords!
		
		TickX = (TickX + RandomX) % (Width * 2),
		TickY = (TickY + RandomY) % (Height * 2),
		TickZ = (TickZ + RandomZ) % (Width * 2),
		m_BlockTickX = TickX / 2,
		m_BlockTickY = TickY / 2,
		m_BlockTickZ = TickZ / 2
	)
	{

		if (m_BlockTickY > cChunkDef::GetHeight(m_HeightMap, m_BlockTickX, m_BlockTickZ))
		{
			continue; // It's all air up here
		}

		unsigned int Index = MakeIndexNoCheck( m_BlockTickX, m_BlockTickY, m_BlockTickZ );
		BLOCKTYPE ID = m_BlockTypes[Index];
		switch( ID )
		{
			case E_BLOCK_CROPS:
			{
				NIBBLETYPE Meta = GetMeta(Index);
				if (Meta < 7)
				{
					FastSetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ, E_BLOCK_CROPS, ++Meta);
				}
				break;
			}
			
			case E_BLOCK_GRASS:        TickGrass       (m_BlockTickX, m_BlockTickY, m_BlockTickZ, a_TickRandom); break;
			case E_BLOCK_PUMPKIN_STEM:
			case E_BLOCK_MELON_STEM:   TickMelonPumpkin(m_BlockTickX, m_BlockTickY, m_BlockTickZ, Index, ID, a_TickRandom); break;
			case E_BLOCK_FARMLAND:     TickFarmland    (m_BlockTickX, m_BlockTickY, m_BlockTickZ); break;
			case E_BLOCK_SUGARCANE:    GrowSugarcane   (m_BlockTickX, m_BlockTickY, m_BlockTickZ, 1); break;
			case E_BLOCK_CACTUS:       GrowCactus      (m_BlockTickX, m_BlockTickY, m_BlockTickZ, 1); break;
			
			case E_BLOCK_SAPLING:
			{
				// Check the highest bit, if set, grow the tree, if not, set it (1-bit delay):
				NIBBLETYPE Meta = GetMeta(m_BlockTickX, m_BlockTickY, m_BlockTickZ);
				if ((Meta & 0x08) != 0)
				{
					m_World->GrowTree( m_BlockTickX + m_PosX*Width, m_BlockTickY, m_BlockTickZ + m_PosZ*Width );
				}
				else
				{
					SetMeta(m_BlockTickX, m_BlockTickY, m_BlockTickZ, Meta | 0x08);
				}
				break;
			}
			
			case E_BLOCK_LEAVES: TickLeaves(m_BlockTickX, m_BlockTickY, m_BlockTickZ, a_TickRandom); break;
			
			default:
			{
				break;
			}
		}
	}
}





void cChunk::TickGrass(int a_RelX, int a_RelY, int a_RelZ, MTRand & a_TickRandom)
{
	// Grass turns into dirt if there's another block on top of it:
	{
		BLOCKTYPE AboveBlock = cChunkDef::GetBlock(m_BlockTypes, a_RelX, a_RelY + 1, a_RelZ);
		if (!((g_BlockOneHitDig[AboveBlock]) || (g_BlockTransparent[AboveBlock])))
		{
			FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_DIRT, 0);
			return;
		}
	}
	
	// Grass spreads to nearby blocks if there's enough light (TODO) and free space above that block
	// Ref.: http://www.minecraftwiki.net/wiki/Grass_Block#Growth
	for (int i = 0; i < 2; i++)  // Pick two blocks to grow to
	{
		int OfsX = a_TickRandom.randInt(2) - 1;  // [-1 .. 1]
		int OfsY = a_TickRandom.randInt(4) - 3;  // [-3 .. 1]
		int OfsZ = a_TickRandom.randInt(2) - 1;  // [-1 .. 1]
		
		BLOCKTYPE  DestBlock;
		NIBBLETYPE DestMeta;
		if (
			!UnboundedRelGetBlock(a_RelX + OfsX, a_RelY + OfsY,     a_RelZ + OfsZ, DestBlock, DestMeta) ||
			(DestBlock != E_BLOCK_DIRT)
		)
		{
			continue;
		}

		BLOCKTYPE AboveDest;
		NIBBLETYPE AboveMeta;
		if (
			UnboundedRelGetBlock(a_RelX + OfsX, a_RelY + OfsY + 1, a_RelZ + OfsZ, AboveDest, AboveMeta) &&
			((g_BlockOneHitDig[AboveDest]) || (g_BlockTransparent[AboveDest]))
			// TODO: Query dest light, if it's enough
		)
		{
			UnboundedRelFastSetBlock(a_RelX + OfsX, a_RelY + OfsY, a_RelZ + OfsZ, E_BLOCK_GRASS, 0);
		}
	}  // for i - repeat twice
}





void cChunk::TickMelonPumpkin(int a_RelX, int a_RelY, int a_RelZ, int a_BlockIdx, BLOCKTYPE a_BlockType, MTRand & a_TickRandom)
{
	NIBBLETYPE Meta = GetMeta(a_BlockIdx);
	if (Meta < 7)
	{
		FastSetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ, a_BlockType, ++Meta);
		return;
	}
	GrowMelonPumpkin(a_RelX, a_RelY, a_RelZ, a_BlockType, a_TickRandom);
}





void cChunk::TickFarmland(int a_RelX, int a_RelY, int a_RelZ)
{
	// TODO: Rain hydrates blocks, too. Check world weather, don't search for water if raining.
	// NOTE: The desert biomes do not get precipitation, so another check needs to be made.
	
	// Search for water in a close proximity:
	// Ref.: http://www.minecraftwiki.net/wiki/Farmland#Hydrated_Farmland_Tiles
	bool Found = false;
	for (int y = a_RelY; y <= a_RelY + 1; y++)
	{
		for (int z = a_RelZ - 4; z <= a_RelZ + 4; z++)
		{
			for (int x = a_RelX - 4; x <= a_RelX + 4; x++)
			{
				BLOCKTYPE BlockType;
				NIBBLETYPE Meta;  // unused
				
				if (!UnboundedRelGetBlock(x, y, z, BlockType, Meta))
				{
					// Too close to an unloaded chunk, we might miss a water block there, so don't tick at all
					return;
				}
				if (
					(BlockType == E_BLOCK_WATER) ||
					(BlockType == E_BLOCK_STATIONARY_WATER)
				)
				{
					Found = true;
					break;
				}
			}  // for x
			if (Found)
			{
				break;
			}
		}  // for z
		if (Found)
		{
			break;
		}
	}  // for y
	
	NIBBLETYPE BlockMeta = GetMeta(a_RelX, a_RelY, a_RelZ);
	
	if (Found)
	{
		// Water was found, hydrate the block until hydration reaches 7:
		if (BlockMeta < 7)
		{
			FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_FARMLAND, ++BlockMeta);
		}
		return;
	}

	// Water wasn't found, de-hydrate block:
	if (BlockMeta > 0)
	{
		FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_FARMLAND, --BlockMeta);
		return;
	}
	
	// Farmland too dry. If nothing is growing on top, turn back to dirt:
	
	switch (GetBlock(a_RelX, a_RelY + 1, a_RelZ))
	{
		case E_BLOCK_CROPS:
		case E_BLOCK_MELON_STEM:
		case E_BLOCK_PUMPKIN_STEM:
			break;
		default:
			FastSetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_DIRT, 0);
			break;
	}
}





void cChunk::TickLeaves(int a_RelX, int a_RelY, int a_RelZ, MTRand & a_TickRandom)
{
	// Since leaves-checking is a costly operation, it is done only if leaves are marked for checking (Meta has its 0x08 bit cleared)
	// The meta bit 0x08 bit is cleared (check flag set) each time a block next to the leaves changes
	
	NIBBLETYPE Meta = GetMeta(a_RelX, a_RelY, a_RelZ);
	if ((Meta & 0x04) != 0)
	{
		// Player-placed leaves, don't decay
		return;
	}
	if ((Meta & 0x08) != 0)
	{
		// These leaves have been checked for decay lately and nothing around them changed
		return;
	}

	// Get the data around the leaves:
	cBlockArea Area;
	int BaseX = cChunkDef::Width * m_PosX + a_RelX;
	int BaseZ = cChunkDef::Width * m_PosZ + a_RelZ;
	if (!Area.Read(
		m_World, 
		BaseX - LEAVES_CHECK_DISTANCE, BaseX + LEAVES_CHECK_DISTANCE, 
		a_RelY - LEAVES_CHECK_DISTANCE, a_RelY + LEAVES_CHECK_DISTANCE, 
		BaseZ - LEAVES_CHECK_DISTANCE, BaseZ + LEAVES_CHECK_DISTANCE, 
		cBlockArea::baTypes)
	)
	{
		// Cannot check leaves, a chunk is missing too close
		return;
	}

	if (HasNearLog(Area, BaseX, a_RelY, BaseZ))
	{
		// Wood found, the leaves stay; mark them as checked:
		SetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ, Meta & 0x07);
		return;
	}
	// Decay the leaves:
	m_World->DigBlock(m_PosX * cChunkDef::Width + a_RelX, a_RelY, m_PosZ * cChunkDef::Width + a_RelZ);

	// Let them drop something if the random is right:
	cItems PickupItems;
	cBlockToPickup::ToPickup(E_BLOCK_LEAVES, Meta, cItem(), PickupItems);
		
	// Allow plugins to change the dropped objects:
	cRoot::Get()->GetPluginManager()->CallHookBlockToPickup(E_BLOCK_LEAVES, Meta, NULL, cItem(), PickupItems);
	m_World->SpawnItemPickups(PickupItems, BaseX, a_RelY, BaseZ);
}





#define PROCESS_NEIGHBOR(x,y,z) \
	switch (a_Area.GetBlockType(x, y, z)) \
	{ \
		case E_BLOCK_LEAVES: a_Area.SetBlockType(x, y, z, E_BLOCK_SPONGE + i + 1); break; \
		case E_BLOCK_LOG: return true; \
	}

bool cChunk::HasNearLog(cBlockArea & a_Area, int a_BlockX, int a_BlockY, int a_BlockZ)
{
	// Filter the blocks into a {leaves, log, other (air)} set:
	BLOCKTYPE * Types = a_Area.GetBlockTypes();
	for (int i = a_Area.GetBlockCount() - 1; i > 0; i--)
	{
		switch (Types[i])
		{
			case E_BLOCK_LEAVES:
			case E_BLOCK_LOG:
			{
				break;
			}
			default:
			{
				Types[i] = E_BLOCK_AIR;
				break;
			}
		}
	}  // for i - Types[]
	
	// Perform a breadth-first search to see if there's a log connected within 4 blocks of the leaves block:
	// Simply replace all reachable leaves blocks with a sponge block plus iteration (in the Area) and see if we can reach a log in 4 iterations
	a_Area.SetBlockType(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_SPONGE);
	for (int i = 0; i < LEAVES_CHECK_DISTANCE; i++)
	{
		for (int y = a_BlockY - i; y <= a_BlockY + i; y++)
		{
			for (int z = a_BlockZ - i; z <= a_BlockZ + i; z++)
			{
				for (int x = a_BlockX - i; x <= a_BlockX + i; x++)
				{
					if (a_Area.GetBlockType(x, y, z) != E_BLOCK_SPONGE + i)
					{
						continue;
					}
					PROCESS_NEIGHBOR(x - 1, y,     z);
					PROCESS_NEIGHBOR(x + 1, y,     z);
					PROCESS_NEIGHBOR(x,     y,     z - 1);
					PROCESS_NEIGHBOR(x,     y,     z + 1);
					PROCESS_NEIGHBOR(x,     y + 1, z);
					PROCESS_NEIGHBOR(x,     y - 1, z);
				}  // for x
			}  // for z
		}  // for y
	}  // for i - BFS iterations
	return false;
}





void cChunk::GrowMelonPumpkin(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, MTRand & a_TickRandom)
{
	// Convert the stem BlockType into produce BlockType
	BLOCKTYPE ProduceType;
	switch (a_BlockType)
	{
		case E_BLOCK_MELON_STEM:   ProduceType = E_BLOCK_MELON;   break;
		case E_BLOCK_PUMPKIN_STEM: ProduceType = E_BLOCK_PUMPKIN; break;
		default:
		{
			ASSERT(!"Unhandled blocktype in TickMelonPumpkin()");
			return;
		}
	}

	// Check if there's another melon / pumpkin around that stem, if so, abort:
	bool IsValid;
	BLOCKTYPE BlockType[4];
	NIBBLETYPE BlockMeta;  // unused
	IsValid =            UnboundedRelGetBlock(a_RelX + 1, a_RelY, a_RelZ,     BlockType[0], BlockMeta);
	IsValid = IsValid && UnboundedRelGetBlock(a_RelX - 1, a_RelY, a_RelZ,     BlockType[1], BlockMeta);
	IsValid = IsValid && UnboundedRelGetBlock(a_RelX,     a_RelY, a_RelZ + 1, BlockType[2], BlockMeta);
	IsValid = IsValid && UnboundedRelGetBlock(a_RelX,     a_RelY, a_RelZ - 1, BlockType[3], BlockMeta);
	if (
		!IsValid || 
		(BlockType[0] == ProduceType) || 
		(BlockType[1] == ProduceType) || 
		(BlockType[2] == ProduceType) || 
		(BlockType[3] == ProduceType)
	)
	{
		// Neighbors not valid or already taken by the same produce
		return;
	}
	
	// Pick a direction in which to place the produce:
	int x = 0, z = 0;
	int CheckType = a_TickRandom.randInt(3);  // The index to the neighbors array which should be checked for emptiness
	switch (CheckType)
	{
		case 0: x =  1; break;
		case 1: x = -1; break;
		case 2: z =  1; break;
		case 3: z = -1; break;
	}
	
	// Check that the block in that direction is empty:
	switch (BlockType[CheckType])
	{
		case E_BLOCK_AIR:
		case E_BLOCK_SNOW:
		case E_BLOCK_TALL_GRASS:
		case E_BLOCK_DEAD_BUSH:
		{
			break;
		}
		default: return;
	}
	
	// Check if there's soil under the neighbor. We already know the neighbors are valid. Place produce if ok
	BLOCKTYPE Soil;
	UnboundedRelGetBlock(a_RelX + x, a_RelY - 1, a_RelZ + z, Soil, BlockMeta);
	switch (Soil)
	{
		case E_BLOCK_DIRT:
		case E_BLOCK_GRASS:
		case E_BLOCK_FARMLAND:
		{
			// Place a randomly-facing produce:
			UnboundedRelFastSetBlock(a_RelX + x, a_RelY, a_RelZ + z, ProduceType, (NIBBLETYPE)(a_TickRandom.randInt(4) % 4));
			break;
		}
	}
}





void cChunk::GrowSugarcane(int a_RelX, int a_RelY, int a_RelZ, int a_NumBlocks)
{
	// Check the total height of the sugarcane blocks here:
	int Top = a_RelY + 1;
	while (
		(Top < cChunkDef::Height) &&
		(GetBlock(a_RelX, Top, a_RelZ) == E_BLOCK_SUGARCANE)
	)
	{
		++Top;
	}
	int Bottom = a_RelY - 1;
	while (
		(Bottom > 0) &&
		(GetBlock(a_RelX, Bottom, a_RelZ) == E_BLOCK_SUGARCANE)
	)
	{
		--Bottom;
	}
	
	// Grow by at most a_NumBlocks, but no more than max height:
	int ToGrow = std::min(a_NumBlocks, m_World->GetMaxSugarcaneHeight() + 1 - (Top - Bottom));
	for (int i = 0; i < ToGrow; i++)
	{
		BLOCKTYPE  BlockType;
		NIBBLETYPE BlockMeta;
		if (UnboundedRelGetBlock(a_RelX, Top + i, a_RelZ, BlockType, BlockMeta) && (BlockType == E_BLOCK_AIR))
		{
			UnboundedRelFastSetBlock(a_RelX, Top + i, a_RelZ, E_BLOCK_SUGARCANE, 0);
		}
		else
		{
			break;
		}
	}  // for i
}





void cChunk::GrowCactus(int a_RelX, int a_RelY, int a_RelZ, int a_NumBlocks)
{
	// Check the total height of the sugarcane blocks here:
	int Top = a_RelY + 1;
	while (
		(Top < cChunkDef::Height) &&
		(GetBlock(a_RelX, Top, a_RelZ) == E_BLOCK_CACTUS)
	)
	{
		++Top;
	}
	int Bottom = a_RelY - 1;
	while (
		(Bottom > 0) &&
		(GetBlock(a_RelX, Bottom, a_RelZ) == E_BLOCK_CACTUS)
	)
	{
		--Bottom;
	}
	
	// Grow by at most a_NumBlocks, but no more than max height:
	int ToGrow = std::min(a_NumBlocks, m_World->GetMaxCactusHeight() + 1 - (Top - Bottom));
	for (int i = 0; i < ToGrow; i++)
	{
		BLOCKTYPE  BlockType;
		NIBBLETYPE BlockMeta;
		if (UnboundedRelGetBlock(a_RelX, Top + i, a_RelZ, BlockType, BlockMeta) && (BlockType == E_BLOCK_AIR))
		{
			// TODO: Check the surrounding blocks, if they aren't air, break the cactus block into pickups (and continue breaking blocks above in the next loop iterations)
			UnboundedRelFastSetBlock(a_RelX, Top + i, a_RelZ, E_BLOCK_CACTUS, 0);
		}
		else
		{
			break;
		}
	}  // for i
}





bool cChunk::UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta)
{
	if ((a_RelY < 0) || (a_RelY > cChunkDef::Height))
	{
		return false;
	}
	
	if ((a_RelX >= 0) && (a_RelX < cChunkDef::Width) && (a_RelZ >= 0) && (a_RelZ < cChunkDef::Width))
	{
		int BlockIdx = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
		a_BlockType = GetBlock(BlockIdx);
		a_BlockMeta = GetMeta(BlockIdx);
		return true;
	}
	return m_ChunkMap->LockedGetBlock(
		m_PosX * cChunkDef::Width + a_RelX,
		ZERO_CHUNK_Y * cChunkDef::Height + a_RelY,
		m_PosZ * cChunkDef::Width + a_RelZ,
		a_BlockType, a_BlockMeta
	);
}





bool cChunk::UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{
	if ((a_RelX >= 0) && (a_RelX < cChunkDef::Width) && (a_RelZ >= 0) && (a_RelZ < cChunkDef::Width))
	{
		SetBlock(a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta);
		return true;
	}
	return m_ChunkMap->LockedSetBlock(
		m_PosX * cChunkDef::Width + a_RelX,
		ZERO_CHUNK_Y * cChunkDef::Height + a_RelY,
		m_PosZ * cChunkDef::Width + a_RelZ,
		a_BlockType, a_BlockMeta
	);
}





bool cChunk::UnboundedRelFastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta)
{
	if ((a_RelX >= 0) && (a_RelX < cChunkDef::Width) && (a_RelZ >= 0) && (a_RelZ < cChunkDef::Width))
	{
		FastSetBlock(a_RelX, a_RelY, a_RelZ, a_BlockType, a_BlockMeta);
		return true;
	}
	return m_ChunkMap->LockedFastSetBlock(
		m_PosX * cChunkDef::Width + a_RelX,
		ZERO_CHUNK_Y * cChunkDef::Height + a_RelY,
		m_PosZ * cChunkDef::Width + a_RelZ,
		a_BlockType, a_BlockMeta
	);
}





int cChunk::GetHeight( int a_X, int a_Z )
{
	ASSERT((a_X >= 0) && (a_X < Width) && (a_Z >= 0) && (a_Z < Width));
	
	if ((a_X >= 0) && (a_X < Width) && (a_Z >= 0) && (a_Z < Width))
	{
		return m_HeightMap[a_X + a_Z * Width];
	}
	return 0;
}





void cChunk::CreateBlockEntities(void)
{
	for (int x = 0; x < Width; x++)
	{
		for (int z = 0; z < Width; z++)
		{
			for (int y = 0; y < Height; y++)
			{
				ENUM_BLOCK_ID BlockType = (ENUM_BLOCK_ID)m_BlockTypes[ MakeIndex( x, y, z ) ];
				switch ( BlockType )
				{
					case E_BLOCK_CHEST:
					{
						if (!HasBlockEntityAt(x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width))
						{
							m_BlockEntities.push_back( new cChestEntity( x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width, m_World) );
						}
						break;
					}
					
					case E_BLOCK_FURNACE:
					{
						if (!HasBlockEntityAt(x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width))
						{
							m_BlockEntities.push_back( new cFurnaceEntity( x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width, m_World) );
						}
						break;
					}
					
					case E_BLOCK_SIGN_POST:
					case E_BLOCK_WALLSIGN:
					{
						if (!HasBlockEntityAt(x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width))
						{
							m_BlockEntities.push_back( new cSignEntity( BlockType, x + m_PosX * Width, y + m_PosY * Height, z + m_PosZ * Width, m_World) );
						}
						break;
					}
				}  // switch (BlockType)
			}  // for y
		}  // for z
	}  // for x
}





void cChunk::CalculateHeightmap()
{
	for (int x = 0; x < Width; x++)
	{
		for (int z = 0; z < Width; z++)
		{
			for (int y = Height - 1; y > -1; y--)
			{
				int index = MakeIndex( x, y, z );
				if (m_BlockTypes[index] != E_BLOCK_AIR)
				{
					m_HeightMap[x + z * Width] = (unsigned char)y;
					break;
				}
			}  // for y
		}  // for z
	}  // for x
}





void cChunk::SetBlock( int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta )
{
	if (a_RelX < 0 || a_RelX >= Width || a_RelY < 0 || a_RelY >= Height || a_RelZ < 0 || a_RelZ >= Width)
	{
		return;  // Clip
	}

	ASSERT(IsValid());  // Is this chunk loaded / generated?
	
	int index = MakeIndexNoCheck( a_RelX, a_RelY, a_RelZ );
	BLOCKTYPE OldBlockMeta = GetNibble( m_BlockMeta, index );
	BLOCKTYPE OldBlockType = m_BlockTypes[index];
	m_BlockTypes[index] = a_BlockType;

	SetNibble( m_BlockMeta, index, a_BlockMeta );

	if ((OldBlockType == a_BlockType) && (OldBlockMeta == a_BlockMeta))
	{
		return;
	}

	MarkDirty();
	
	{
		cCSLock Lock(m_CSBlockLists);
		m_PendingSendBlocks.push_back( index );
	}

	// ONLY recalculate lighting if it's necessary!
	if(
		(g_BlockLightValue[ OldBlockType ] != g_BlockLightValue[ a_BlockType ]) ||
		(g_BlockSpreadLightFalloff[ OldBlockType ] != g_BlockSpreadLightFalloff[ a_BlockType ]) ||
		(g_BlockTransparent[ OldBlockType ] != g_BlockTransparent[ a_BlockType ] )
	)
	{
		m_IsLightValid = false;
	}

	// Update heightmap, if needed:
	if (a_RelY >= m_HeightMap[a_RelX + a_RelZ * Width])
	{
		if (a_BlockType != E_BLOCK_AIR)
		{
			SetHeight(m_HeightMap, a_RelX, a_RelZ, a_RelY);
		}
		else
		{
			for (int y = a_RelY - 1; y > 0; --y)
			{
				if (cChunkDef::GetBlock(m_BlockTypes, a_RelX, y, a_RelZ) != E_BLOCK_AIR)
				{
					SetHeight(m_HeightMap, a_RelX, a_RelZ, y);
					break;
				}
			}  // for y - column in m_BlockData
		}
	}

	m_ToTickBlocks.push_back( MakeIndex( a_RelX,     a_RelY,     a_RelZ ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX + 1, a_RelY,     a_RelZ ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX - 1, a_RelY,     a_RelZ ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX,     a_RelY + 1, a_RelZ ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX,     a_RelY - 1, a_RelZ ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX,     a_RelY,     a_RelZ + 1 ) );
	m_ToTickBlocks.push_back( MakeIndex( a_RelX,     a_RelY,     a_RelZ - 1 ) );

	Vector3i WorldPos = PositionToWorldPosition( a_RelX, a_RelY, a_RelZ );
	cBlockEntity* BlockEntity = GetBlockEntity( WorldPos );
	if( BlockEntity )
	{
		BlockEntity->Destroy();
		RemoveBlockEntity( BlockEntity );
		delete BlockEntity;
	}
	switch( a_BlockType )
	{
		case E_BLOCK_CHEST:
		{
			AddBlockEntity( new cChestEntity( WorldPos.x, WorldPos.y, WorldPos.z, m_World) );
			break;
		}
		case E_BLOCK_FURNACE:
		{
			AddBlockEntity( new cFurnaceEntity( WorldPos.x, WorldPos.y, WorldPos.z, m_World) );
			break;
		}
		case E_BLOCK_SIGN_POST:
		case E_BLOCK_WALLSIGN:
		{
			AddBlockEntity( new cSignEntity( (ENUM_BLOCK_ID)a_BlockType, WorldPos.x, WorldPos.y, WorldPos.z, m_World) );
			break;
		}
	}  // switch (a_BlockType)
}





void cChunk::FastSetBlock( int a_X, int a_Y, int a_Z, BLOCKTYPE a_BlockType, BLOCKTYPE a_BlockMeta)
{
	ASSERT(!((a_X < 0 || a_X >= Width || a_Y < 0 || a_Y >= Height || a_Z < 0 || a_Z >= Width)));

	ASSERT(IsValid());
	
	const int index = MakeIndexNoCheck( a_X, a_Y, a_Z );
	const BLOCKTYPE OldBlock = m_BlockTypes[index];
	const BLOCKTYPE OldBlockMeta = GetNibble( m_BlockMeta, index );
	if ((OldBlock == a_BlockType) && (OldBlockMeta == a_BlockMeta))
	{
		return;
	}

	MarkDirty();
	
	m_BlockTypes[index] = a_BlockType;

	{
		cCSLock Lock(m_CSBlockLists);
		m_PendingSendBlocks.push_back( index );
	}
	
	SetNibble( m_BlockMeta, index, a_BlockMeta );

	// ONLY recalculate lighting if it's necessary!
	if(
		(g_BlockLightValue[ OldBlock ] != g_BlockLightValue[ a_BlockType ]) ||
		(g_BlockSpreadLightFalloff[ OldBlock ] != g_BlockSpreadLightFalloff[ a_BlockType ]) ||
		(g_BlockTransparent[ OldBlock ] != g_BlockTransparent[ a_BlockType ] )
	)
	{
		m_IsLightValid = false;
	}

	// Update heightmap, if needed:
	if (a_Y >= m_HeightMap[a_X + a_Z * Width])
	{
		if (a_BlockType != E_BLOCK_AIR)
		{
			m_HeightMap[a_X + a_Z * Width] = (unsigned char)a_Y;
		}
		else
		{
			for (int y = a_Y - 1; y > 0; --y)
			{
				if (m_BlockTypes[MakeIndexNoCheck(a_X, y, a_Z)] != E_BLOCK_AIR)
				{
					m_HeightMap[a_X + a_Z * Width] = (unsigned char)y;
					break;
				}
			}  // for y - column in m_BlockData
		}
	}
}





void cChunk::SendBlockTo( int a_X, int a_Y, int a_Z, cClientHandle* a_Client )
{
	if( a_Client == 0 )
	{
		cCSLock Lock(m_CSBlockLists);
		unsigned int index = MakeIndex( a_X, a_Y, a_Z );
		if( index != INDEX_OUT_OF_RANGE )
		{
			m_PendingSendBlocks.push_back( index );
		}
		else
		{
			LOGWARN("cChunk::SendBlockTo Index out of range!");
		}
		return;
	}

	for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr )
	{
		if ( *itr == a_Client )
		{
			unsigned int index = MakeIndex( a_X, a_Y, a_Z );
			Vector3i WorldPos = PositionToWorldPosition( a_X, a_Y, a_Z );
			cPacket_BlockChange BlockChange;
			BlockChange.m_PosX = WorldPos.x;
			BlockChange.m_PosY = (unsigned char)WorldPos.y;
			BlockChange.m_PosZ = WorldPos.z;
			if( index != INDEX_OUT_OF_RANGE )
			{
				BlockChange.m_BlockType = m_BlockTypes[ index ];
				BlockChange.m_BlockMeta = GetNibble( m_BlockMeta, index );
			} // else it's both 0
			a_Client->Send( BlockChange );
			break;
		}
	}
}





void cChunk::AddBlockEntity( cBlockEntity* a_BlockEntity )
{
	cCSLock Lock(m_CSBlockLists);
	m_BlockEntities.push_back( a_BlockEntity );
}





cBlockEntity * cChunk::GetBlockEntity(int a_X, int a_Y, int a_Z)
{
	// Assumes that the m_CSBlockList is already locked, we're being called from SetBlock()
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		if (
			((*itr)->GetPosX() == a_X) &&
			((*itr)->GetPosY() == a_Y) &&
			((*itr)->GetPosZ() == a_Z)
		)
		{
			return *itr;
		}
	}  // for itr - m_BlockEntities[]
	
	return NULL;
}





void cChunk::UseBlockEntity(cPlayer * a_Player, int a_X, int a_Y, int a_Z)
{
	cBlockEntity * be = GetBlockEntity(a_X, a_Y, a_Z);
	if (be != NULL)
	{
		be->UsedBy(a_Player);
	}
}





void cChunk::CollectPickupsByPlayer(cPlayer * a_Player)
{
	double PosX = a_Player->GetPosX();
	double PosY = a_Player->GetPosY();
	double PosZ = a_Player->GetPosZ();
	
	for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr)
	{
		if ( (*itr)->GetEntityType() != cEntity::eEntityType_Pickup )
		{
			continue; // Only pickups
		}
		float DiffX = (float)((*itr)->GetPosX() - PosX );
		float DiffY = (float)((*itr)->GetPosY() - PosY );
		float DiffZ = (float)((*itr)->GetPosZ() - PosZ );
		float SqrDist = DiffX * DiffX + DiffY * DiffY + DiffZ * DiffZ;
		if (SqrDist < 1.5f * 1.5f)  // 1.5 block
		{
			MarkDirty();
			(reinterpret_cast<cPickup *>(*itr))->CollectedBy( a_Player );
		}
	}
}





void cChunk::UpdateSign(int a_PosX, int a_PosY, int a_PosZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4)
{
	// Also sends update packets to all clients in the chunk
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		if (
			((*itr)->GetPosX() == a_PosX) &&
			((*itr)->GetPosY() == a_PosY) &&
			((*itr)->GetPosZ() == a_PosZ) &&
			(
				((*itr)->GetBlockType() == E_BLOCK_WALLSIGN) ||
				((*itr)->GetBlockType() == E_BLOCK_SIGN_POST)
			)
		)
		{
			MarkDirty();
			(reinterpret_cast<cSignEntity *>(*itr))->SetLines(a_Line1, a_Line2, a_Line3, a_Line4);
			(*itr)->SendTo(NULL);
		}
	}  // for itr - m_BlockEntities[]
}





void cChunk::RemoveBlockEntity( cBlockEntity* a_BlockEntity )
{
	cCSLock Lock(m_CSBlockLists);
	MarkDirty();
	m_BlockEntities.remove( a_BlockEntity );
}





bool cChunk::AddClient(cClientHandle* a_Client)
{
	for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr)
	{
		if (a_Client == *itr)
		{
			// Already there, nothing needed
			return false;
		}
	}
	m_LoadedByClient.push_back( a_Client );

	for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr )
	{
		LOGD("cChunk: Entity #%d (%s) at [%i, %i, %i] spawning for player \"%s\"", (*itr)->GetUniqueID(), (*itr)->GetClass(), m_PosX, m_PosY, m_PosZ, a_Client->GetUsername().c_str() );
		(*itr)->SpawnOn( a_Client );
	}
	return true;
}





void cChunk::RemoveClient( cClientHandle* a_Client )
{
	for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr)
	{
		if (*itr != a_Client)
		{
			continue;
		}
		
		m_LoadedByClient.erase(itr);

		if ( !a_Client->IsDestroyed() )
		{
			for (cEntityList::iterator itr = m_Entities.begin(); itr != m_Entities.end(); ++itr )
			{
				LOGD("chunk [%i, %i] destroying entity #%i for player \"%s\"", m_PosX, m_PosZ, (*itr)->GetUniqueID(), a_Client->GetUsername().c_str() );
				cPacket_DestroyEntity DestroyEntity( *itr );
				a_Client->Send( DestroyEntity );
			}
		}
		return;
	}  // for itr - m_LoadedByClient[]
}





bool cChunk::HasClient( cClientHandle* a_Client )
{
	for (cClientHandleList::const_iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr)
	{
		if ((*itr) == a_Client)
		{
			return true;
		}
	}
	return false;
}





bool cChunk::HasAnyClients(void)
{
	return !m_LoadedByClient.empty();
}





void cChunk::AddEntity( cEntity * a_Entity)
{
	if (a_Entity->GetEntityType() != cEntity::eEntityType_Player)
	{
		MarkDirty();
	}
	m_Entities.push_back( a_Entity );
}





void cChunk::RemoveEntity(cEntity * a_Entity)
{
	size_t SizeBefore = m_Entities.size();
	m_Entities.remove(a_Entity);
	size_t SizeAfter = m_Entities.size();
	
	if (SizeBefore != SizeAfter)
	{
		// Mark as dirty if it was a server-generated entity:
		if (a_Entity->GetEntityType() != cEntity::eEntityType_Player)
		{
			MarkDirty();
		}
	}
}





bool cChunk::ForEachEntity(cEntityCallback & a_Callback)
{
	// The entity list is locked by the parent chunkmap's CS
	for (cEntityList::iterator itr = m_Entities.begin(), itr2 = itr; itr != m_Entities.end(); itr = itr2)
	{
		++itr2;
		if (a_Callback.Item(*itr))
		{
			return false;
		}
	}  // for itr - m_Entitites[]
	return true;
}





bool cChunk::ForEachChest(cChestCallback & a_Callback)
{
	// The blockentity list is locked by the parent chunkmap's CS
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
	{
		++itr2;
		if ((*itr)->GetBlockType() != E_BLOCK_CHEST)
		{
			continue;
		}
		if (a_Callback.Item((cChestEntity *)*itr))
		{
			return false;
		}
	}  // for itr - m_BlockEntitites[]
	return true;
}





bool cChunk::ForEachFurnace(cFurnaceCallback & a_Callback)
{
	// The blockentity list is locked by the parent chunkmap's CS
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
	{
		++itr2;
		switch ((*itr)->GetBlockType())
		{
			case E_BLOCK_FURNACE:
			case E_BLOCK_LIT_FURNACE:
			{
				break;
			}
			default:
			{
				continue;
			}
		}
		if (a_Callback.Item((cFurnaceEntity *)*itr))
		{
			return false;
		}
	}  // for itr - m_BlockEntitites[]
	return true;
}





bool cChunk::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCallback & a_Callback)
{
	// The blockentity list is locked by the parent chunkmap's CS
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
	{
		++itr2;
		if (((*itr)->GetPosX() != a_BlockX) || ((*itr)->GetPosY() != a_BlockY) || ((*itr)->GetPosZ() != a_BlockZ))
		{
			continue;
		}
		if ((*itr)->GetBlockType() != E_BLOCK_CHEST)
		{
			// There is a block entity here, but of different type. No other block entity can be here, so we can safely bail out
			return false;
		}
		
		// The correct block entity is here
		if (a_Callback.Item((cChestEntity *)*itr))
		{
			return false;
		}
		return true;
	}  // for itr - m_BlockEntitites[]
	
	// Not found:
	return false;
}





bool cChunk::DoWithFurnaceAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFurnaceCallback & a_Callback)
{
	// The blockentity list is locked by the parent chunkmap's CS
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(), itr2 = itr; itr != m_BlockEntities.end(); itr = itr2)
	{
		++itr2;
		if (((*itr)->GetPosX() != a_BlockX) || ((*itr)->GetPosY() != a_BlockY) || ((*itr)->GetPosZ() != a_BlockZ))
		{
			continue;
		}
		switch ((*itr)->GetBlockType())
		{
			case E_BLOCK_FURNACE:
			case E_BLOCK_LIT_FURNACE:
			{
				break;
			}
			default:
			{
				// There is a block entity here, but of different type. No other block entity can be here, so we can safely bail out
				return false;
			}
		}  // switch (BlockType)
		
		// The correct block entity is here, 
		if (a_Callback.Item((cFurnaceEntity *)*itr))
		{
			return false;
		}
		return true;
	}  // for itr - m_BlockEntitites[]
	
	// Not found:
	return false;
}





bool cChunk::GetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4)
{
	// The blockentity list is locked by the parent chunkmap's CS
	for (cBlockEntityList::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr)
	{
		if (((*itr)->GetPosX() != a_BlockX) || ((*itr)->GetPosY() != a_BlockY) || ((*itr)->GetPosZ() != a_BlockZ))
		{
			continue;
		}
		switch ((*itr)->GetBlockType())
		{
			case E_BLOCK_WALLSIGN:
			case E_BLOCK_SIGN_POST:
			{
				a_Line1 = ((cSignEntity *)*itr)->GetLine(0);
				a_Line2 = ((cSignEntity *)*itr)->GetLine(1);
				a_Line3 = ((cSignEntity *)*itr)->GetLine(2);
				a_Line4 = ((cSignEntity *)*itr)->GetLine(3);
				return true;
			}
		}  // switch (BlockType)
		
		// There is a block entity here, but of different type. No other block entity can be here, so we can safely bail out
		return false;
	}  // for itr - m_BlockEntitites[]
	
	// Not found:
	return false;
}





BLOCKTYPE cChunk::GetBlock( int a_X, int a_Y, int a_Z )
{
	if ((a_X < 0) || (a_X >= Width) || (a_Y < 0) || (a_Y >= Height) || (a_Z < 0) || (a_Z >= Width)) return 0; // Clip

	return m_BlockTypes[ MakeIndexNoCheck( a_X, a_Y, a_Z ) ];
}





BLOCKTYPE cChunk::GetBlock( int a_BlockIdx )
{
	if( a_BlockIdx < 0 || a_BlockIdx >= NumBlocks ) return 0;
	return m_BlockTypes[ a_BlockIdx ];
}





void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta)
{
	int Idx = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY, a_RelZ);
	a_BlockType = cChunkDef::GetBlock (m_BlockTypes, a_RelX, a_RelY, a_RelZ);
	a_BlockMeta = cChunkDef::GetNibble(m_BlockMeta, a_RelX, a_RelY, a_RelZ);
}





/*
// _X 2012_02_23: Loading in old format not supported anymore
/// Loads the chunk from the old-format disk file, erases the file afterwards. Returns true if successful
bool cChunk::LoadFromDisk()
{
	AString SourceFile;
	Printf(SourceFile, "world/X%i_Y%i_Z%i.bin", m_PosX, m_PosY, m_PosZ );

	cFile f;
	if (!f.Open(SourceFile, cFile::fmRead))
	{
		return false;
	}

	if (f.Read(m_BlockData, sizeof(m_BlockData)) != sizeof(m_BlockData))
	{
		LOGERROR("ERROR READING FROM FILE %s", SourceFile.c_str()); 
		return false;
	}

	// Now load Block Entities:
	ENUM_BLOCK_ID BlockType;
	while (f.Read(&BlockType, sizeof(ENUM_BLOCK_ID)) == sizeof(ENUM_BLOCK_ID))
	{
		switch (BlockType)
		{
			case E_BLOCK_CHEST:
			{
				cChestEntity * ChestEntity = new cChestEntity( 0, 0, 0, m_World );
				if (!ChestEntity->LoadFromFile(f))
				{
					LOGERROR("ERROR READING CHEST FROM FILE %s", SourceFile.c_str());
					delete ChestEntity;
					return false;
				}
				m_BlockEntities.push_back( ChestEntity );
				break;
			}
			
			case E_BLOCK_FURNACE:
			{
				cFurnaceEntity* FurnaceEntity = new cFurnaceEntity( 0, 0, 0, m_World );
				if (!FurnaceEntity->LoadFromFile(f))
				{
					LOGERROR("ERROR READING FURNACE FROM FILE %s", SourceFile.c_str());
					delete FurnaceEntity;
					return false;
				}
				m_BlockEntities.push_back( FurnaceEntity );
				break;
			}
			
			case E_BLOCK_SIGN_POST:
			case E_BLOCK_WALLSIGN:
			{
				cSignEntity * SignEntity = new cSignEntity(BlockType, 0, 0, 0, m_World );
				if (!SignEntity->LoadFromFile( f ) )
				{
					LOGERROR("ERROR READING SIGN FROM FILE %s", SourceFile.c_str());
					delete SignEntity;
					return false;
				}
				m_BlockEntities.push_back( SignEntity );
				break;
			}
			
			default:
			{
				ASSERT(!"Unhandled block entity in file");
				break;
			}
		}
	}
	f.Close();

	// Delete old format file
	if (std::remove(SourceFile.c_str()) != 0)
	{
		LOGERROR("Could not delete file %s", SourceFile.c_str());
	}
	else
	{
		LOGINFO("Successfully deleted old format file \"%s\"", SourceFile.c_str());
	}
	m_IsDirty = false;
	return true;
}
*/





void cChunk::Broadcast( const cPacket * a_Packet, cClientHandle* a_Exclude)
{
	for (cClientHandleList::const_iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr )
	{
		if (*itr == a_Exclude)
		{
			continue;
		}
		(*itr)->Send(*a_Packet);
	}  // for itr - LoadedByClient[]
}





void cChunk::PositionToWorldPosition(int a_ChunkX, int a_ChunkY, int a_ChunkZ, int & a_X, int & a_Y, int & a_Z)
{
	a_Y = a_ChunkY;
	a_X = m_PosX * Width + a_ChunkX;
	a_Z = m_PosZ * Width + a_ChunkZ;
}





Vector3i cChunk::PositionToWorldPosition( int a_ChunkX, int a_ChunkY, int a_ChunkZ )
{
	return Vector3i( m_PosX * Width + a_ChunkX, m_PosY * Height + a_ChunkY, m_PosZ * Width + a_ChunkZ );
}





#if !C_CHUNK_USE_INLINE
# include "cChunk.inl.h"
#endif