diff options
Diffstat (limited to 'src')
305 files changed, 8126 insertions, 3189 deletions
diff --git a/src/AllocationPool.h b/src/AllocationPool.h index 61431a548..7c358cc84 100644 --- a/src/AllocationPool.h +++ b/src/AllocationPool.h @@ -45,7 +45,7 @@ class cListAllocationPool : public cAllocationPool<T> for (size_t i = 0; i < NumElementsInReserve; i++) { void * space = malloc(sizeof(T)); - if (space == NULL) + if (space == nullptr) { m_Callbacks->OnStartUsingReserve(); break; @@ -68,7 +68,7 @@ class cListAllocationPool : public cAllocationPool<T> if (m_FreeList.size() <= NumElementsInReserve) { void * space = malloc(sizeof(T)); - if (space != NULL) + if (space != nullptr) { return new(space) T; } @@ -90,7 +90,7 @@ class cListAllocationPool : public cAllocationPool<T> } virtual void Free(T * a_ptr) override { - if (a_ptr == NULL) + if (a_ptr == nullptr) { return; } diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 73de98e22..7b78578ee 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -15,7 +15,7 @@ $cfile "../Vector3.h" $cfile "../ChunkDef.h" $cfile "../BiomeDef.h" -$cfile "../../lib/inifile/iniFile.h" +$cfile "../IniFile.h" $cfile "../OSSupport/File.h" @@ -33,15 +33,27 @@ $cfile "../StringUtils.h" $cfile "../Defines.h" $cfile "../ChatColor.h" $cfile "../ClientHandle.h" +$cfile "../Entities/ArrowEntity.h" $cfile "../Entities/Entity.h" +$cfile "../Entities/EntityEffect.h" +$cfile "../Entities/ExpBottleEntity.h" +$cfile "../Entities/FireChargeEntity.h" +$cfile "../Entities/FireworkEntity.h" $cfile "../Entities/Floater.h" +$cfile "../Entities/GhastFireballEntity.h" +$cfile "../Entities/HangingEntity.h" +$cfile "../Entities/ItemFrame.h" $cfile "../Entities/Pawn.h" $cfile "../Entities/Player.h" $cfile "../Entities/Painting.h" $cfile "../Entities/Pickup.h" $cfile "../Entities/ProjectileEntity.h" +$cfile "../Entities/SplashPotionEntity.h" +$cfile "../Entities/ThrownEggEntity.h" +$cfile "../Entities/ThrownEnderPearlEntity.h" +$cfile "../Entities/ThrownSnowballEntity.h" $cfile "../Entities/TNTEntity.h" -$cfile "../Entities/EntityEffect.h" +$cfile "../Entities/WitherSkullEntity.h" $cfile "../Server.h" $cfile "../World.h" $cfile "../Inventory.h" diff --git a/src/Bindings/CMakeLists.txt b/src/Bindings/CMakeLists.txt index 930ee9771..d47579cd6 100644 --- a/src/Bindings/CMakeLists.txt +++ b/src/Bindings/CMakeLists.txt @@ -5,134 +5,133 @@ include_directories ("${PROJECT_SOURCE_DIR}/../") include_directories (".") SET (SRCS - Bindings.cpp - DeprecatedBindings.cpp - LuaChunkStay.cpp - LuaState.cpp - LuaWindow.cpp - ManualBindings.cpp - ManualBindings_RankManager.cpp - Plugin.cpp - PluginLua.cpp - PluginManager.cpp - WebPlugin.cpp + Bindings.cpp + DeprecatedBindings.cpp + LuaChunkStay.cpp + LuaState.cpp + LuaWindow.cpp + ManualBindings.cpp + ManualBindings_RankManager.cpp + Plugin.cpp + PluginLua.cpp + PluginManager.cpp + WebPlugin.cpp ) SET (HDRS - Bindings.h - DeprecatedBindings.h - LuaChunkStay.h - LuaFunctions.h - LuaState.h - LuaWindow.h - ManualBindings.h - Plugin.h - PluginLua.h - PluginManager.h - WebPlugin.h - tolua++.h + Bindings.h + DeprecatedBindings.h + LuaChunkStay.h + LuaFunctions.h + LuaState.h + LuaWindow.h + ManualBindings.h + Plugin.h + PluginLua.h + PluginManager.h + WebPlugin.h + tolua++.h ) # List all the files that are generated as part of the Bindings build process set (BINDING_OUTPUTS - ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h - ${CMAKE_CURRENT_SOURCE_DIR}/LuaState_Call.inc + ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/Bindings.h ) set(BINDING_DEPENDENCIES - tolua - ../Bindings/virtual_method_hooks.lua - ../Bindings/AllToLua.pkg - ../Bindings/gen_LuaState_Call.lua - ../Bindings/LuaFunctions.h - ../Bindings/LuaWindow.h - ../Bindings/Plugin.h - ../Bindings/PluginLua.h - ../Bindings/PluginManager.h - ../Bindings/WebPlugin.h - ../BiomeDef.h - ../BlockArea.h + tolua + ../Bindings/virtual_method_hooks.lua + ../Bindings/AllToLua.pkg + ../Bindings/LuaFunctions.h + ../Bindings/LuaWindow.h + ../Bindings/Plugin.h + ../Bindings/PluginLua.h + ../Bindings/PluginManager.h + ../Bindings/WebPlugin.h + ../BiomeDef.h + ../BlockArea.h ../BlockEntities/BeaconEntity.h - ../BlockEntities/BlockEntity.h - ../BlockEntities/BlockEntityWithItems.h - ../BlockEntities/ChestEntity.h - ../BlockEntities/DispenserEntity.h - ../BlockEntities/DropSpenserEntity.h - ../BlockEntities/DropperEntity.h - ../BlockEntities/FurnaceEntity.h - ../BlockEntities/HopperEntity.h - ../BlockEntities/JukeboxEntity.h - ../BlockEntities/NoteEntity.h - ../BlockEntities/SignEntity.h - ../BlockEntities/MobHeadEntity.h - ../BlockEntities/FlowerPotEntity.h - ../BlockID.h - ../BoundingBox.h - ../ChatColor.h - ../ChunkDef.h - ../ClientHandle.h - ../CraftingRecipes.h - ../Cuboid.h - ../Defines.h - ../Enchantments.h - ../Entities/EntityEffect.h - ../Entities/Entity.h - ../Entities/Floater.h - ../Entities/Pawn.h - ../Entities/Painting.h - ../Entities/Pickup.h - ../Entities/Player.h - ../Entities/ProjectileEntity.h - ../Entities/ArrowEntity.h - ../Entities/ThrownEggEntity.h - ../Entities/ThrownEnderPearlEntity.h - ../Entities/ExpBottleEntity.h - ../Entities/ThrownSnowballEntity.h - ../Entities/FireChargeEntity.h - ../Entities/FireworkEntity.h - ../Entities/GhastFireballEntity.h - ../Entities/TNTEntity.h - ../Entities/ExpOrb.h - ../Entities/HangingEntity.h - ../Entities/ItemFrame.h - ../Generating/ChunkDesc.h - ../Inventory.h - ../Item.h - ../ItemGrid.h - ../Mobs/Monster.h - ../OSSupport/File.h - ../Root.h - ../Server.h - ../StringUtils.h - ../Tracer.h - ../UI/Window.h - ../Vector3.h - ../WebAdmin.h - ../World.h + ../BlockEntities/BlockEntity.h + ../BlockEntities/BlockEntityWithItems.h + ../BlockEntities/ChestEntity.h + ../BlockEntities/DispenserEntity.h + ../BlockEntities/DropSpenserEntity.h + ../BlockEntities/DropperEntity.h + ../BlockEntities/FurnaceEntity.h + ../BlockEntities/HopperEntity.h + ../BlockEntities/JukeboxEntity.h + ../BlockEntities/NoteEntity.h + ../BlockEntities/SignEntity.h + ../BlockEntities/MobHeadEntity.h + ../BlockEntities/FlowerPotEntity.h + ../BlockID.h + ../BoundingBox.h + ../ChatColor.h + ../ChunkDef.h + ../ClientHandle.h + ../CraftingRecipes.h + ../Cuboid.h + ../Defines.h + ../Enchantments.h + ../Entities/ArrowEntity.h + ../Entities/Entity.h + ../Entities/EntityEffect.h + ../Entities/ExpBottleEntity.h + ../Entities/FireChargeEntity.h + ../Entities/FireworkEntity.h + ../Entities/Floater.h + ../Entities/GhastFireballEntity.h + ../Entities/HangingEntity.h + ../Entities/ItemFrame.h + ../Entities/Pawn.h + ../Entities/Player.h + ../Entities/Painting.h + ../Entities/Pickup.h + ../Entities/ProjectileEntity.h + ../Entities/SplashPotionEntity.h + ../Entities/ThrownEggEntity.h + ../Entities/ThrownEnderPearlEntity.h + ../Entities/ThrownSnowballEntity.h + ../Entities/TNTEntity.h + ../Entities/WitherSkullEntity.h + ../Generating/ChunkDesc.h + ../Inventory.h + ../Item.h + ../ItemGrid.h + ../Mobs/Monster.h + ../OSSupport/File.h + ../Root.h + ../Server.h + ../StringUtils.h + ../Tracer.h + ../UI/Window.h + ../Vector3.h + ../WebAdmin.h + ../World.h ) if (NOT MSVC) - ADD_CUSTOM_COMMAND( - # add any new generated bindings here - OUTPUT ${BINDING_OUTPUTS} + ADD_CUSTOM_COMMAND( + # add any new generated bindings here + OUTPUT ${BINDING_OUTPUTS} - # Regenerate bindings: - COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg - WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + # Regenerate bindings: + COMMAND tolua -L virtual_method_hooks.lua -o Bindings.cpp -H Bindings.h AllToLua.pkg + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} - # add any new generation dependencies here - DEPENDS ${BINDING_DEPENDENCIES} - ) + # add any new generation dependencies here + DEPENDS ${BINDING_DEPENDENCIES} + ) endif () + set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.h PROPERTIES GENERATED TRUE) -set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/LuaState_Call.inc PROPERTIES GENERATED TRUE) set_source_files_properties(${CMAKE_SOURCE_DIR}/src/Bindings/Bindings.cpp PROPERTIES COMPILE_FLAGS -Wno-error) if(NOT MSVC) - add_library(Bindings ${SRCS} ${HDRS}) + add_library(Bindings ${SRCS} ${HDRS}) - target_link_libraries(Bindings lua sqlite tolualib polarssl) + target_link_libraries(Bindings lua sqlite tolualib polarssl) endif() diff --git a/src/Bindings/DeprecatedBindings.cpp b/src/Bindings/DeprecatedBindings.cpp index 02aa15be4..ded7a0142 100644 --- a/src/Bindings/DeprecatedBindings.cpp +++ b/src/Bindings/DeprecatedBindings.cpp @@ -29,7 +29,7 @@ static int tolua_get_AllToLua_g_BlockLightValue(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushnumber(tolua_S, (lua_Number)cBlockInfo::GetLightValue((BLOCKTYPE)BlockType)); return 1; @@ -55,7 +55,7 @@ static int tolua_get_AllToLua_g_BlockSpreadLightFalloff(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushnumber(tolua_S, (lua_Number)cBlockInfo::GetSpreadLightFalloff((BLOCKTYPE)BlockType)); return 1; @@ -81,7 +81,7 @@ static int tolua_get_AllToLua_g_BlockTransparent(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsTransparent((BLOCKTYPE)BlockType)); return 1; @@ -107,7 +107,7 @@ static int tolua_get_AllToLua_g_BlockOneHitDig(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsOneHitDig((BLOCKTYPE)BlockType)); return 1; @@ -133,7 +133,7 @@ static int tolua_get_AllToLua_g_BlockPistonBreakable(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsPistonBreakable((BLOCKTYPE)BlockType)); return 1; @@ -159,7 +159,7 @@ static int tolua_get_AllToLua_g_BlockIsSnowable(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, cBlockInfo::IsSnowable((BLOCKTYPE)BlockType)); return 1; @@ -185,7 +185,7 @@ static int tolua_get_AllToLua_g_BlockIsSolid(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, (bool)cBlockInfo::IsSolid((BLOCKTYPE)BlockType)); return 1; @@ -211,7 +211,7 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) BlockType = (int)tolua_tonumber(tolua_S, 2, 0); if ((BlockType < 0) || (BlockType > E_BLOCK_MAX_TYPE_ID)) { - tolua_error(tolua_S, "array indexing out of range.", NULL); + tolua_error(tolua_S, "array indexing out of range.", nullptr); } tolua_pushboolean(tolua_S, (bool)cBlockInfo::FullyOccupiesVoxel((BLOCKTYPE)BlockType)); return 1; @@ -224,16 +224,16 @@ static int tolua_get_AllToLua_g_BlockFullyOccupiesVoxel(lua_State* tolua_S) void DeprecatedBindings::Bind(lua_State * tolua_S) { - tolua_beginmodule(tolua_S, NULL); - - tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, NULL); - tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, NULL); - tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, NULL); - tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, NULL); - tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, NULL); - tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, NULL); - tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, NULL); - tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, NULL); + tolua_beginmodule(tolua_S, nullptr); + + tolua_array(tolua_S, "g_BlockLightValue", tolua_get_AllToLua_g_BlockLightValue, nullptr); + tolua_array(tolua_S, "g_BlockSpreadLightFalloff", tolua_get_AllToLua_g_BlockSpreadLightFalloff, nullptr); + tolua_array(tolua_S, "g_BlockTransparent", tolua_get_AllToLua_g_BlockTransparent, nullptr); + tolua_array(tolua_S, "g_BlockOneHitDig", tolua_get_AllToLua_g_BlockOneHitDig, nullptr); + tolua_array(tolua_S, "g_BlockPistonBreakable", tolua_get_AllToLua_g_BlockPistonBreakable, nullptr); + tolua_array(tolua_S, "g_BlockIsSnowable", tolua_get_AllToLua_g_BlockIsSnowable, nullptr); + tolua_array(tolua_S, "g_BlockIsSolid", tolua_get_AllToLua_g_BlockIsSolid, nullptr); + tolua_array(tolua_S, "g_BlockFullyOccupiesVoxel", tolua_get_AllToLua_g_BlockFullyOccupiesVoxel, nullptr); tolua_endmodule(tolua_S); } diff --git a/src/Bindings/LuaChunkStay.cpp b/src/Bindings/LuaChunkStay.cpp index a3d3a8090..e50ffb75b 100644 --- a/src/Bindings/LuaChunkStay.cpp +++ b/src/Bindings/LuaChunkStay.cpp @@ -13,7 +13,7 @@ cLuaChunkStay::cLuaChunkStay(cPluginLua & a_Plugin) : m_Plugin(a_Plugin), - m_LuaState(NULL) + m_LuaState(nullptr) { } @@ -130,8 +130,11 @@ void cLuaChunkStay::Enable(cChunkMap & a_ChunkMap, int a_OnChunkAvailableStackPo void cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ) { - cPluginLua::cOperation Op(m_Plugin); - Op().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ); + if (m_OnChunkAvailable.IsValid()) + { + cPluginLua::cOperation Op(m_Plugin); + Op().Call((int)m_OnChunkAvailable, a_ChunkX, a_ChunkZ); + } } @@ -140,6 +143,7 @@ void cLuaChunkStay::OnChunkAvailable(int a_ChunkX, int a_ChunkZ) bool cLuaChunkStay::OnAllChunksAvailable(void) { + if (m_OnAllChunksAvailable.IsValid()) { // Call the callback: cPluginLua::cOperation Op(m_Plugin); diff --git a/src/Bindings/LuaState.cpp b/src/Bindings/LuaState.cpp index 85e3f9fc5..2f5d173fd 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -16,6 +16,8 @@ extern "C" #include "Bindings.h" #include "ManualBindings.h" #include "DeprecatedBindings.h" +#include "../Entities/Entity.h" +#include "../BlockEntities/BlockEntity.h" // fwd: SQLite/lsqlite3.c extern "C" @@ -44,7 +46,7 @@ const cLuaState::cRet cLuaState::Return = {}; // cLuaState: cLuaState::cLuaState(const AString & a_SubsystemName) : - m_LuaState(NULL), + m_LuaState(nullptr), m_IsOwned(false), m_SubsystemName(a_SubsystemName), m_NumCurrentFunctionArgs(-1) @@ -88,7 +90,7 @@ cLuaState::~cLuaState() void cLuaState::Create(void) { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { LOGWARNING("%s: Trying to create an already-existing LuaState, ignoring.", __FUNCTION__); return; @@ -117,7 +119,7 @@ void cLuaState::RegisterAPILibs(void) void cLuaState::Close(void) { - if (m_LuaState == NULL) + if (m_LuaState == nullptr) { LOGWARNING("%s: Trying to close an invalid LuaState, ignoring.", __FUNCTION__); return; @@ -132,7 +134,7 @@ void cLuaState::Close(void) return; } lua_close(m_LuaState); - m_LuaState = NULL; + m_LuaState = nullptr; m_IsOwned = false; } @@ -142,7 +144,7 @@ void cLuaState::Close(void) void cLuaState::Attach(lua_State * a_State) { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { LOGINFO("%s: Already contains a LuaState (0x%p), will be closed / detached.", __FUNCTION__, m_LuaState); if (m_IsOwned) @@ -164,7 +166,7 @@ void cLuaState::Attach(lua_State * a_State) void cLuaState::Detach(void) { - if (m_LuaState == NULL) + if (m_LuaState == nullptr) { return; } @@ -177,7 +179,7 @@ void cLuaState::Detach(void) Close(); return; } - m_LuaState = NULL; + m_LuaState = nullptr; } @@ -520,7 +522,7 @@ void cLuaState::Push(cBlockEntity * a_BlockEntity) { ASSERT(IsValid()); - tolua_pushusertype(m_LuaState, a_BlockEntity, "cBlockEntity"); + tolua_pushusertype(m_LuaState, a_BlockEntity, (a_BlockEntity == nullptr) ? "cBlockEntity" : a_BlockEntity->GetClass()); m_NumCurrentFunctionArgs += 1; } @@ -556,7 +558,61 @@ void cLuaState::Push(cEntity * a_Entity) { ASSERT(IsValid()); - tolua_pushusertype(m_LuaState, a_Entity, "cEntity"); + if (a_Entity == nullptr) + { + lua_pushnil(m_LuaState); + } + else + { + switch (a_Entity->GetEntityType()) + { + case cEntity::etMonster: + { + // Don't push specific mob types, as those are not exported in the API: + tolua_pushusertype(m_LuaState, a_Entity, "cMonster"); + break; + } + case cEntity::etPlayer: + { + tolua_pushusertype(m_LuaState, a_Entity, "cPlayer"); + break; + } + case cEntity::etPickup: + { + tolua_pushusertype(m_LuaState, a_Entity, "cPickup"); + break; + } + case cEntity::etTNT: + { + tolua_pushusertype(m_LuaState, a_Entity, "cTNTEntity"); + break; + } + case cEntity::etProjectile: + { + tolua_pushusertype(m_LuaState, a_Entity, a_Entity->GetClass()); + break; + } + case cEntity::etFloater: + { + tolua_pushusertype(m_LuaState, a_Entity, "cFloater"); + break; + } + + case cEntity::etEntity: + case cEntity::etEnderCrystal: + case cEntity::etFallingBlock: + case cEntity::etMinecart: + case cEntity::etBoat: + case cEntity::etExpOrb: + case cEntity::etItemFrame: + case cEntity::etPainting: + { + // Push the generic entity class type: + tolua_pushusertype(m_LuaState, a_Entity, "cEntity"); + } + } // switch (EntityType) + } + m_NumCurrentFunctionArgs += 1; } @@ -813,7 +869,7 @@ void cLuaState::GetStackValue(int a_StackPos, AString & a_Value) { size_t len = 0; const char * data = lua_tolstring(m_LuaState, a_StackPos, &len); - if (data != NULL) + if (data != nullptr) { a_Value.assign(data, len); } @@ -863,7 +919,7 @@ void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { - a_ReturnedVal = NULL; + a_ReturnedVal = nullptr; return; } tolua_Error err; @@ -881,7 +937,7 @@ void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal) { if (lua_isnil(m_LuaState, a_StackPos)) { - a_ReturnedVal = NULL; + a_ReturnedVal = nullptr; return; } tolua_Error err; @@ -946,7 +1002,7 @@ bool cLuaState::CheckParamUserTable(int a_StartParam, const char * a_UserTable, lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -979,7 +1035,7 @@ bool cLuaState::CheckParamUserType(int a_StartParam, const char * a_UserType, in lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1012,7 +1068,7 @@ bool cLuaState::CheckParamTable(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1045,7 +1101,7 @@ bool cLuaState::CheckParamNumber(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1078,7 +1134,7 @@ bool cLuaState::CheckParamString(int a_StartParam, int a_EndParam) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s'.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } // for i - Param @@ -1111,7 +1167,7 @@ bool cLuaState::CheckParamFunction(int a_StartParam, int a_EndParam) VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", - (entry.name != NULL) ? entry.name : "?", i, GetTypeText(i).c_str() + (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param @@ -1144,7 +1200,7 @@ bool cLuaState::CheckParamFunctionOrNil(int a_StartParam, int a_EndParam) VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); luaL_error(m_LuaState, "Error in function '%s' parameter #%d. Function expected, got %s", - (entry.name != NULL) ? entry.name : "?", i, GetTypeText(i).c_str() + (entry.name != nullptr) ? entry.name : "?", i, GetTypeText(i).c_str() ); return false; } // for i - Param @@ -1168,7 +1224,7 @@ bool cLuaState::CheckParamEnd(int a_Param) lua_Debug entry; VERIFY(lua_getstack(m_LuaState, 0, &entry)); VERIFY(lua_getinfo (m_LuaState, "n", &entry)); - AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != NULL) ? entry.name : "?"); + AString ErrMsg = Printf("#ferror in function '%s': Too many arguments.", (entry.name != nullptr) ? entry.name : "?"); tolua_error(m_LuaState, ErrMsg.c_str(), &tolua_err); return false; } @@ -1347,7 +1403,7 @@ int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_Sr case LUA_TUSERDATA: { // Get the class name: - const char * type = NULL; + const char * type = nullptr; if (lua_getmetatable(a_SrcLuaState, i) == 0) { LOGWARNING("%s: Unknown class in pos %d, cannot copy.", __FUNCTION__, i); @@ -1359,7 +1415,7 @@ int cLuaState::CopyStackFrom(cLuaState & a_SrcLuaState, int a_SrcStart, int a_Sr lua_pop(a_SrcLuaState, 1); // Stack -1 // Copy the value: - void * ud = tolua_touserdata(a_SrcLuaState, i, NULL); + void * ud = tolua_touserdata(a_SrcLuaState, i, nullptr); tolua_pushusertype(m_LuaState, ud, type); break; } @@ -1385,7 +1441,7 @@ void cLuaState::ToString(int a_StackPos, AString & a_String) { size_t len; const char * s = lua_tolstring(m_LuaState, a_StackPos, &len); - if (s != NULL) + if (s != nullptr) { a_String.assign(s, len); } @@ -1407,7 +1463,7 @@ void cLuaState::LogStack(const char * a_Header) void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header) { // Format string consisting only of %s is used to appease the compiler - LOG("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); + LOG("%s", (a_Header != nullptr) ? a_Header : "Lua C API Stack contents:"); for (int i = lua_gettop(a_LuaState); i > 0; i--) { AString Value; @@ -1444,7 +1500,7 @@ int cLuaState::ReportFnCallErrors(lua_State * a_LuaState) // cLuaState::cRef: cLuaState::cRef::cRef(void) : - m_LuaState(NULL), + m_LuaState(nullptr), m_Ref(LUA_REFNIL) { } @@ -1454,7 +1510,7 @@ cLuaState::cRef::cRef(void) : cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) : - m_LuaState(NULL), + m_LuaState(nullptr), m_Ref(LUA_REFNIL) { RefStack(a_LuaState, a_StackPos); @@ -1466,7 +1522,7 @@ cLuaState::cRef::cRef(cLuaState & a_LuaState, int a_StackPos) : cLuaState::cRef::~cRef() { - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { UnRef(); } @@ -1479,7 +1535,7 @@ cLuaState::cRef::~cRef() void cLuaState::cRef::RefStack(cLuaState & a_LuaState, int a_StackPos) { ASSERT(a_LuaState.IsValid()); - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { UnRef(); } @@ -1500,7 +1556,7 @@ void cLuaState::cRef::UnRef(void) { luaL_unref(*m_LuaState, LUA_REGISTRYINDEX, m_Ref); } - m_LuaState = NULL; + m_LuaState = nullptr; m_Ref = LUA_REFNIL; } diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index ef87c3efc..c13e36188 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -164,7 +164,7 @@ public: void Detach(void); /** Returns true if the m_LuaState is valid */ - bool IsValid(void) const { return (m_LuaState != NULL); } + bool IsValid(void) const { return (m_LuaState != nullptr); } /** Adds the specified path to package.<a_PathVariable> */ void AddPackagePath(const AString & a_PathVariable, const AString & a_Path); @@ -240,10 +240,28 @@ public: /** Retrieve value at a_StackPos, if it is a valid cWorld class. If not, a_Value is unchanged */ void GetStackValue(int a_StackPos, pWorld & a_Value); + /** Call the specified Lua function. + Returns true if call succeeded, false if there was an error. + A special param of cRet & signifies the end of param list and the start of return values. + Example call: Call(Fn, Param1, Param2, Param3, cLuaState::Return, Ret1, Ret2) */ + template <typename FnT, typename... Args> + bool Call(const FnT & a_Function, Args &&... args) + { + if (!PushFunction(a_Function)) + { + // Pushing the function failed + return false; + } + return PushCallPop(args...); + } - // Include the cLuaState::Call() overload implementation that is generated by the gen_LuaState_Call.lua script: - #include "LuaState_Call.inc" - + /** Retrieves a list of values from the Lua stack, starting at the specified index. */ + template <typename T, typename... Args> + inline void GetStackValues(int a_StartStackPos, T & a_Ret, Args &&... args) + { + GetStackValue(a_StartStackPos, a_Ret); + GetStackValues(a_StartStackPos + 1, args...); + } /** Returns true if the specified parameters on the stack are of the specified usertable type; also logs warning if not. Used for static functions */ bool CheckParamUserTable(int a_StartParam, const char * a_UserTable, int a_EndParam = -1); @@ -304,12 +322,13 @@ public: void ToString(int a_StackPos, AString & a_String); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ - void LogStack(const char * a_Header = NULL); + void LogStack(const char * a_Header = nullptr); /** Logs all the elements' types on the API stack, with an optional header for the listing. */ - static void LogStack(lua_State * a_LuaState, const char * a_Header = NULL); + static void LogStack(lua_State * a_LuaState, const char * a_Header = nullptr); protected: + lua_State * m_LuaState; /** If true, the state is owned by this object and will be auto-Closed. False => attached state */ @@ -327,6 +346,63 @@ protected: int m_NumCurrentFunctionArgs; + /** Variadic template terminator: Counting zero args returns zero. */ + int CountArgs(void) + { + return 0; + } + + /** Variadic template: Counting args means add one to the count of the rest. */ + template <typename T, typename... Args> + int CountArgs(T, Args... args) + { + return 1 + CountArgs(args...); + } + + /** Variadic template terminator: If there's nothing more to push / pop, just call the function. + Note that there are no return values either, because those are prefixed by a cRet value, so the arg list is never empty. */ + bool PushCallPop(void) + { + return CallFunction(0); + } + + /** Variadic template recursor: More params to push. Push them and recurse. */ + template <typename T, typename... Args> + inline bool PushCallPop(T a_Param, Args &&... args) + { + Push(a_Param); + return PushCallPop(args...); + } + + /** Variadic template terminator: If there's nothing more to push, but return values to collect, call the function and collect the returns. */ + template <typename... Args> + bool PushCallPop(cLuaState::cRet, Args &&... args) + { + // Calculate the number of return values (number of args left): + int NumReturns = CountArgs(args...); + + // Call the function: + if (!CallFunction(NumReturns)) + { + return false; + } + + // Collect the return values: + GetStackValues(-NumReturns, args...); + lua_pop(m_LuaState, NumReturns); + + // All successful: + return true; + } + + /** Variadic template terminator: If there are no more values to get, bail out. + This function is not available in the public API, because it's an error to request no values directly; only internal functions can do that. + If you get a compile error saying this function is not accessible, check your calling code, you aren't reading any stack values. */ + void GetStackValues(int a_StartingStackPos) + { + // Do nothing + } + /** Pushes the function of the specified name onto the stack. Returns true if successful. Logs a warning on failure (incl. m_SubsystemName) */ diff --git a/src/Bindings/LuaWindow.cpp b/src/Bindings/LuaWindow.cpp index c4d03b86b..35730878d 100644 --- a/src/Bindings/LuaWindow.cpp +++ b/src/Bindings/LuaWindow.cpp @@ -18,7 +18,7 @@ cLuaWindow::cLuaWindow(cWindow::WindowType a_WindowType, int a_SlotsX, int a_SlotsY, const AString & a_Title) : super(a_WindowType, a_Title), m_Contents(a_SlotsX, a_SlotsY), - m_Plugin(NULL), + m_Plugin(nullptr), m_LuaRef(LUA_REFNIL), m_OnClosingFnRef(LUA_REFNIL), m_OnSlotChangedFnRef(LUA_REFNIL) @@ -70,7 +70,7 @@ cLuaWindow::~cLuaWindow() void cLuaWindow::SetLuaRef(cPluginLua * a_Plugin, int a_LuaRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); ASSERT(m_LuaRef == LUA_REFNIL); m_Plugin = a_Plugin; m_LuaRef = a_LuaRef; @@ -82,7 +82,7 @@ void cLuaWindow::SetLuaRef(cPluginLua * a_Plugin, int a_LuaRef) bool cLuaWindow::IsLuaReferenced(void) const { - return ((m_Plugin != NULL) && (m_LuaRef != LUA_REFNIL)); + return ((m_Plugin != nullptr) && (m_LuaRef != LUA_REFNIL)); } @@ -92,7 +92,7 @@ bool cLuaWindow::IsLuaReferenced(void) const void cLuaWindow::SetOnClosing(cPluginLua * a_Plugin, int a_FnRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); // If there already was a function, unreference it first if (m_OnClosingFnRef != LUA_REFNIL) @@ -112,7 +112,7 @@ void cLuaWindow::SetOnClosing(cPluginLua * a_Plugin, int a_FnRef) void cLuaWindow::SetOnSlotChanged(cPluginLua * a_Plugin, int a_FnRef) { // Either m_Plugin is not set or equal to the passed plugin; only one plugin can use one cLuaWindow object - ASSERT((m_Plugin == NULL) || (m_Plugin == a_Plugin)); + ASSERT((m_Plugin == nullptr) || (m_Plugin == a_Plugin)); // If there already was a function, unreference it first if (m_OnSlotChangedFnRef != LUA_REFNIL) @@ -134,7 +134,7 @@ bool cLuaWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) // First notify the plugin through the registered callback: if (m_OnClosingFnRef != LUA_REFNIL) { - ASSERT(m_Plugin != NULL); + ASSERT(m_Plugin != nullptr); if (m_Plugin->CallbackWindowClosing(m_OnClosingFnRef, *this, a_Player, a_CanRefuse)) { // The callback disagrees (the higher levels check the CanRefuse flag compliance) @@ -153,7 +153,7 @@ void cLuaWindow::Destroy(void) { super::Destroy(); - if ((m_LuaRef != LUA_REFNIL) && (m_Plugin != NULL)) + if ((m_LuaRef != LUA_REFNIL) && (m_Plugin != nullptr)) { // The object is referenced by Lua, un-reference it m_Plugin->Unreference(m_LuaRef); diff --git a/src/Bindings/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index f643f06ec..a4a5d79b4 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -145,13 +145,13 @@ static AString GetLogMessage(lua_State * tolua_S) tolua_Error err; if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err)) { - return ((cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL))->ExtractText(); + return ((cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr))->ExtractText(); } else { size_t len = 0; const char * str = lua_tolstring(tolua_S, 1, &len); - if (str != NULL) + if (str != nullptr) { return AString(str, len); } @@ -170,7 +170,7 @@ static int tolua_LOG(lua_State * tolua_S) tolua_Error err; if (tolua_isusertype(tolua_S, 1, "cCompositeChat", false, &err)) { - LogLevel = cCompositeChat::MessageTypeToLogLevel(((cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL))->GetMessageType()); + LogLevel = cCompositeChat::MessageTypeToLogLevel(((cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr))->GetMessageType()); } // Log the message: @@ -264,7 +264,7 @@ static cPluginLua * GetLuaPlugin(lua_State * L) { LOGWARNING("%s: cannot get plugin instance, what have you done to my Lua state?", __FUNCTION__); lua_pop(L, 1); - return NULL; + return nullptr; } cPluginLua * Plugin = (cPluginLua *)lua_topointer(L, -1); lua_pop(L, 1); @@ -312,10 +312,10 @@ static int tolua_DoWith(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); const char * ItemName = tolua_tocppstring(tolua_S, 2, ""); - if ((ItemName == NULL) || (ItemName[0] == 0)) + if ((ItemName == nullptr) || (ItemName[0] == 0)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a non-empty string for parameter #1", NumArgs); } @@ -406,7 +406,7 @@ static int tolua_DoWithID(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 2 or 3 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, nullptr); int ItemID = (int)tolua_tonumber(tolua_S, 2, 0); if (!lua_isfunction(tolua_S, 3)) @@ -496,7 +496,7 @@ static int tolua_DoWithXYZ(lua_State* tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 4 or 5 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3) || !lua_isnumber(tolua_S, 4)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1, #2 and #3"); @@ -591,7 +591,7 @@ static int tolua_ForEachInChunk(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 3 or 4 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, NULL); + Ty1 * self = (Ty1 *) tolua_tousertype(tolua_S, 1, nullptr); if (!lua_isnumber(tolua_S, 2) || !lua_isnumber(tolua_S, 3)) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Expected a number for parameters #1 and #2"); @@ -694,10 +694,10 @@ static int tolua_ForEachInBox(lua_State * tolua_S) } // Get the params: - Ty1 * Self = NULL; - cBoundingBox * Box = NULL; + Ty1 * Self = nullptr; + cBoundingBox * Box = nullptr; L.GetStackValues(1, Self, Box); - if ((Self == NULL) || (Box == NULL)) + if ((Self == nullptr) || (Box == nullptr)) { LOGWARNING("Invalid world (%p) or boundingbox (%p)", Self, Box); L.LogStackTrace(); @@ -760,8 +760,8 @@ static int tolua_ForEach(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Requires 1 or 2 arguments, got %i", NumArgs); } - Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + Ty1 * self = (Ty1 *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -857,14 +857,14 @@ static int tolua_cWorld_GetBlockInfo(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetBlockInfo'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetBlockInfo'", nullptr); } #endif { @@ -912,14 +912,14 @@ static int tolua_cWorld_GetBlockTypeMeta(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetBlockTypeMeta'", nullptr); } #endif { @@ -964,14 +964,14 @@ static int tolua_cWorld_GetSignLines(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'GetSignLines'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'GetSignLines'", nullptr); } #endif { @@ -1022,7 +1022,7 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockY = (int) tolua_tonumber (tolua_S, 3, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 4, 0); @@ -1030,11 +1030,11 @@ static int tolua_cWorld_SetSignLines(lua_State * tolua_S) const AString Line2 = tolua_tocppstring(tolua_S, 6, 0); const AString Line3 = tolua_tocppstring(tolua_S, 7, 0); const AString Line4 = tolua_tocppstring(tolua_S, 8, 0); - cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, NULL); + cPlayer * Player = (cPlayer *)tolua_tousertype (tolua_S, 9, nullptr); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'SetSignLines' / 'UpdateSign'", nullptr); } #endif { @@ -1071,13 +1071,13 @@ static int tolua_cWorld_TryGetHeight(lua_State * tolua_S) else #endif { - cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, NULL); + cWorld * self = (cWorld *) tolua_tousertype (tolua_S, 1, nullptr); int BlockX = (int) tolua_tonumber (tolua_S, 2, 0); int BlockZ = (int) tolua_tonumber (tolua_S, 3, 0); #ifndef TOLUA_RELEASE - if (self == NULL) + if (self == nullptr) { - tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", NULL); + tolua_error(tolua_S, "Invalid 'self' in function 'TryGetHeight'", nullptr); } #endif { @@ -1136,15 +1136,15 @@ static int tolua_cWorld_QueueTask(lua_State * tolua_S) // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; } // Retrieve the args: - cWorld * self = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cWorld * self = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -1160,7 +1160,7 @@ static int tolua_cWorld_QueueTask(lua_State * tolua_S) return lua_do_error(tolua_S, "Error in function call '#funcname#': Could not get function reference of parameter #1"); } - self->QueueTask(new cLuaWorldTask(*Plugin, FnRef)); + self->QueueTask(make_unique<cLuaWorldTask>(*Plugin, FnRef)); return 0; } @@ -1200,7 +1200,7 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; @@ -1216,8 +1216,8 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) { return 0; } - cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (World == NULL) + cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (World == nullptr) { return lua_do_error(tolua_S, "Error in function call '#funcname#': Not called on an object instance"); } @@ -1241,7 +1241,7 @@ static int tolua_cWorld_ScheduleTask(lua_State * tolua_S) static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); const cPluginManager::PluginMap & AllPlugins = self->GetAllPlugins(); @@ -1252,7 +1252,7 @@ static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) { const cPlugin* Plugin = iter->second; tolua_pushstring(tolua_S, iter->first.c_str()); - if (Plugin != NULL) + if (Plugin != nullptr) { tolua_pushusertype(tolua_S, (void *)Plugin, "const cPlugin"); } @@ -1274,7 +1274,7 @@ static int tolua_cPluginManager_GetAllPlugins(lua_State * tolua_S) static int tolua_cPluginManager_GetCurrentPlugin(lua_State * S) { cPluginLua * Plugin = GetLuaPlugin(S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has already been printed in GetLuaPlugin() return 0; @@ -1305,7 +1305,7 @@ static int tolua_cPluginManager_AddHook_FnRef(cPluginManager * a_PluginManager, // Retrieve the cPlugin from the LuaState: cPluginLua * Plugin = GetLuaPlugin(S); - if (Plugin == NULL) + if (Plugin == nullptr) { // An error message has been already printed in GetLuaPlugin() return 0; @@ -1344,8 +1344,8 @@ static int tolua_cPluginManager_AddHook_DefFn(cPluginManager * a_PluginManager, // The arg types have already been checked // Retrieve and check the cPlugin parameter - cPluginLua * Plugin = (cPluginLua *)tolua_tousertype(S, a_ParamIdx, NULL); - if (Plugin == NULL) + cPluginLua * Plugin = (cPluginLua *)tolua_tousertype(S, a_ParamIdx, nullptr); + if (Plugin == nullptr) { LOGWARNING("cPluginManager.AddHook(): Invalid Plugin parameter, expected a valid cPlugin object. Hook not added"); S.LogStackTrace(); @@ -1370,7 +1370,7 @@ static int tolua_cPluginManager_AddHook_DefFn(cPluginManager * a_PluginManager, // Get the standard name for the callback function: const char * FnName = cPluginLua::GetHookFnName(HookType); - if (FnName == NULL) + if (FnName == nullptr) { LOGWARNING("cPluginManager.AddHook(): Unknown hook type (%d). Hook not added.", HookType); S.LogStackTrace(); @@ -1417,8 +1417,8 @@ static int tolua_cPluginManager_AddHook(lua_State * tolua_S) if (tolua_isusertype(S, 1, "cPluginManager", 0, &err)) { // Style 2 or 3, retrieve the PlgMgr instance - PlgMgr = (cPluginManager *)tolua_tousertype(S, 1, NULL); - if (PlgMgr == NULL) + PlgMgr = (cPluginManager *)tolua_tousertype(S, 1, nullptr); + if (PlgMgr == nullptr) { LOGWARNING("Malformed plugin, use cPluginManager.AddHook(HOOK_TYPE, CallbackFunction). Fixing the call for you."); S.LogStackTrace(); @@ -1465,8 +1465,8 @@ static int tolua_cPluginManager_ForEachCommand(lua_State * tolua_S) return 0; } - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARN("Error in function call 'ForEachCommand': Not called on an object instance"); return 0; @@ -1542,8 +1542,8 @@ static int tolua_cPluginManager_ForEachConsoleCommand(lua_State * tolua_S) return 0; } - cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPluginManager * self = (cPluginManager *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARN("Error in function call 'ForEachConsoleCommand': Not called on an object instance"); return 0; @@ -1617,7 +1617,7 @@ static int tolua_cPluginManager_BindCommand(lua_State * L) cPluginManager.BindCommand(Command, Permission, Function, HelpString) -- without the "self" param */ cPluginLua * Plugin = GetLuaPlugin(L); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } @@ -1687,7 +1687,7 @@ static int tolua_cPluginManager_BindConsoleCommand(lua_State * L) // Get the plugin identification out of LuaState: cPluginLua * Plugin = GetLuaPlugin(L); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } @@ -1775,7 +1775,7 @@ static int tolua_cPluginManager_CallPlugin(lua_State * tolua_S) // If requesting calling the current plugin, refuse: cPluginLua * ThisPlugin = GetLuaPlugin(L); - if (ThisPlugin == NULL) + if (ThisPlugin == nullptr) { return 0; } @@ -1843,14 +1843,14 @@ static int tolua_cWorld_ChunkStay(lua_State * tolua_S) } cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } // Read the params: - cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, NULL); - if (World == NULL) + cWorld * World = (cWorld *)tolua_tousertype(tolua_S, 1, nullptr); + if (World == nullptr) { LOGWARNING("World:ChunkStay(): invalid world parameter"); L.LogStackTrace(); @@ -1862,7 +1862,7 @@ static int tolua_cWorld_ChunkStay(lua_State * tolua_S) if (!ChunkStay->AddChunks(2)) { delete ChunkStay; - ChunkStay = NULL; + ChunkStay = nullptr; return 0; } @@ -1889,8 +1889,8 @@ static int tolua_cPlayer_GetPermissions(lua_State * tolua_S) } // Get the params: - cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; @@ -1911,15 +1911,15 @@ static int tolua_cPlayer_OpenWindow(lua_State * tolua_S) // Retrieve the plugin instance from the Lua state cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { return 0; } // Get the parameters: - cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, NULL); - cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, NULL); - if ((self == NULL) || (wnd == NULL)) + cPlayer * self = (cPlayer *)tolua_tousertype(tolua_S, 1, nullptr); + cWindow * wnd = (cWindow *)tolua_tousertype(tolua_S, 2, nullptr); + if ((self == nullptr) || (wnd == nullptr)) { LOGWARNING("%s: invalid self (%p) or wnd (%p)", __FUNCTION__, self, wnd); return 0; @@ -1992,15 +1992,15 @@ static int tolua_SetObjectCallback(lua_State * tolua_S) // Retrieve the plugin instance from the Lua state cPluginLua * Plugin = GetLuaPlugin(tolua_S); - if (Plugin == NULL) + if (Plugin == nullptr) { // Warning message has already been printed by GetLuaPlugin(), bail out silently return 0; } // Get the parameters - self and the function reference: - OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + OBJTYPE * self = (OBJTYPE *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { LOGWARNING("%s: invalid self (%p)", __FUNCTION__, self); return 0; @@ -2023,7 +2023,7 @@ static int tolua_SetObjectCallback(lua_State * tolua_S) static int tolua_cPluginLua_AddWebTab(lua_State * tolua_S) { - cPluginLua * self = (cPluginLua *)tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * self = (cPluginLua *)tolua_tousertype(tolua_S, 1, nullptr); tolua_Error tolua_err; tolua_err.array = 0; @@ -2067,7 +2067,7 @@ static int tolua_cPluginLua_AddWebTab(lua_State * tolua_S) static int tolua_cPluginLua_AddTab(lua_State* tolua_S) { - cPluginLua * self = (cPluginLua *) tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * self = (cPluginLua *) tolua_tousertype(tolua_S, 1, nullptr); LOGWARN("WARNING: Using deprecated function AddTab()! Use AddWebTab() instead. (plugin \"%s\" in folder \"%s\")", self->GetName().c_str(), self->GetDirectory().c_str() ); @@ -2087,7 +2087,7 @@ static int tolua_cPlugin_Call(lua_State * tolua_S) L.LogStackTrace(); // Retrieve the params: plugin and the function name to call - cPluginLua * TargetPlugin = (cPluginLua *) tolua_tousertype(tolua_S, 1, NULL); + cPluginLua * TargetPlugin = (cPluginLua *) tolua_tousertype(tolua_S, 1, nullptr); AString FunctionName = tolua_tostring(tolua_S, 2, ""); // Call the function: @@ -2142,7 +2142,7 @@ static int tolua_push_StringStringMap(lua_State* tolua_S, std::map< std::string, static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); return tolua_push_StringStringMap(tolua_S, self->Params); } @@ -2152,7 +2152,7 @@ static int tolua_get_HTTPRequest_Params(lua_State* tolua_S) static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); return tolua_push_StringStringMap(tolua_S, self->PostParams); } @@ -2162,7 +2162,7 @@ static int tolua_get_HTTPRequest_PostParams(lua_State* tolua_S) static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) { - HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, NULL); + HTTPRequest* self = (HTTPRequest*) tolua_tousertype(tolua_S, 1, nullptr); std::map< std::string, HTTPFormData >& FormData = self->FormData; lua_newtable(tolua_S); @@ -2185,7 +2185,7 @@ static int tolua_get_HTTPRequest_FormData(lua_State* tolua_S) static int tolua_cWebAdmin_GetPlugins(lua_State * tolua_S) { - cWebAdmin * self = (cWebAdmin *)tolua_tousertype(tolua_S, 1, NULL); + cWebAdmin * self = (cWebAdmin *)tolua_tousertype(tolua_S, 1, nullptr); const cWebAdmin::PluginList & AllPlugins = self->GetPlugins(); @@ -2266,7 +2266,7 @@ static int tolua_AllToLua_cWebAdmin_GetURLEncodedString(lua_State * tolua_S) static int tolua_cWebPlugin_GetTabNames(lua_State * tolua_S) { - cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S, 1, NULL); + cWebPlugin* self = (cWebPlugin*) tolua_tousertype(tolua_S, 1, nullptr); const cWebPlugin::TabNameList & TabNames = self->GetTabNames(); @@ -2302,8 +2302,8 @@ static int tolua_cClientHandle_SendPluginMessage(lua_State * L) { return 0; } - cClientHandle * Client = (cClientHandle *)tolua_tousertype(L, 1, NULL); - if (Client == NULL) + cClientHandle * Client = (cClientHandle *)tolua_tousertype(L, 1, nullptr); + if (Client == nullptr) { LOGWARNING("ClientHandle is nil in cClientHandle:SendPluginMessage()"); S.LogStackTrace(); @@ -2548,11 +2548,11 @@ static int Lua_ItemGrid_GetSlotCoords(lua_State * L) } { - const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, NULL); + const cItemGrid * self = (const cItemGrid *)tolua_tousertype(L, 1, nullptr); int SlotNum = (int)tolua_tonumber(L, 2, 0); - if (self == NULL) + if (self == nullptr) { - tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", NULL); + tolua_error(L, "invalid 'self' in function 'cItemGrid:GetSlotCoords'", nullptr); return 0; } int X, Y; @@ -2689,7 +2689,7 @@ static int tolua_cLineBlockTracer_Trace(lua_State * tolua_S) } // Trace: - cWorld * World = (cWorld *)tolua_tousertype(L, idx, NULL); + cWorld * World = (cWorld *)tolua_tousertype(L, idx, nullptr); cLuaBlockTracerCallbacks Callbacks(L, idx + 1); double StartX = tolua_tonumber(L, idx + 2, 0); double StartY = tolua_tonumber(L, idx + 3, 0); @@ -2719,8 +2719,8 @@ static int tolua_cRoot_GetFurnaceRecipe(lua_State * tolua_S) } // Check the input param: - cItem * Input = (cItem *)tolua_tousertype(L, 2, NULL); - if (Input == NULL) + cItem * Input = (cItem *)tolua_tousertype(L, 2, nullptr); + if (Input == nullptr) { LOGWARNING("cRoot:GetFurnaceRecipe: the Input parameter is nil or missing."); return 0; @@ -2729,7 +2729,7 @@ static int tolua_cRoot_GetFurnaceRecipe(lua_State * tolua_S) // Get the recipe for the input cFurnaceRecipe * FR = cRoot::Get()->GetFurnaceRecipe(); const cFurnaceRecipe::cRecipe * Recipe = FR->GetRecipeFrom(*Input); - if (Recipe == NULL) + if (Recipe == nullptr) { // There is no such furnace recipe for this input, return no value return 0; @@ -2760,10 +2760,10 @@ static int tolua_cHopperEntity_GetOutputBlockPos(lua_State * tolua_S) { return 0; } - cHopperEntity * self = (cHopperEntity *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cHopperEntity * self = (cHopperEntity *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cHopperEntity::GetOutputBlockPos()'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cHopperEntity::GetOutputBlockPos()'", nullptr); return 0; } @@ -2800,10 +2800,10 @@ static int tolua_cBlockArea_GetBlockTypeMeta(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr); return 0; } int BlockX = (int)tolua_tonumber(tolua_S, 2, 0); @@ -2834,10 +2834,10 @@ static int tolua_cBlockArea_GetOrigin(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetOrigin'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetOrigin'", nullptr); return 0; } @@ -2866,10 +2866,10 @@ static int tolua_cBlockArea_GetRelBlockTypeMeta(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetRelBlockTypeMeta'", nullptr); return 0; } int BlockX = (int)tolua_tonumber(tolua_S, 2, 0); @@ -2900,10 +2900,10 @@ static int tolua_cBlockArea_GetSize(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr); return 0; } @@ -2931,10 +2931,10 @@ static int tolua_cBlockArea_GetCoordRange(lua_State * tolua_S) return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea:GetSize'", nullptr); return 0; } @@ -2962,10 +2962,10 @@ static int tolua_cBlockArea_LoadFromSchematicFile(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr); return 0; } @@ -2992,10 +2992,10 @@ static int tolua_cBlockArea_LoadFromSchematicString(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::LoadFromSchematicFile'", nullptr); return 0; } @@ -3023,10 +3023,10 @@ static int tolua_cBlockArea_SaveToSchematicFile(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr); return 0; } AString Filename = tolua_tostring(tolua_S, 2, 0); @@ -3051,10 +3051,10 @@ static int tolua_cBlockArea_SaveToSchematicString(lua_State * tolua_S) { return 0; } - cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cBlockArea * self = (cBlockArea *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cBlockArea::SaveToSchematicFile'", nullptr); return 0; } @@ -3085,10 +3085,10 @@ static int tolua_cCompositeChat_AddRunCommandPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddRunCommandPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddRunCommandPart'", nullptr); return 0; } @@ -3122,10 +3122,10 @@ static int tolua_cCompositeChat_AddSuggestCommandPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddSuggestCommandPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddSuggestCommandPart'", nullptr); return 0; } @@ -3159,10 +3159,10 @@ static int tolua_cCompositeChat_AddTextPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddTextPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddTextPart'", nullptr); return 0; } @@ -3195,10 +3195,10 @@ static int tolua_cCompositeChat_AddUrlPart(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddUrlPart'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:AddUrlPart'", nullptr); return 0; } @@ -3232,10 +3232,10 @@ static int tolua_cCompositeChat_ParseText(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:ParseText'", nullptr); return 0; } @@ -3267,10 +3267,10 @@ static int tolua_cCompositeChat_SetMessageType(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:SetMessageType'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:SetMessageType'", nullptr); return 0; } @@ -3299,10 +3299,10 @@ static int tolua_cCompositeChat_UnderlineUrls(lua_State * tolua_S) { return 0; } - cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, NULL); - if (self == NULL) + cCompositeChat * self = (cCompositeChat *)tolua_tousertype(tolua_S, 1, nullptr); + if (self == nullptr) { - tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:UnderlineUrls'", NULL); + tolua_error(tolua_S, "invalid 'self' in function 'cCompositeChat:UnderlineUrls'", nullptr); return 0; } @@ -3320,7 +3320,7 @@ static int tolua_cCompositeChat_UnderlineUrls(lua_State * tolua_S) void ManualBindings::Bind(lua_State * tolua_S) { - tolua_beginmodule(tolua_S, NULL); + tolua_beginmodule(tolua_S, nullptr); tolua_function(tolua_S, "Clamp", tolua_Clamp); tolua_function(tolua_S, "StringSplit", tolua_StringSplit); tolua_function(tolua_S, "StringSplitAndTrim", tolua_StringSplitAndTrim); @@ -3447,7 +3447,7 @@ void ManualBindings::Bind(lua_State * tolua_S) tolua_function(tolua_S, "AddWebTab", tolua_cPluginLua_AddWebTab); tolua_endmodule(tolua_S); - tolua_cclass(tolua_S, "HTTPRequest", "HTTPRequest", "", NULL); + tolua_cclass(tolua_S, "HTTPRequest", "HTTPRequest", "", nullptr); tolua_beginmodule(tolua_S, "HTTPRequest"); // tolua_variable(tolua_S, "Method", tolua_get_HTTPRequest_Method, tolua_set_HTTPRequest_Method); // tolua_variable(tolua_S, "Path", tolua_get_HTTPRequest_Path, tolua_set_HTTPRequest_Path); diff --git a/src/Bindings/ManualBindings_RankManager.cpp b/src/Bindings/ManualBindings_RankManager.cpp index 3c58a0a92..fa1b88b6a 100644 --- a/src/Bindings/ManualBindings_RankManager.cpp +++ b/src/Bindings/ManualBindings_RankManager.cpp @@ -34,7 +34,7 @@ static int tolua_cRankManager_AddGroup(lua_State * L) S.GetStackValue(2, GroupName); // Add the group: - cRoot::Get()->GetRankManager().AddGroup(GroupName); + cRoot::Get()->GetRankManager()->AddGroup(GroupName); return 0; } @@ -63,7 +63,7 @@ static int tolua_cRankManager_AddGroupToRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Add the group to the rank: - S.Push(cRoot::Get()->GetRankManager().AddGroupToRank(GroupName, RankName)); + S.Push(cRoot::Get()->GetRankManager()->AddGroupToRank(GroupName, RankName)); return 1; } @@ -92,7 +92,7 @@ static int tolua_cRankManager_AddPermissionToGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Add the group to the rank: - S.Push(cRoot::Get()->GetRankManager().AddPermissionToGroup(Permission, GroupName)); + S.Push(cRoot::Get()->GetRankManager()->AddPermissionToGroup(Permission, GroupName)); return 1; } @@ -121,7 +121,7 @@ static int tolua_cRankManager_AddRank(lua_State * L) S.GetStackValues(2, RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); // Add the rank: - cRoot::Get()->GetRankManager().AddRank(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); + cRoot::Get()->GetRankManager()->AddRank(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); return 0; } @@ -142,7 +142,7 @@ static int tolua_cRankManager_ClearPlayerRanks(lua_State * L) } // Remove all players: - cRoot::Get()->GetRankManager().ClearPlayerRanks(); + cRoot::Get()->GetRankManager()->ClearPlayerRanks(); return 1; } @@ -166,7 +166,7 @@ static int tolua_cRankManager_GetAllGroups(lua_State * L) } // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetAllGroups(); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetAllGroups(); // Push the results: S.Push(Groups); @@ -193,7 +193,7 @@ static int tolua_cRankManager_GetAllPermissions(lua_State * L) } // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetAllPermissions(); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetAllPermissions(); // Push the results: S.Push(Permissions); @@ -220,7 +220,7 @@ static int tolua_cRankManager_GetAllPlayerUUIDs(lua_State * L) } // Get the player uuid's: - AStringVector Players = cRoot::Get()->GetRankManager().GetAllPlayerUUIDs(); + AStringVector Players = cRoot::Get()->GetRankManager()->GetAllPlayerUUIDs(); // Push the results: S.Push(Players); @@ -247,7 +247,7 @@ static int tolua_cRankManager_GetAllRanks(lua_State * L) } // Get the ranks: - AStringVector Ranks = cRoot::Get()->GetRankManager().GetAllRanks(); + AStringVector Ranks = cRoot::Get()->GetRankManager()->GetAllRanks(); // Push the results: S.Push(Ranks); @@ -274,7 +274,7 @@ static int tolua_cRankManager_GetDefaultRank(lua_State * L) } // Return the rank name: - S.Push(cRoot::Get()->GetRankManager().GetDefaultRank()); + S.Push(cRoot::Get()->GetRankManager()->GetDefaultRank()); return 1; } @@ -303,7 +303,7 @@ static int tolua_cRankManager_GetGroupPermissions(lua_State * L) S.GetStackValue(2, GroupName); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetGroupPermissions(GroupName); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetGroupPermissions(GroupName); // Push the results: S.Push(Permissions); @@ -335,7 +335,7 @@ static int tolua_cRankManager_GetPlayerGroups(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetPlayerGroups(PlayerUUID); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetPlayerGroups(PlayerUUID); // Push the results: S.Push(Groups); @@ -368,7 +368,7 @@ static int tolua_cRankManager_GetPlayerMsgVisuals(lua_State * L) // Get the permissions: AString MsgPrefix, MsgSuffix, MsgNameColorCode; - if (!cRoot::Get()->GetRankManager().GetPlayerMsgVisuals(PlayerUUID, MsgPrefix, MsgSuffix, MsgNameColorCode)) + if (!cRoot::Get()->GetRankManager()->GetPlayerMsgVisuals(PlayerUUID, MsgPrefix, MsgSuffix, MsgNameColorCode)) { return 0; } @@ -405,7 +405,7 @@ static int tolua_cRankManager_GetPlayerPermissions(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetPlayerPermissions(PlayerUUID); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetPlayerPermissions(PlayerUUID); // Push the results: S.Push(Permissions); @@ -437,7 +437,7 @@ static int tolua_cRankManager_GetPlayerRankName(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the rank name: - AString RankName = cRoot::Get()->GetRankManager().GetPlayerRankName(PlayerUUID); + AString RankName = cRoot::Get()->GetRankManager()->GetPlayerRankName(PlayerUUID); // Push the result: S.Push(RankName); @@ -469,7 +469,7 @@ static int tolua_cRankManager_GetPlayerName(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the player name: - AString PlayerName = cRoot::Get()->GetRankManager().GetPlayerName(PlayerUUID); + AString PlayerName = cRoot::Get()->GetRankManager()->GetPlayerName(PlayerUUID); // Push the result: S.Push(PlayerName); @@ -501,7 +501,7 @@ static int tolua_cRankManager_GetRankGroups(lua_State * L) S.GetStackValue(2, RankName); // Get the groups: - AStringVector Groups = cRoot::Get()->GetRankManager().GetRankGroups(RankName); + AStringVector Groups = cRoot::Get()->GetRankManager()->GetRankGroups(RankName); // Push the results: S.Push(Groups); @@ -533,7 +533,7 @@ static int tolua_cRankManager_GetRankPermissions(lua_State * L) S.GetStackValue(2, RankName); // Get the permissions: - AStringVector Permissions = cRoot::Get()->GetRankManager().GetRankPermissions(RankName); + AStringVector Permissions = cRoot::Get()->GetRankManager()->GetRankPermissions(RankName); // Push the results: S.Push(Permissions); @@ -566,7 +566,7 @@ static int tolua_cRankManager_GetRankVisuals(lua_State * L) // Get the visuals: AString MsgPrefix, MsgSuffix, MsgNameColorCode; - if (!cRoot::Get()->GetRankManager().GetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)) + if (!cRoot::Get()->GetRankManager()->GetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode)) { // No such rank, return nothing: return 0; @@ -604,7 +604,7 @@ static int tolua_cRankManager_GroupExists(lua_State * L) S.GetStackValue(2, GroupName); // Get the response: - bool res = cRoot::Get()->GetRankManager().GroupExists(GroupName); + bool res = cRoot::Get()->GetRankManager()->GroupExists(GroupName); // Push the result: S.Push(res); @@ -636,7 +636,7 @@ static int tolua_cRankManager_IsGroupInRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsGroupInRank(GroupName, RankName); + bool res = cRoot::Get()->GetRankManager()->IsGroupInRank(GroupName, RankName); // Push the result: S.Push(res); @@ -668,7 +668,7 @@ static int tolua_cRankManager_IsPermissionInGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsPermissionInGroup(Permission, GroupName); + bool res = cRoot::Get()->GetRankManager()->IsPermissionInGroup(Permission, GroupName); // Push the result: S.Push(res); @@ -700,7 +700,7 @@ static int tolua_cRankManager_IsPlayerRankSet(lua_State * L) S.GetStackValue(2, PlayerUUID); // Get the response: - bool res = cRoot::Get()->GetRankManager().IsPlayerRankSet(PlayerUUID); + bool res = cRoot::Get()->GetRankManager()->IsPlayerRankSet(PlayerUUID); // Push the result: S.Push(res); @@ -732,7 +732,7 @@ static int tolua_cRankManager_RankExists(lua_State * L) S.GetStackValue(2, RankName); // Get the response: - bool res = cRoot::Get()->GetRankManager().RankExists(RankName); + bool res = cRoot::Get()->GetRankManager()->RankExists(RankName); // Push the result: S.Push(res); @@ -764,7 +764,7 @@ static int tolua_cRankManager_RemoveGroup(lua_State * L) S.GetStackValue(2, GroupName); // Remove the group: - cRoot::Get()->GetRankManager().RemoveGroup(GroupName); + cRoot::Get()->GetRankManager()->RemoveGroup(GroupName); return 0; } @@ -793,7 +793,7 @@ static int tolua_cRankManager_RemoveGroupFromRank(lua_State * L) S.GetStackValues(2, GroupName, RankName); // Remove the group: - cRoot::Get()->GetRankManager().RemoveGroupFromRank(GroupName, RankName); + cRoot::Get()->GetRankManager()->RemoveGroupFromRank(GroupName, RankName); return 0; } @@ -822,7 +822,7 @@ static int tolua_cRankManager_RemovePermissionFromGroup(lua_State * L) S.GetStackValues(2, Permission, GroupName); // Remove the group: - cRoot::Get()->GetRankManager().RemovePermissionFromGroup(Permission, GroupName); + cRoot::Get()->GetRankManager()->RemovePermissionFromGroup(Permission, GroupName); return 0; } @@ -851,7 +851,7 @@ static int tolua_cRankManager_RemovePlayerRank(lua_State * L) S.GetStackValue(2, PlayerUUID); // Remove the player's rank: - cRoot::Get()->GetRankManager().RemovePlayerRank(PlayerUUID); + cRoot::Get()->GetRankManager()->RemovePlayerRank(PlayerUUID); return 0; } @@ -881,7 +881,7 @@ static int tolua_cRankManager_RemoveRank(lua_State * L) S.GetStackValues(2, RankName, ReplacementRankName); // Remove the rank: - cRoot::Get()->GetRankManager().RemoveRank(RankName, ReplacementRankName); + cRoot::Get()->GetRankManager()->RemoveRank(RankName, ReplacementRankName); return 0; } @@ -910,7 +910,7 @@ static int tolua_cRankManager_RenameGroup(lua_State * L) S.GetStackValues(2, OldName, NewName); // Remove the group: - bool res = cRoot::Get()->GetRankManager().RenameGroup(OldName, NewName); + bool res = cRoot::Get()->GetRankManager()->RenameGroup(OldName, NewName); // Push the result: S.Push(res); @@ -942,7 +942,7 @@ static int tolua_cRankManager_RenameRank(lua_State * L) S.GetStackValues(2, OldName, NewName); // Remove the rank: - bool res = cRoot::Get()->GetRankManager().RenameRank(OldName, NewName); + bool res = cRoot::Get()->GetRankManager()->RenameRank(OldName, NewName); // Push the result: S.Push(res); @@ -974,7 +974,7 @@ static int tolua_cRankManager_SetDefaultRank(lua_State * L) S.GetStackValue(2, RankName); // Set the rank, return the result: - S.Push(cRoot::Get()->GetRankManager().SetDefaultRank(RankName)); + S.Push(cRoot::Get()->GetRankManager()->SetDefaultRank(RankName)); return 1; } @@ -1003,7 +1003,7 @@ static int tolua_cRankManager_SetPlayerRank(lua_State * L) S.GetStackValues(2, PlayerUUID, PlayerName, RankName); // Set the rank: - cRoot::Get()->GetRankManager().SetPlayerRank(PlayerUUID, PlayerName, RankName); + cRoot::Get()->GetRankManager()->SetPlayerRank(PlayerUUID, PlayerName, RankName); return 0; } @@ -1032,7 +1032,7 @@ static int tolua_cRankManager_SetRankVisuals(lua_State * L) S.GetStackValues(2, RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); // Set the visuals: - cRoot::Get()->GetRankManager().SetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); + cRoot::Get()->GetRankManager()->SetRankVisuals(RankName, MsgPrefix, MsgSuffix, MsgNameColorCode); return 0; } @@ -1044,7 +1044,7 @@ void ManualBindings::BindRankManager(lua_State * tolua_S) { // Create the cRankManager class in the API: tolua_usertype(tolua_S, "cRankManager"); - tolua_cclass(tolua_S, "cRankManager", "cRankManager", "", NULL); + tolua_cclass(tolua_S, "cRankManager", "cRankManager", "", nullptr); // Fill in the functions (alpha-sorted): tolua_beginmodule(tolua_S, "cRankManager"); diff --git a/src/Bindings/Plugin.h b/src/Bindings/Plugin.h index fb22dd33e..8cc9ff0cd 100644 --- a/src/Bindings/Plugin.h +++ b/src/Bindings/Plugin.h @@ -45,26 +45,26 @@ public: virtual void Tick(float a_Dt) = 0; /** Calls the specified hook with the params given. Returns the bool that the hook callback returns.*/ - virtual bool OnBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; - virtual bool OnBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; - virtual bool OnChat (cPlayer * a_Player, AString & a_Message) = 0; - virtual bool OnChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0; - virtual bool OnChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; - virtual bool OnChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; - virtual bool OnChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0; - virtual bool OnChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ) = 0; - virtual bool OnCollectingPickup (cPlayer * a_Player, cPickup * a_Pickup) = 0; - virtual bool OnCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0; + virtual bool OnBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; + virtual bool OnBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; + virtual bool OnChat (cPlayer & a_Player, AString & a_Message) = 0; + virtual bool OnChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0; + virtual bool OnChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; + virtual bool OnChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) = 0; + virtual bool OnChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0; + virtual bool OnChunkUnloading (cWorld & a_World, int a_ChunkX, int a_ChunkZ) = 0; + virtual bool OnCollectingPickup (cPlayer & a_Player, cPickup & a_Pickup) = 0; + virtual bool OnCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) = 0; virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) = 0; virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) = 0; virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) = 0; virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0; virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) = 0; - virtual bool OnHandshake (cClientHandle * a_Client, const AString & a_Username) = 0; + virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) = 0; virtual bool OnHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum) = 0; virtual bool OnHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum) = 0; virtual bool OnKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) = 0; - virtual bool OnLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) = 0; + virtual bool OnLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) = 0; virtual bool OnPlayerAnimation (cPlayer & a_Player, int a_Animation) = 0; virtual bool OnPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0; virtual bool OnPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) = 0; @@ -89,8 +89,8 @@ public: virtual bool OnPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) = 0; virtual bool OnPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message) = 0; virtual bool OnPluginsLoaded (void) = 0; - virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0; - virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) = 0; + virtual bool OnPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0; + virtual bool OnPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) = 0; virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos) = 0; virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) = 0; virtual bool OnServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon) = 0; @@ -99,8 +99,8 @@ public: virtual bool OnSpawningEntity (cWorld & a_World, cEntity & a_Entity) = 0; virtual bool OnSpawningMonster (cWorld & a_World, cMonster & a_Monster) = 0; virtual bool OnTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) = 0; - virtual bool OnUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) = 0; - virtual bool OnUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) = 0; + virtual bool OnUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) = 0; + virtual bool OnUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) = 0; virtual bool OnWeatherChanged (cWorld & a_World) = 0; virtual bool OnWeatherChanging (cWorld & a_World, eWeather & a_NewWeather) = 0; virtual bool OnWorldStarted (cWorld & a_World) = 0; @@ -110,7 +110,7 @@ public: Command permissions have already been checked. Returns true if command handled successfully */ - virtual bool HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) = 0; + virtual bool HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) = 0; /** Handles the console command split into a_Split. Returns true if command handled successfully. Output is to be sent to the a_Output callback. diff --git a/src/Bindings/PluginLua.cpp b/src/Bindings/PluginLua.cpp index 2629eb641..391d8bcbe 100644 --- a/src/Bindings/PluginLua.cpp +++ b/src/Bindings/PluginLua.cpp @@ -202,14 +202,14 @@ void cPluginLua::Tick(float a_Dt) -bool cPluginLua::OnBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) +bool cPluginLua::OnBlockSpread(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_BLOCK_SPREAD]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Source, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Source, cLuaState::Return, res); if (res) { return true; @@ -222,14 +222,14 @@ bool cPluginLua::OnBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int -bool cPluginLua::OnBlockToPickups(cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) +bool cPluginLua::OnBlockToPickups(cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_BLOCK_TO_PICKUPS]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, &a_Pickups, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, &a_Pickups, cLuaState::Return, res); if (res) { return true; @@ -242,14 +242,14 @@ bool cPluginLua::OnBlockToPickups(cWorld * a_World, cEntity * a_Digger, int a_Bl -bool cPluginLua::OnChat(cPlayer * a_Player, AString & a_Message) +bool cPluginLua::OnChat(cPlayer & a_Player, AString & a_Message) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHAT]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Message, cLuaState::Return, res, a_Message); + m_LuaState.Call((int)(**itr), &a_Player, a_Message, cLuaState::Return, res, a_Message); if (res) { return true; @@ -262,14 +262,14 @@ bool cPluginLua::OnChat(cPlayer * a_Player, AString & a_Message) -bool cPluginLua::OnChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkAvailable(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_AVAILABLE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -282,14 +282,14 @@ bool cPluginLua::OnChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginLua::OnChunkGenerated(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_GENERATED]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); if (res) { return true; @@ -302,14 +302,14 @@ bool cPluginLua::OnChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, -bool cPluginLua::OnChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginLua::OnChunkGenerating(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_GENERATING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, a_ChunkDesc, cLuaState::Return, res); if (res) { return true; @@ -322,14 +322,14 @@ bool cPluginLua::OnChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, -bool cPluginLua::OnChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkUnloaded(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_UNLOADED]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -342,14 +342,14 @@ bool cPluginLua::OnChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginLua::OnChunkUnloading(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CHUNK_UNLOADING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_ChunkX, a_ChunkZ, cLuaState::Return, res); if (res) { return true; @@ -362,14 +362,14 @@ bool cPluginLua::OnChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) -bool cPluginLua::OnCollectingPickup(cPlayer * a_Player, cPickup * a_Pickup) +bool cPluginLua::OnCollectingPickup(cPlayer & a_Player, cPickup & a_Pickup) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_COLLECTING_PICKUP]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Pickup, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Pickup, cLuaState::Return, res); if (res) { return true; @@ -382,14 +382,14 @@ bool cPluginLua::OnCollectingPickup(cPlayer * a_Player, cPickup * a_Pickup) -bool cPluginLua::OnCraftingNoRecipe(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnCraftingNoRecipe(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_CRAFTING_NO_RECIPE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), (cPlayer *)a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -471,12 +471,12 @@ bool cPluginLua::OnExploded(cWorld & a_World, double a_ExplosionSize, bool a_Can { switch (a_Source) { - case esOther: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; - case esPrimedTNT: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cTNTEntity *)a_SourceData, cLuaState::Return, res); break; - case esMonster: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cMonster *)a_SourceData, cLuaState::Return, res); break; - case esBed: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; - case esEnderCrystal: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; - case esGhastFireball: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; + case esOther: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; + case esPrimedTNT: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cTNTEntity *)a_SourceData, cLuaState::Return, res); break; + case esMonster: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (cMonster *)a_SourceData, cLuaState::Return, res); break; + case esBed: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; + case esEnderCrystal: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, (Vector3i *)a_SourceData, cLuaState::Return, res); break; + case esGhastFireball: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; case esWitherSkullBlack: case esWitherSkullBlue: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; case esWitherBirth: m_LuaState.Call((int)(**itr), &a_World, a_ExplosionSize, a_CanCauseFire, a_X, a_Y, a_Z, a_Source, a_SourceData, cLuaState::Return, res); break; @@ -536,14 +536,14 @@ bool cPluginLua::OnExploding(cWorld & a_World, double & a_ExplosionSize, bool & -bool cPluginLua::OnHandshake(cClientHandle * a_Client, const AString & a_Username) +bool cPluginLua::OnHandshake(cClientHandle & a_Client, const AString & a_Username) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_HANDSHAKE]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Client, a_Username, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Client, a_Username, cLuaState::Return, res); if (res) { return true; @@ -617,14 +617,14 @@ bool cPluginLua::OnKilling(cEntity & a_Victim, cEntity * a_Killer, TakeDamageInf -bool cPluginLua::OnLogin(cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) +bool cPluginLua::OnLogin(cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_LOGIN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Client, a_ProtocolVersion, a_Username, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Client, a_ProtocolVersion, a_Username, cLuaState::Return, res); if (res) { return true; @@ -784,7 +784,7 @@ bool cPluginLua::OnPlayerFishing(cPlayer & a_Player, cItems & a_Reward) cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PLAYER_FISHING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), &a_Player, a_Reward, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Reward, cLuaState::Return, res); if (res) { return true; @@ -1115,14 +1115,14 @@ bool cPluginLua::OnPluginsLoaded(void) -bool cPluginLua::OnPostCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnPostCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_POST_CRAFTING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -1135,14 +1135,14 @@ bool cPluginLua::OnPostCrafting(const cPlayer * a_Player, const cCraftingGrid * -bool cPluginLua::OnPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginLua::OnPreCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { cCSLock Lock(m_CriticalSection); bool res = false; cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_PRE_CRAFTING]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_Player, a_Grid, a_Recipe, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_Player, &a_Grid, &a_Recipe, cLuaState::Return, res); if (res) { return true; @@ -1316,7 +1316,7 @@ bool cPluginLua::OnTakeDamage(cEntity & a_Receiver, TakeDamageInfo & a_TDI) bool cPluginLua::OnUpdatedSign( - cWorld * a_World, + cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player @@ -1327,7 +1327,7 @@ bool cPluginLua::OnUpdatedSign( cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_UPDATED_SIGN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res); if (res) { return true; @@ -1341,7 +1341,7 @@ bool cPluginLua::OnUpdatedSign( bool cPluginLua::OnUpdatingSign( - cWorld * a_World, + cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player @@ -1352,7 +1352,7 @@ bool cPluginLua::OnUpdatingSign( cLuaRefs & Refs = m_HookMap[cPluginManager::HOOK_UPDATING_SIGN]; for (cLuaRefs::iterator itr = Refs.begin(), end = Refs.end(); itr != end; ++itr) { - m_LuaState.Call((int)(**itr), a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res, a_Line1, a_Line2, a_Line3, a_Line4); + m_LuaState.Call((int)(**itr), &a_World, a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4, a_Player, cLuaState::Return, res, a_Line1, a_Line2, a_Line3, a_Line4); if (res) { return true; @@ -1435,7 +1435,7 @@ bool cPluginLua::OnWorldTick(cWorld & a_World, float a_Dt, int a_LastTickDuratio -bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) +bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) { ASSERT(!a_Split.empty()); CommandMap::iterator cmd = m_Commands.find(a_Split[0]); @@ -1447,7 +1447,7 @@ bool cPluginLua::HandleCommand(const AStringVector & a_Split, cPlayer * a_Player cCSLock Lock(m_CriticalSection); bool res = false; - m_LuaState.Call(cmd->second, a_Split, a_Player, cLuaState::Return, res); + m_LuaState.Call(cmd->second, a_Split, &a_Player, cLuaState::Return, res); return res; } @@ -1487,7 +1487,7 @@ void cPluginLua::ClearCommands(void) cCSLock Lock(m_CriticalSection); // Unreference the bound functions so that Lua can GC them - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { for (CommandMap::iterator itr = m_Commands.begin(), end = m_Commands.end(); itr != end; ++itr) { @@ -1506,7 +1506,7 @@ void cPluginLua::ClearConsoleCommands(void) cCSLock Lock(m_CriticalSection); // Unreference the bound functions so that Lua can GC them - if (m_LuaState != NULL) + if (m_LuaState != nullptr) { for (CommandMap::iterator itr = m_ConsoleCommands.begin(), end = m_ConsoleCommands.end(); itr != end; ++itr) { @@ -1523,7 +1523,7 @@ void cPluginLua::ClearConsoleCommands(void) bool cPluginLua::CanAddOldStyleHook(int a_HookType) { const char * FnName = GetHookFnName(a_HookType); - if (FnName == NULL) + if (FnName == nullptr) { // Unknown hook ID LOGWARNING("Plugin %s wants to add an unknown hook ID (%d). The plugin need not work properly.", @@ -1614,7 +1614,7 @@ const char * cPluginLua::GetHookFnName(int a_HookType) } // switch (a_Hook) LOGWARNING("Requested name of an unknown hook type function: %d (max is %d)", a_HookType, cPluginManager::HOOK_MAX); ASSERT(!"Unknown hook requested!"); - return NULL; + return nullptr; } @@ -1627,12 +1627,12 @@ bool cPluginLua::AddHookRef(int a_HookType, int a_FnRefIdx) // Check if the function reference is valid: cLuaState::cRef * Ref = new cLuaState::cRef(m_LuaState, a_FnRefIdx); - if ((Ref == NULL) || !Ref->IsValid()) + if ((Ref == nullptr) || !Ref->IsValid()) { LOGWARNING("Plugin %s tried to add a hook %d with bad handler function.", GetName().c_str(), a_HookType); m_LuaState.LogStackTrace(); delete Ref; - Ref = NULL; + Ref = nullptr; return false; } @@ -1700,7 +1700,7 @@ AString cPluginLua::HandleWebRequest(const HTTPRequest * a_Request) } } - if (Tab != NULL) + if (Tab != nullptr) { AString Contents = Printf("WARNING: WebPlugin tab '%s' did not return a string!", Tab->Title.c_str()); if (!m_LuaState.Call(Tab->UserData, a_Request, cLuaState::Return, Contents)) diff --git a/src/Bindings/PluginLua.h b/src/Bindings/PluginLua.h index eda65b76c..6bb134efc 100644 --- a/src/Bindings/PluginLua.h +++ b/src/Bindings/PluginLua.h @@ -69,26 +69,26 @@ public: virtual void Tick(float a_Dt) override; - virtual bool OnBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) override; - virtual bool OnBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override; - virtual bool OnChat (cPlayer * a_Player, AString & a_Message) override; - virtual bool OnChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override; - virtual bool OnChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; - virtual bool OnChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; - virtual bool OnChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override; - virtual bool OnChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ) override; - virtual bool OnCollectingPickup (cPlayer * a_Player, cPickup * a_Pickup) override; - virtual bool OnCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override; + virtual bool OnBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) override; + virtual bool OnBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override; + virtual bool OnChat (cPlayer & a_Player, AString & a_Message) override; + virtual bool OnChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ) override; + virtual bool OnChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; + virtual bool OnChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) override; + virtual bool OnChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ) override; + virtual bool OnChunkUnloading (cWorld & a_World, int a_ChunkX, int a_ChunkZ) override; + virtual bool OnCollectingPickup (cPlayer & a_Player, cPickup & a_Pickup) override; + virtual bool OnCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) override; virtual bool OnDisconnect (cClientHandle & a_Client, const AString & a_Reason) override; virtual bool OnEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier) override; virtual bool OnExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split) override; virtual bool OnExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override; virtual bool OnExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData) override; - virtual bool OnHandshake (cClientHandle * a_Client, const AString & a_Username) override; + virtual bool OnHandshake (cClientHandle & a_Client, const AString & a_Username) override; virtual bool OnHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum) override; virtual bool OnHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum) override; virtual bool OnKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI) override; - virtual bool OnLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) override; + virtual bool OnLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) override; virtual bool OnPlayerAnimation (cPlayer & a_Player, int a_Animation) override; virtual bool OnPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; virtual bool OnPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) override; @@ -113,8 +113,8 @@ public: virtual bool OnPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ) override; virtual bool OnPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message) override; virtual bool OnPluginsLoaded (void) override; - virtual bool OnPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override; - virtual bool OnPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) override; + virtual bool OnPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) override; + virtual bool OnPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) override; virtual bool OnProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos) override; virtual bool OnProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity) override; virtual bool OnServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon) override; @@ -123,14 +123,14 @@ public: virtual bool OnSpawningEntity (cWorld & a_World, cEntity & a_Entity) override; virtual bool OnSpawningMonster (cWorld & a_World, cMonster & a_Monster) override; virtual bool OnTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TakeDamageInfo) override; - virtual bool OnUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) override; - virtual bool OnUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) override; + virtual bool OnUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) override; + virtual bool OnUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) override; virtual bool OnWeatherChanged (cWorld & a_World) override; virtual bool OnWeatherChanging (cWorld & a_World, eWeather & a_NewWeather) override; virtual bool OnWorldStarted (cWorld & a_World) override; virtual bool OnWorldTick (cWorld & a_World, float a_Dt, int a_LastTickDurationMSec) override; - virtual bool HandleCommand(const AStringVector & a_Split, cPlayer * a_Player) override; + virtual bool HandleCommand(const AStringVector & a_Split, cPlayer & a_Player) override; virtual bool HandleConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output) override; diff --git a/src/Bindings/PluginManager.cpp b/src/Bindings/PluginManager.cpp index e0faa838a..f63578885 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -9,7 +9,7 @@ #include "../Server.h" #include "../CommandOutput.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../Entities/Player.h" #define FIND_HOOK(a_HookName) HookMap::iterator Plugins = m_Hooks.find(a_HookName); @@ -66,7 +66,7 @@ void cPluginManager::FindPlugins(void) // First get a clean list of only the currently running plugins, we don't want to mess those up for (PluginMap::iterator itr = m_Plugins.begin(); itr != m_Plugins.end();) { - if (itr->second == NULL) + if (itr->second == nullptr) { PluginMap::iterator thiz = itr; ++thiz; @@ -89,7 +89,7 @@ void cPluginManager::FindPlugins(void) // Add plugin name/directory to the list if (m_Plugins.find(*itr) == m_Plugins.end()) { - m_Plugins[*itr] = NULL; + m_Plugins[*itr] = nullptr; } } } @@ -151,7 +151,7 @@ void cPluginManager::ReloadPluginsNow(cIniFile & a_SettingsIni) // Remove invalid plugins from the PluginMap. for (PluginMap::iterator itr = m_Plugins.begin(); itr != m_Plugins.end();) { - if (itr->second == NULL) + if (itr->second == nullptr) { PluginMap::iterator thiz = itr; ++thiz; @@ -225,7 +225,7 @@ void cPluginManager::Tick(float a_Dt) -bool cPluginManager::CallHookBlockSpread(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) +bool cPluginManager::CallHookBlockSpread(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) { FIND_HOOK(HOOK_BLOCK_SPREAD); VERIFY_HOOK; @@ -245,7 +245,7 @@ bool cPluginManager::CallHookBlockSpread(cWorld * a_World, int a_BlockX, int a_B bool cPluginManager::CallHookBlockToPickups( - cWorld * a_World, cEntity * a_Digger, + cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups ) @@ -267,7 +267,7 @@ bool cPluginManager::CallHookBlockToPickups( -bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) +bool cPluginManager::CallHookChat(cPlayer & a_Player, AString & a_Message) { // Check if the message contains a command, execute it: switch (HandleCommand(a_Player, a_Message, true)) @@ -288,14 +288,14 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) case crError: { // An error in the plugin has prevented the command from executing. Report the error to the player: - a_Player->SendMessageFailure(Printf("Something went wrong while executing command \"%s\"", a_Message.c_str())); + a_Player.SendMessageFailure(Printf("Something went wrong while executing command \"%s\"", a_Message.c_str())); return true; } case crNoPermission: { // The player is not allowed to execute this command - a_Player->SendMessageFailure(Printf("Forbidden command; insufficient privileges: \"%s\"", a_Message.c_str())); + a_Player.SendMessageFailure(Printf("Forbidden command; insufficient privileges: \"%s\"", a_Message.c_str())); return true; } @@ -311,8 +311,8 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) { AStringVector Split(StringSplit(a_Message, " ")); ASSERT(!Split.empty()); // This should not happen - we know there's at least one char in the message so the split needs to be at least one item long - a_Player->SendMessageInfo(Printf("Unknown command: \"%s\"", a_Message.c_str())); - LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player->GetName().c_str(), a_Message.c_str()); + a_Player.SendMessageInfo(Printf("Unknown command: \"%s\"", a_Message.c_str())); + LOGINFO("Player %s issued an unknown command: \"%s\"", a_Player.GetName().c_str(), a_Message.c_str()); return true; // Cancel sending } @@ -334,7 +334,7 @@ bool cPluginManager::CallHookChat(cPlayer * a_Player, AString & a_Message) -bool cPluginManager::CallHookChunkAvailable(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkAvailable(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_AVAILABLE); VERIFY_HOOK; @@ -353,7 +353,7 @@ bool cPluginManager::CallHookChunkAvailable(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkGenerated(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginManager::CallHookChunkGenerated(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { FIND_HOOK(HOOK_CHUNK_GENERATED); VERIFY_HOOK; @@ -372,7 +372,7 @@ bool cPluginManager::CallHookChunkGenerated(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkGenerating(cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) +bool cPluginManager::CallHookChunkGenerating(cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc) { FIND_HOOK(HOOK_CHUNK_GENERATING); VERIFY_HOOK; @@ -391,7 +391,7 @@ bool cPluginManager::CallHookChunkGenerating(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookChunkUnloaded(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkUnloaded(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_UNLOADED); VERIFY_HOOK; @@ -410,7 +410,7 @@ bool cPluginManager::CallHookChunkUnloaded(cWorld * a_World, int a_ChunkX, int a -bool cPluginManager::CallHookChunkUnloading(cWorld * a_World, int a_ChunkX, int a_ChunkZ) +bool cPluginManager::CallHookChunkUnloading(cWorld & a_World, int a_ChunkX, int a_ChunkZ) { FIND_HOOK(HOOK_CHUNK_UNLOADING); VERIFY_HOOK; @@ -429,14 +429,14 @@ bool cPluginManager::CallHookChunkUnloading(cWorld * a_World, int a_ChunkX, int -bool cPluginManager::CallHookCollectingPickup(cPlayer * a_Player, cPickup & a_Pickup) +bool cPluginManager::CallHookCollectingPickup(cPlayer & a_Player, cPickup & a_Pickup) { FIND_HOOK(HOOK_COLLECTING_PICKUP); VERIFY_HOOK; for (PluginList::iterator itr = Plugins->second.begin(); itr != Plugins->second.end(); ++itr) { - if ((*itr)->OnCollectingPickup(a_Player, &a_Pickup)) + if ((*itr)->OnCollectingPickup(a_Player, a_Pickup)) { return true; } @@ -448,7 +448,7 @@ bool cPluginManager::CallHookCollectingPickup(cPlayer * a_Player, cPickup & a_Pi -bool cPluginManager::CallHookCraftingNoRecipe(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookCraftingNoRecipe(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe) { FIND_HOOK(HOOK_CRAFTING_NO_RECIPE); VERIFY_HOOK; @@ -562,7 +562,7 @@ bool cPluginManager::CallHookExploding(cWorld & a_World, double & a_ExplosionSiz -bool cPluginManager::CallHookHandshake(cClientHandle * a_ClientHandle, const AString & a_Username) +bool cPluginManager::CallHookHandshake(cClientHandle & a_ClientHandle, const AString & a_Username) { FIND_HOOK(HOOK_HANDSHAKE); VERIFY_HOOK; @@ -638,7 +638,7 @@ bool cPluginManager::CallHookKilling(cEntity & a_Victim, cEntity * a_Killer, Tak -bool cPluginManager::CallHookLogin(cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username) +bool cPluginManager::CallHookLogin(cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username) { FIND_HOOK(HOOK_LOGIN); VERIFY_HOOK; @@ -1111,7 +1111,7 @@ bool cPluginManager::CallHookPluginsLoaded(void) -bool cPluginManager::CallHookPostCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookPostCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { FIND_HOOK(HOOK_POST_CRAFTING); VERIFY_HOOK; @@ -1130,7 +1130,7 @@ bool cPluginManager::CallHookPostCrafting(const cPlayer * a_Player, const cCraft -bool cPluginManager::CallHookPreCrafting(const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe) +bool cPluginManager::CallHookPreCrafting(cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe) { FIND_HOOK(HOOK_PRE_CRAFTING); VERIFY_HOOK; @@ -1299,7 +1299,7 @@ bool cPluginManager::CallHookTakeDamage(cEntity & a_Receiver, TakeDamageInfo & a -bool cPluginManager::CallHookUpdatingSign(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) +bool cPluginManager::CallHookUpdatingSign(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player) { FIND_HOOK(HOOK_UPDATING_SIGN); VERIFY_HOOK; @@ -1318,7 +1318,7 @@ bool cPluginManager::CallHookUpdatingSign(cWorld * a_World, int a_BlockX, int a_ -bool cPluginManager::CallHookUpdatedSign(cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) +bool cPluginManager::CallHookUpdatedSign(cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player) { FIND_HOOK(HOOK_UPDATED_SIGN); VERIFY_HOOK; @@ -1413,10 +1413,8 @@ bool cPluginManager::CallHookWorldTick(cWorld & a_World, float a_Dt, int a_LastT -cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer * a_Player, const AString & a_Command, bool a_ShouldCheckPermissions) +cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions) { - ASSERT(a_Player != NULL); - AStringVector Split(StringSplit(a_Command, " ")); if (Split.empty()) { @@ -1431,23 +1429,23 @@ cPluginManager::CommandResult cPluginManager::HandleCommand(cPlayer * a_Player, } // Ask plugins first if a command is okay to execute the command: - if (CallHookExecuteCommand(a_Player, Split)) + if (CallHookExecuteCommand(&a_Player, Split)) { - LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player->GetName().c_str(), Split[0].c_str()); + LOGINFO("Player %s tried executing command \"%s\" that was stopped by the HOOK_EXECUTE_COMMAND hook", a_Player.GetName().c_str(), Split[0].c_str()); return crBlocked; } if ( a_ShouldCheckPermissions && !cmd->second.m_Permission.empty() && - !a_Player->HasPermission(cmd->second.m_Permission) + !a_Player.HasPermission(cmd->second.m_Permission) ) { - LOGINFO("Player %s tried to execute forbidden command: \"%s\"", a_Player->GetName().c_str(), Split[0].c_str()); + LOGINFO("Player %s tried to execute forbidden command: \"%s\"", a_Player.GetName().c_str(), Split[0].c_str()); return crNoPermission; } - ASSERT(cmd->second.m_Plugin != NULL); + ASSERT(cmd->second.m_Plugin != nullptr); if (!cmd->second.m_Plugin->HandleCommand(Split, a_Player)) { @@ -1465,7 +1463,7 @@ cPlugin * cPluginManager::GetPlugin( const AString & a_Plugin) const { for (PluginMap::const_iterator itr = m_Plugins.begin(); itr != m_Plugins.end(); ++itr) { - if (itr->second == NULL) continue; + if (itr->second == nullptr) continue; if (itr->second->GetName().compare(a_Plugin) == 0) { return itr->second; @@ -1515,7 +1513,7 @@ bool cPluginManager::DisablePlugin(const AString & a_PluginName) if (itr->first.compare(a_PluginName) == 0) // _X 2013_02_01: wtf? Isn't this supposed to be what find() does? { m_DisablePluginList.push_back(itr->second); - itr->second = NULL; // Get rid of this thing right away + itr->second = nullptr; // Get rid of this thing right away return true; } return false; @@ -1560,12 +1558,12 @@ void cPluginManager::RemovePlugin(cPlugin * a_Plugin) RemovePluginCommands(a_Plugin); RemovePluginConsoleCommands(a_Plugin); RemoveHooks(a_Plugin); - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->OnDisable(); } delete a_Plugin; - a_Plugin = NULL; + a_Plugin = nullptr; } @@ -1574,7 +1572,7 @@ void cPluginManager::RemovePlugin(cPlugin * a_Plugin) void cPluginManager::RemovePluginCommands(cPlugin * a_Plugin) { - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->ClearCommands(); } @@ -1652,7 +1650,7 @@ AString cPluginManager::GetCommandPermission(const AString & a_Command) -cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer * a_Player, const AString & a_Command) +cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer & a_Player, const AString & a_Command) { return HandleCommand(a_Player, a_Command, true); } @@ -1661,7 +1659,7 @@ cPluginManager::CommandResult cPluginManager::ExecuteCommand(cPlayer * a_Player, -cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer * a_Player, const AString & a_Command) +cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer & a_Player, const AString & a_Command) { return HandleCommand(a_Player, a_Command, false); } @@ -1672,7 +1670,7 @@ cPluginManager::CommandResult cPluginManager::ForceExecuteCommand(cPlayer * a_Pl void cPluginManager::RemovePluginConsoleCommands(cPlugin * a_Plugin) { - if (a_Plugin != NULL) + if (a_Plugin != nullptr) { a_Plugin->ClearConsoleCommands(); } @@ -1701,7 +1699,7 @@ bool cPluginManager::BindConsoleCommand(const AString & a_Command, cPlugin * a_P CommandMap::iterator cmd = m_ConsoleCommands.find(a_Command); if (cmd != m_ConsoleCommands.end()) { - if (cmd->second.m_Plugin == NULL) + if (cmd->second.m_Plugin == nullptr) { LOGWARNING("Console command \"%s\" is already bound internally by MCServer, cannot bind in plugin \"%s\".", a_Command.c_str(), a_Plugin->GetName().c_str()); } @@ -1761,14 +1759,14 @@ bool cPluginManager::ExecuteConsoleCommand(const AStringVector & a_Split, cComma return false; } - if (cmd->second.m_Plugin == NULL) + if (cmd->second.m_Plugin == nullptr) { // This is a built-in command return false; } // Ask plugins first if a command is okay to execute the console command: - if (CallHookExecuteCommand(NULL, a_Split)) + if (CallHookExecuteCommand(nullptr, a_Split)) { a_Output.Out("Command \"%s\" was stopped by the HOOK_EXECUTE_COMMAND hook", a_Split[0].c_str()); return false; @@ -1790,7 +1788,7 @@ void cPluginManager::TabCompleteCommand(const AString & a_Text, AStringVector & // Command name doesn't match continue; } - if ((a_Player != NULL) && !a_Player->HasPermission(itr->second.m_Permission)) + if ((a_Player != nullptr) && !a_Player->HasPermission(itr->second.m_Permission)) { // Player doesn't have permission for the command continue; @@ -1816,7 +1814,7 @@ bool cPluginManager::DoWithPlugin(const AString & a_PluginName, cPluginCallback { // TODO: Implement locking for plugins PluginMap::iterator itr = m_Plugins.find(a_PluginName); - if ((itr == m_Plugins.end()) || (itr->second == NULL)) + if ((itr == m_Plugins.end()) || (itr->second == nullptr)) { return false; } @@ -1830,6 +1828,7 @@ bool cPluginManager::DoWithPlugin(const AString & a_PluginName, cPluginCallback bool cPluginManager::AddPlugin(cPlugin * a_Plugin) { m_Plugins[a_Plugin->GetDirectory()] = a_Plugin; + if (a_Plugin->Initialize()) { // Initialization OK @@ -1849,7 +1848,7 @@ void cPluginManager::AddHook(cPlugin * a_Plugin, int a_Hook) { if (!a_Plugin) { - LOGWARN("Called cPluginManager::AddHook() with a_Plugin == NULL"); + LOGWARN("Called cPluginManager::AddHook() with a_Plugin == nullptr"); return; } PluginList & Plugins = m_Hooks[a_Hook]; diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h index fff3bc323..bc8c1f5e6 100644 --- a/src/Bindings/PluginManager.h +++ b/src/Bindings/PluginManager.h @@ -178,26 +178,26 @@ public: size_t GetNumPlugins() const; // tolua_export // Calls for individual hooks. Each returns false if the action is to continue or true if the plugin wants to abort - bool CallHookBlockSpread (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source); - bool CallHookBlockToPickups (cWorld * a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups); - bool CallHookChat (cPlayer * a_Player, AString & a_Message); - bool CallHookChunkAvailable (cWorld * a_World, int a_ChunkX, int a_ChunkZ); - bool CallHookChunkGenerated (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); - bool CallHookChunkGenerating (cWorld * a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); - bool CallHookChunkUnloaded (cWorld * a_World, int a_ChunkX, int a_ChunkZ); - bool CallHookChunkUnloading (cWorld * a_World, int a_ChunkX, int a_ChunkZ); - bool CallHookCollectingPickup (cPlayer * a_Player, cPickup & a_Pickup); - bool CallHookCraftingNoRecipe (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe); + bool CallHookBlockSpread (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source); + bool CallHookBlockToPickups (cWorld & a_World, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups); + bool CallHookChat (cPlayer & a_Player, AString & a_Message); + bool CallHookChunkAvailable (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookChunkGenerated (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); + bool CallHookChunkGenerating (cWorld & a_World, int a_ChunkX, int a_ChunkZ, cChunkDesc * a_ChunkDesc); + bool CallHookChunkUnloaded (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookChunkUnloading (cWorld & a_World, int a_ChunkX, int a_ChunkZ); + bool CallHookCollectingPickup (cPlayer & a_Player, cPickup & a_Pickup); + bool CallHookCraftingNoRecipe (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe * a_Recipe); bool CallHookDisconnect (cClientHandle & a_Client, const AString & a_Reason); bool CallHookEntityAddEffect (cEntity & a_Entity, int a_EffectType, int a_EffectDurationTicks, int a_EffectIntensity, double a_DistanceModifier); - bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == NULL, it is a console cmd + bool CallHookExecuteCommand (cPlayer * a_Player, const AStringVector & a_Split); // If a_Player == nullptr, it is a console cmd bool CallHookExploded (cWorld & a_World, double a_ExplosionSize, bool a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData); bool CallHookExploding (cWorld & a_World, double & a_ExplosionSize, bool & a_CanCauseFire, double a_X, double a_Y, double a_Z, eExplosionSource a_Source, void * a_SourceData); - bool CallHookHandshake (cClientHandle * a_ClientHandle, const AString & a_Username); + bool CallHookHandshake (cClientHandle & a_ClientHandle, const AString & a_Username); bool CallHookHopperPullingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_DstSlotNum, cBlockEntityWithItems & a_SrcEntity, int a_SrcSlotNum); bool CallHookHopperPushingItem (cWorld & a_World, cHopperEntity & a_Hopper, int a_SrcSlotNum, cBlockEntityWithItems & a_DstEntity, int a_DstSlotNum); bool CallHookKilling (cEntity & a_Victim, cEntity * a_Killer, TakeDamageInfo & a_TDI); - bool CallHookLogin (cClientHandle * a_Client, int a_ProtocolVersion, const AString & a_Username); + bool CallHookLogin (cClientHandle & a_Client, int a_ProtocolVersion, const AString & a_Username); bool CallHookPlayerAnimation (cPlayer & a_Player, int a_Animation); bool CallHookPlayerBreakingBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); bool CallHookPlayerBrokenBlock (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); @@ -222,8 +222,8 @@ public: bool CallHookPlayerUsingItem (cPlayer & a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, char a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ); bool CallHookPluginMessage (cClientHandle & a_Client, const AString & a_Channel, const AString & a_Message); bool CallHookPluginsLoaded (void); - bool CallHookPostCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe); - bool CallHookPreCrafting (const cPlayer * a_Player, const cCraftingGrid * a_Grid, cCraftingRecipe * a_Recipe); + bool CallHookPostCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe); + bool CallHookPreCrafting (cPlayer & a_Player, cCraftingGrid & a_Grid, cCraftingRecipe & a_Recipe); bool CallHookProjectileHitBlock (cProjectileEntity & a_Projectile, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Face, const Vector3d & a_BlockHitPos); bool CallHookProjectileHitEntity (cProjectileEntity & a_Projectile, cEntity & a_HitEntity); bool CallHookServerPing (cClientHandle & a_ClientHandle, AString & a_ServerDescription, int & a_OnlinePlayersCount, int & a_MaxPlayersCount, AString & a_Favicon); @@ -232,8 +232,8 @@ public: bool CallHookSpawningEntity (cWorld & a_World, cEntity & a_Entity); bool CallHookSpawningMonster (cWorld & a_World, cMonster & a_Monster); bool CallHookTakeDamage (cEntity & a_Receiver, TakeDamageInfo & a_TDI); - bool CallHookUpdatedSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player); - bool CallHookUpdatingSign (cWorld * a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player); + bool CallHookUpdatedSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player); + bool CallHookUpdatingSign (cWorld & a_World, int a_BlockX, int a_BlockY, int a_BlockZ, AString & a_Line1, AString & a_Line2, AString & a_Line3, AString & a_Line4, cPlayer * a_Player); bool CallHookWeatherChanged (cWorld & a_World); bool CallHookWeatherChanging (cWorld & a_World, eWeather & a_NewWeather); bool CallHookWorldStarted (cWorld & a_World); @@ -264,10 +264,10 @@ public: AString GetCommandPermission(const AString & a_Command); // tolua_export /** Executes the command, as if it was requested by a_Player. Checks permissions first. Returns crExecuted if executed. */ - CommandResult ExecuteCommand(cPlayer * a_Player, const AString & a_Command); // tolua_export + CommandResult ExecuteCommand(cPlayer & a_Player, const AString & a_Command); // tolua_export /** Executes the command, as if it was requested by a_Player. Permisssions are not checked. Returns crExecuted if executed. */ - CommandResult ForceExecuteCommand(cPlayer * a_Player, const AString & a_Command); // tolua_export + CommandResult ForceExecuteCommand(cPlayer & a_Player, const AString & a_Command); // tolua_export /** Removes all console command bindings that the specified plugin has made */ void RemovePluginConsoleCommands(cPlugin * a_Plugin); @@ -285,7 +285,7 @@ public: bool ExecuteConsoleCommand(const AStringVector & a_Split, cCommandOutputCallback & a_Output); /** Appends all commands beginning with a_Text (case-insensitive) into a_Results. - If a_Player is not NULL, only commands for which the player has permissions are added. + If a_Player is not nullptr, only commands for which the player has permissions are added. */ void TabCompleteCommand(const AString & a_Text, AStringVector & a_Results, cPlayer * a_Player); @@ -341,7 +341,7 @@ private: bool AddPlugin(cPlugin * a_Plugin); /** Tries to match a_Command to the internal table of commands, if a match is found, the corresponding plugin is called. Returns crExecuted if the command is executed. */ - cPluginManager::CommandResult HandleCommand(cPlayer * a_Player, const AString & a_Command, bool a_ShouldCheckPermissions); + CommandResult HandleCommand(cPlayer & a_Player, const AString & a_Command, bool a_ShouldCheckPermissions); } ; // tolua_export diff --git a/src/Bindings/WebPlugin.cpp b/src/Bindings/WebPlugin.cpp index eca1c74e6..5759b20e7 100644 --- a/src/Bindings/WebPlugin.cpp +++ b/src/Bindings/WebPlugin.cpp @@ -12,7 +12,7 @@ cWebPlugin::cWebPlugin() { cWebAdmin * WebAdmin = cRoot::Get()->GetWebAdmin(); - if (WebAdmin != NULL) + if (WebAdmin != nullptr) { WebAdmin->AddPlugin(this); } @@ -25,7 +25,7 @@ cWebPlugin::cWebPlugin() cWebPlugin::~cWebPlugin() { cWebAdmin * WebAdmin = cRoot::Get()->GetWebAdmin(); - if (WebAdmin != NULL) + if (WebAdmin != nullptr) { WebAdmin->RemovePlugin(this); } @@ -65,7 +65,7 @@ std::pair< AString, AString > cWebPlugin::GetTabNameForRequest(const HTTPRequest if (Split.size() > 1) { - sWebPluginTab * Tab = NULL; + sWebPluginTab * Tab = nullptr; if (Split.size() > 2) // If we got the tab name, show that page { for (TabList::iterator itr = GetTabs().begin(); itr != GetTabs().end(); ++itr) @@ -85,7 +85,7 @@ std::pair< AString, AString > cWebPlugin::GetTabNameForRequest(const HTTPRequest } } - if (Tab != NULL) + if (Tab != nullptr) { Names.first = Tab->Title; Names.second = Tab->SafeTitle; diff --git a/src/Bindings/gen_LuaState_Call.lua b/src/Bindings/gen_LuaState_Call.lua deleted file mode 100644 index 7f62573c7..000000000 --- a/src/Bindings/gen_LuaState_Call.lua +++ /dev/null @@ -1,224 +0,0 @@ - --- gen_LuaState_Call.lua - --- Generates the cLuaState::Call() function templates that are included from LuaState.h - ---[[ -The cLuaState::Call() family of functions provides a template-based system for calling any Lua function -either by name or by reference with almost any number of parameters and return values. This is done by -providing a number of overloads of the same name with variable number of template-type parameters. To -separate the arguments from the return values, a special type of cLuaState::cRet is used. ---]] - - - - -print("Generating LuaState_Call.inc . . .") - - - - --- List of combinations (# params, # returns) to generate: -local Combinations = -{ - -- no return values: - {0, 0}, - {1, 0}, - {2, 0}, - {3, 0}, - {4, 0}, - - -- 1 return value: - {0, 1}, - {1, 1}, - {2, 1}, - {3, 1}, - {4, 1}, - {5, 1}, - {6, 1}, - {7, 1}, - {8, 1}, - {9, 1}, - {10, 1}, - - -- 2 return values: - {0, 2}, - {1, 2}, - {2, 2}, - {3, 2}, - {4, 2}, - {5, 2}, - {6, 2}, - {7, 2}, - {8, 2}, - {9, 2}, - - -- Special combinations: - {5, 5}, - {7, 3}, - {8, 3}, - {9, 5}, -} - - - - ---- Writes a single overloaded function definition for the specified number of params and returns into f ---[[ -The format for the generated function is this: -/** Call the specified 3-param 2-return Lua function: -Returns true if call succeeded, false if there was an error. */ -template <typename FnT, typename ParamT1, typename ParamT2, typename ParamT3, typename RetT1, typename RetT2> -bool Call(FnT a_Function, ParamT1 a_Param1, ParamT2 a_Param2, ParamT3 a_Param3, const cLuaState::cRet & a_RetMark, RetT1 & a_Ret1, RetT2 & a_Ret2) -{ - UNUSED(a_RetMark); - if (!PushFunction(a_Function)) - { - return false; - } - Push(a_Param1); - Push(a_Param2); - Push(a_Param3); - if (!CallFunction(2)) - { - return false; - } - GetStackValue(-2, a_Ret1); - GetStackValue(-1, a_Ret2); - lua_pop(m_LuaState, 2); - return true; -} -Note especially the negative numbers in GetStackValue() calls. ---]] -local function WriteOverload(f, a_NumParams, a_NumReturns) - -- Write the function doxy-comments: - f:write("/** Call the specified ", a_NumParams, "-param ", a_NumReturns, "-return Lua function:\n") - f:write("Returns true if call succeeded, false if there was an error. */\n") - - -- Write the template <...> line: - f:write("template <typename FnT") - for i = 1, a_NumParams do - f:write(", typename ParamT", i) - end - if (a_NumReturns > 0) then - for i = 1, a_NumReturns do - f:write(", typename RetT", i) - end - end - f:write(">\n") - - -- Write the function signature: - f:write("bool Call(") - f:write("const FnT & a_Function") - for i = 1, a_NumParams do - f:write(", ParamT", i, " a_Param", i) - end - if (a_NumReturns > 0) then - f:write(", const cLuaState::cRet & a_RetMark") - for i = 1, a_NumReturns do - f:write(", RetT", i, " & a_Ret", i) - end - end - f:write(")\n") - - -- Common code: - f:write("{\n") - if (a_NumReturns > 0) then - f:write("\tUNUSED(a_RetMark);\n") - end - f:write("\tif (!PushFunction(a_Function))\n") - f:write("\t{\n") - f:write("\t\treturn false;\n") - f:write("\t}\n") - - -- Push the params: - for i = 1, a_NumParams do - f:write("\tPush(a_Param", i, ");\n") - end - - -- Call the function: - f:write("\tif (!CallFunction(", a_NumReturns, "))\n") - f:write("\t{\n") - f:write("\t\treturn false;\n") - f:write("\t}\n") - - -- Get the return values: - for i = 1, a_NumReturns do - f:write("\tGetStackValue(", -1 - a_NumReturns + i, ", a_Ret", i, ");\n") - end - - -- Pop the returns off the stack, if needed: - if (a_NumReturns > 0) then - f:write("\tlua_pop(m_LuaState, ", a_NumReturns, ");\n") - end - - -- Everything ok: - f:write("\treturn true;\n") - f:write("}\n") - - -- Separate from the next function: - f:write("\n\n\n\n\n") -end - - - - - -local f = assert(io.open("LuaState_Call.inc", "w")) - --- Write file header: -f:write([[ -// LuaState_Call.inc - -// This file is auto-generated by gen_LuaState_Call.lua -// Make changes to the generator instead of to this file! - -// This file contains the various overloads for the cLuaState::Call() function -// Each overload handles a different number of parameters / return values -]]) -f:write("\n\n\n\n\n") - --- Write out a template function for each overload: -for _, combination in ipairs(Combinations) do - WriteOverload(f, combination[1], combination[2]) -end - --- Generate the cLuaState::GetStackValues() multi-param templates: -for i = 2, 6 do - f:write("/** Reads ", i, " consecutive values off the stack */\ntemplate <\n") - - -- Write the template function header: - local txt = {} - for idx = 1, i do - table.insert(txt, "\ttypename ArgT" .. idx) - end - f:write(table.concat(txt, ",\n")) - - -- Write the argument declarations: - txt = {} - f:write("\n>\nvoid GetStackValues(\n\tint a_BeginPos,\n") - for idx = 1, i do - table.insert(txt, "\tArgT" .. idx .. " & Arg" .. idx) - end - f:write(table.concat(txt, ",\n")) - - -- Write the function body: - f:write("\n)\n{\n") - for idx = 1, i do - f:write("\tGetStackValue(a_BeginPos + ", idx - 1, ", Arg", idx, ");\n") - end - f:write("}\n\n\n\n\n\n") -end - --- Close the generated file -f:close() - - - - - -print("LuaState_Call.inc generated.") - - - - diff --git a/src/Bindings/virtual_method_hooks.lua b/src/Bindings/virtual_method_hooks.lua index 8ad30bf78..a52728ff8 100644 --- a/src/Bindings/virtual_method_hooks.lua +++ b/src/Bindings/virtual_method_hooks.lua @@ -7,16 +7,6 @@ local default_private_access = false --- Code generators used by the build --- Note that these are not exactly needed for the bindings, but rather we --- misuse tolua's Lua engine to process files for us -dofile("gen_LuaState_Call.lua") - - - - - - local access = {public = 0, protected = 1, private = 2} function preparse_hook(p) diff --git a/src/BiomeDef.cpp b/src/BiomeDef.cpp index 02f8c2232..188e06173 100644 --- a/src/BiomeDef.cpp +++ b/src/BiomeDef.cpp @@ -160,3 +160,65 @@ bool IsBiomeNoDownfall(EMCSBiome a_Biome) } } } + + + + + +bool IsBiomeVeryCold(EMCSBiome a_Biome) +{ + switch (a_Biome) + { + case biFrozenOcean: + case biFrozenRiver: + case biIcePlains: + case biIceMountains: + case biColdBeach: + case biColdTaiga: + case biColdTaigaHills: + case biIcePlainsSpikes: + case biColdTaigaM: + { + return true; + } + default: + { + return false; + } + } +} + + + + +bool IsBiomeCold(EMCSBiome a_Biome) +{ + switch (a_Biome) + { + case biExtremeHills: + case biTaiga: + case biTaigaHills: + case biExtremeHillsEdge: + case biStoneBeach: + case biMegaTaiga: + case biMegaTaigaHills: + case biExtremeHillsPlus: + case biExtremeHillsM: + case biTaigaM: + case biColdTaigaM: + case biMegaSpruceTaiga: + case biMegaSpruceTaigaHills: + case biExtremeHillsPlusM: + { + return true; + } + default: + { + return false; + } + } +} + + + + diff --git a/src/BiomeDef.h b/src/BiomeDef.h index f929596e9..84751cfd7 100644 --- a/src/BiomeDef.h +++ b/src/BiomeDef.h @@ -113,5 +113,20 @@ extern AString BiomeToString(int a_Biome); /** Returns true if the biome has no downfall - deserts and savannas */ extern bool IsBiomeNoDownfall(EMCSBiome a_Biome); +/** Returns true if the biome is an ocean biome. */ +inline bool IsBiomeOcean(int a_Biome) +{ + return ((a_Biome == biOcean) || (a_Biome == biDeepOcean)); +} + +/** Returns true if the biome is very cold +(has snow on ground everywhere, turns top water to ice, has snowfall instead of rain everywhere). +Doesn't report mildly cold biomes (where it snows above certain elevation), use IsBiomeCold() for those. */ +extern bool IsBiomeVeryCold(EMCSBiome a_Biome); + +/** Returns true if the biome is cold +(has snow and snowfall at higher elevations but not at regular heights). +Doesn't report Very Cold biomes, use IsBiomeVeryCold() for those. */ +extern bool IsBiomeCold(EMCSBiome a_Biome); // tolua_end diff --git a/src/BlockArea.cpp b/src/BlockArea.cpp index ba55528b8..4c3da0535 100644 --- a/src/BlockArea.cpp +++ b/src/BlockArea.cpp @@ -273,10 +273,10 @@ void MergeCombinatorMask(BLOCKTYPE & a_DstType, BLOCKTYPE a_SrcType, NIBBLETYPE // cBlockArea: cBlockArea::cBlockArea(void) : - m_BlockTypes(NULL), - m_BlockMetas(NULL), - m_BlockLight(NULL), - m_BlockSkyLight(NULL) + m_BlockTypes(nullptr), + m_BlockMetas(nullptr), + m_BlockLight(nullptr), + m_BlockSkyLight(nullptr) { } @@ -295,10 +295,10 @@ cBlockArea::~cBlockArea() void cBlockArea::Clear(void) { - delete[] m_BlockTypes; m_BlockTypes = NULL; - delete[] m_BlockMetas; m_BlockMetas = NULL; - delete[] m_BlockLight; m_BlockLight = NULL; - delete[] m_BlockSkyLight; m_BlockSkyLight = NULL; + delete[] m_BlockTypes; m_BlockTypes = nullptr; + delete[] m_BlockMetas; m_BlockMetas = nullptr; + delete[] m_BlockLight; m_BlockLight = nullptr; + delete[] m_BlockSkyLight; m_BlockSkyLight = nullptr; m_Origin.Set(0, 0, 0); m_Size.Set(0, 0, 0); } @@ -711,7 +711,7 @@ void cBlockArea::Merge(const cBlockArea & a_Src, int a_RelX, int a_RelY, int a_R const NIBBLETYPE * SrcMetas = a_Src.GetBlockMetas(); NIBBLETYPE * DstMetas = m_BlockMetas; - bool IsDummyMetas = ((SrcMetas == NULL) || (DstMetas == NULL)); + bool IsDummyMetas = ((SrcMetas == nullptr) || (DstMetas == nullptr)); if (IsDummyMetas) { @@ -1013,8 +1013,8 @@ void cBlockArea::RotateCCW(void) } // for x std::swap(m_BlockTypes, NewTypes); std::swap(m_BlockMetas, NewMetas); - delete[] NewTypes; NewTypes = NULL; - delete[] NewMetas; NewMetas = NULL; + delete[] NewTypes; NewTypes = nullptr; + delete[] NewMetas; NewMetas = nullptr; std::swap(m_Size.x, m_Size.z); } @@ -1058,8 +1058,8 @@ void cBlockArea::RotateCW(void) } // for x std::swap(m_BlockTypes, NewTypes); std::swap(m_BlockMetas, NewMetas); - delete[] NewTypes; NewTypes = NULL; - delete[] NewMetas; NewMetas = NULL; + delete[] NewTypes; NewTypes = nullptr; + delete[] NewMetas; NewMetas = nullptr; std::swap(m_Size.x, m_Size.z); } @@ -1206,7 +1206,7 @@ void cBlockArea::RotateCCWNoMeta(void) } // for z } // for x std::swap(m_BlockTypes, NewTypes); - delete[] NewTypes; NewTypes = NULL; + delete[] NewTypes; NewTypes = nullptr; } if (HasBlockMetas()) { @@ -1224,7 +1224,7 @@ void cBlockArea::RotateCCWNoMeta(void) } // for z } // for x std::swap(m_BlockMetas, NewMetas); - delete[] NewMetas; NewMetas = NULL; + delete[] NewMetas; NewMetas = nullptr; } std::swap(m_Size.x, m_Size.z); } @@ -1251,7 +1251,7 @@ void cBlockArea::RotateCWNoMeta(void) } // for x } // for z std::swap(m_BlockTypes, NewTypes); - delete[] NewTypes; NewTypes = NULL; + delete[] NewTypes; NewTypes = nullptr; } if (HasBlockMetas()) { @@ -1269,7 +1269,7 @@ void cBlockArea::RotateCWNoMeta(void) } // for x } // for z std::swap(m_BlockMetas, NewMetas); - delete[] NewMetas; NewMetas = NULL; + delete[] NewMetas; NewMetas = nullptr; } std::swap(m_Size.x, m_Size.z); } @@ -1391,7 +1391,7 @@ void cBlockArea::MirrorYZNoMeta(void) void cBlockArea::SetRelBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType) { - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); return; @@ -1468,7 +1468,7 @@ void cBlockArea::SetBlockSkyLight(int a_BlockX, int a_BlockY, int a_BlockZ, NIBB BLOCKTYPE cBlockArea::GetRelBlockType(int a_RelX, int a_RelY, int a_RelZ) const { - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); return E_BLOCK_AIR; @@ -1555,7 +1555,7 @@ void cBlockArea::SetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOC void cBlockArea::SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { int idx = MakeIndex(a_RelX, a_RelY, a_RelZ); - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("%s: BlockTypes not available but requested to be written to.", __FUNCTION__); } @@ -1563,7 +1563,7 @@ void cBlockArea::SetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, B { m_BlockTypes[idx] = a_BlockType; } - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { LOGWARNING("%s: BlockMetas not available but requested to be written to.", __FUNCTION__); } @@ -1589,7 +1589,7 @@ void cBlockArea::GetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOC void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { int idx = MakeIndex(a_RelX, a_RelY, a_RelZ); - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { LOGWARNING("cBlockArea: BlockTypes have not been read!"); a_BlockType = E_BLOCK_AIR; @@ -1599,7 +1599,7 @@ void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTY a_BlockType = m_BlockTypes[idx]; } - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { LOGWARNING("cBlockArea: BlockMetas have not been read!"); a_BlockMeta = 0; @@ -1617,19 +1617,19 @@ void cBlockArea::GetRelBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTY int cBlockArea::GetDataTypes(void) const { int res = 0; - if (m_BlockTypes != NULL) + if (m_BlockTypes != nullptr) { res |= baTypes; } - if (m_BlockMetas != NULL) + if (m_BlockMetas != nullptr) { res |= baMetas; } - if (m_BlockLight != NULL) + if (m_BlockLight != nullptr) { res |= baLight; } - if (m_BlockSkyLight != NULL) + if (m_BlockSkyLight != nullptr) { res |= baSkyLight; } @@ -1642,12 +1642,12 @@ int cBlockArea::GetDataTypes(void) const bool cBlockArea::SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes) { - ASSERT(m_BlockTypes == NULL); // Has been cleared + ASSERT(m_BlockTypes == nullptr); // Has been cleared if (a_DataTypes & baTypes) { m_BlockTypes = new BLOCKTYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockTypes == NULL) + if (m_BlockTypes == nullptr) { return false; } @@ -1655,36 +1655,36 @@ bool cBlockArea::SetSize(int a_SizeX, int a_SizeY, int a_SizeZ, int a_DataTypes) if (a_DataTypes & baMetas) { m_BlockMetas = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockMetas == NULL) + if (m_BlockMetas == nullptr) { delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } if (a_DataTypes & baLight) { m_BlockLight = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockLight == NULL) + if (m_BlockLight == nullptr) { delete[] m_BlockMetas; - m_BlockMetas = NULL; + m_BlockMetas = nullptr; delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } if (a_DataTypes & baSkyLight) { m_BlockSkyLight = new NIBBLETYPE[a_SizeX * a_SizeY * a_SizeZ]; - if (m_BlockSkyLight == NULL) + if (m_BlockSkyLight == nullptr) { delete[] m_BlockLight; - m_BlockLight = NULL; + m_BlockLight = nullptr; delete[] m_BlockMetas; - m_BlockMetas = NULL; + m_BlockMetas = nullptr; delete[] m_BlockTypes; - m_BlockTypes = NULL; + m_BlockTypes = nullptr; return false; } } @@ -1714,7 +1714,7 @@ int cBlockArea::MakeIndex(int a_RelX, int a_RelY, int a_RelZ) const void cBlockArea::SetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Value, NIBBLETYPE * a_Array) { - if (a_Array == NULL) + if (a_Array == nullptr) { LOGWARNING("cBlockArea: datatype has not been read!"); return; @@ -1737,7 +1737,7 @@ void cBlockArea::SetNibble(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE NIBBLETYPE cBlockArea::GetRelNibble(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE * a_Array) const { - if (a_Array == NULL) + if (a_Array == nullptr) { LOGWARNING("cBlockArea: datatype has not been read!"); return 16; @@ -1896,7 +1896,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the blocktypes: - if (m_Area.m_BlockTypes != NULL) + if (m_Area.m_BlockTypes != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1917,7 +1917,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the block metas: - if (m_Area.m_BlockMetas != NULL) + if (m_Area.m_BlockMetas != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1938,7 +1938,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the blocklight: - if (m_Area.m_BlockLight != NULL) + if (m_Area.m_BlockLight != nullptr) { for (int y = 0; y < SizeY; y++) { @@ -1959,7 +1959,7 @@ void cBlockArea::cChunkReader::ChunkData(const cChunkData & a_BlockBuffer) } // Copy the skylight: - if (m_Area.m_BlockSkyLight != NULL) + if (m_Area.m_BlockSkyLight != nullptr) { for (int y = 0; y < SizeY; y++) { diff --git a/src/BlockArea.h b/src/BlockArea.h index 86f7c4f2d..348e960dd 100644 --- a/src/BlockArea.h +++ b/src/BlockArea.h @@ -282,10 +282,10 @@ public: /** Returns the datatypes that are stored in the object (bitmask of baXXX values) */ int GetDataTypes(void) const; - bool HasBlockTypes (void) const { return (m_BlockTypes != NULL); } - bool HasBlockMetas (void) const { return (m_BlockMetas != NULL); } - bool HasBlockLights (void) const { return (m_BlockLight != NULL); } - bool HasBlockSkyLights(void) const { return (m_BlockSkyLight != NULL); } + bool HasBlockTypes (void) const { return (m_BlockTypes != nullptr); } + bool HasBlockMetas (void) const { return (m_BlockMetas != nullptr); } + bool HasBlockLights (void) const { return (m_BlockLight != nullptr); } + bool HasBlockSkyLights(void) const { return (m_BlockSkyLight != nullptr); } // tolua_end diff --git a/src/BlockEntities/BeaconEntity.cpp b/src/BlockEntities/BeaconEntity.cpp index 02f45a097..85819446c 100644 --- a/src/BlockEntities/BeaconEntity.cpp +++ b/src/BlockEntities/BeaconEntity.cpp @@ -97,7 +97,7 @@ bool cBeaconEntity::SetPrimaryEffect(cEntityEffect::eType a_Effect) m_PrimaryEffect = a_Effect; // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(1, m_PrimaryEffect); } @@ -119,7 +119,7 @@ bool cBeaconEntity::SetSecondaryEffect(cEntityEffect::eType a_Effect) m_SecondaryEffect = a_Effect; // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(2, m_SecondaryEffect); } @@ -184,7 +184,7 @@ void cBeaconEntity::UpdateBeacon(void) if (m_BeaconLevel != OldBeaconLevel) { // Send window update: - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->SetProperty(0, m_BeaconLevel); } @@ -283,13 +283,13 @@ bool cBeaconEntity::Tick(float a_Dt, cChunk & a_Chunk) void cBeaconEntity::UsedBy(cPlayer * a_Player) { cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenWindow(new cBeaconWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - if (Window != NULL) + if (Window != nullptr) { // if (a_Player->GetWindow() != Window) // -> Because mojang doesn't send a 'close window' packet when you click the cancel button in the beacon inventory ... diff --git a/src/BlockEntities/BeaconEntity.h b/src/BlockEntities/BeaconEntity.h index 8c2dad254..d1db3a68f 100644 --- a/src/BlockEntities/BeaconEntity.h +++ b/src/BlockEntities/BeaconEntity.h @@ -32,6 +32,8 @@ class cBeaconEntity : public: // tolua_end + BLOCKENTITY_PROTODEF(cBeaconEntity); + cBeaconEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); // cBlockEntity overrides: diff --git a/src/BlockEntities/BlockEntity.cpp b/src/BlockEntities/BlockEntity.cpp index 05ad03a3d..3d96e891e 100644 --- a/src/BlockEntities/BlockEntity.cpp +++ b/src/BlockEntities/BlockEntity.cpp @@ -48,7 +48,7 @@ cBlockEntity * cBlockEntity::CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE __FUNCTION__, a_BlockType, ItemTypeToString(a_BlockType).c_str() ); ASSERT(!"Requesting creation of an unknown block entity"); - return NULL; + return nullptr; } diff --git a/src/BlockEntities/BlockEntity.h b/src/BlockEntities/BlockEntity.h index 54ab40f3e..ffd6ee856 100644 --- a/src/BlockEntities/BlockEntity.h +++ b/src/BlockEntities/BlockEntity.h @@ -5,6 +5,28 @@ +/** Place this macro in the declaration of each cBlockEntity descendant. */ +#define BLOCKENTITY_PROTODEF(classname) \ + virtual bool IsA(const char * a_ClassName) const override \ + { \ + return ((strcmp(a_ClassName, #classname) == 0) || super::IsA(a_ClassName)); \ + } \ + virtual const char * GetClass(void) const override \ + { \ + return #classname; \ + } \ + static const char * GetClassStatic(void) \ + { \ + return #classname; \ + } \ + virtual const char * GetParentClass(void) const override \ + { \ + return super::GetClass(); \ + } + + + + namespace Json { @@ -48,13 +70,22 @@ public: /// Creates a new block entity for the specified block type /// If a_World is valid, then the entity is created bound to that world - /// Returns NULL for unknown block types - static cBlockEntity * CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World = NULL); + /// Returns nullptr for unknown block types + static cBlockEntity * CreateByBlockType(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World = nullptr); static const char * GetClassStatic(void) // Needed for ManualBindings's ForEach templates { return "cBlockEntity"; } + + /** Returns true if the object is the specified class, or its descendant. */ + virtual bool IsA(const char * a_ClassName) const { return (strcmp(a_ClassName, "cBlockEntity") == 0); } + + /** Returns the name of the tompost class (the most descendant). Used for Lua bindings to push the correct object type. */ + virtual const char * GetClass(void) const { return GetClassStatic(); } + + /** Returns the name of the parent class, or empty string if no parent class. */ + virtual const char * GetParentClass(void) const { return ""; } // tolua_begin diff --git a/src/BlockEntities/BlockEntityWithItems.h b/src/BlockEntities/BlockEntityWithItems.h index 00173cbcb..8c7d4749b 100644 --- a/src/BlockEntities/BlockEntityWithItems.h +++ b/src/BlockEntities/BlockEntityWithItems.h @@ -25,10 +25,12 @@ class cBlockEntityWithItems : public cBlockEntityWindowOwner { typedef cBlockEntity super; - + public: // tolua_end + BLOCKENTITY_PROTODEF(cBlockEntityWithItems); + cBlockEntityWithItems( BLOCKTYPE a_BlockType, // Type of the block that the entity represents int a_BlockX, int a_BlockY, int a_BlockZ, // Position of the block entity @@ -45,7 +47,7 @@ public: virtual void Destroy(void) override { // Drop the contents as pickups: - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); cItems Pickups; m_Contents.CopyToItems(Pickups); m_Contents.Clear(); @@ -76,9 +78,9 @@ protected: { UNUSED(a_SlotNum); ASSERT(a_Grid == &m_Contents); - if (m_World != NULL) + if (m_World != nullptr) { - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->BroadcastWholeWindow(); } diff --git a/src/BlockEntities/ChestEntity.cpp b/src/BlockEntities/ChestEntity.cpp index 19d88b646..0cd9c66e0 100644 --- a/src/BlockEntities/ChestEntity.cpp +++ b/src/BlockEntities/ChestEntity.cpp @@ -23,7 +23,7 @@ cChestEntity::cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_ cChestEntity::~cChestEntity() { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -49,14 +49,14 @@ void cChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { diff --git a/src/BlockEntities/ChestEntity.h b/src/BlockEntities/ChestEntity.h index af5d851a8..09fffb923 100644 --- a/src/BlockEntities/ChestEntity.h +++ b/src/BlockEntities/ChestEntity.h @@ -33,13 +33,13 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cChestEntity); + /** Constructor used for normal operation */ cChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World, BLOCKTYPE a_Type); virtual ~cChestEntity(); - static const char * GetClassStatic(void) { return "cChestEntity"; } - // cBlockEntity overrides: virtual void SendTo(cClientHandle & a_Client) override; virtual void UsedBy(cPlayer * a_Player) override; diff --git a/src/BlockEntities/CommandBlockEntity.cpp b/src/BlockEntities/CommandBlockEntity.cpp index 1a5a3f01e..b7f938ffd 100644 --- a/src/BlockEntities/CommandBlockEntity.cpp +++ b/src/BlockEntities/CommandBlockEntity.cpp @@ -154,7 +154,7 @@ void cCommandBlockEntity::SendTo(cClientHandle & a_Client) void cCommandBlockEntity::Execute() { - ASSERT(m_World != NULL); // Execute should not be called before the command block is attached to a world + ASSERT(m_World != nullptr); // Execute should not be called before the command block is attached to a world if (!m_World->AreCommandBlocksEnabled()) { diff --git a/src/BlockEntities/CommandBlockEntity.h b/src/BlockEntities/CommandBlockEntity.h index 939f38610..217390293 100644 --- a/src/BlockEntities/CommandBlockEntity.h +++ b/src/BlockEntities/CommandBlockEntity.h @@ -36,6 +36,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cCommandBlockEntity); + /// Creates a new empty command block entity cCommandBlockEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); diff --git a/src/BlockEntities/DispenserEntity.cpp b/src/BlockEntities/DispenserEntity.cpp index aea854dc2..42a0476b6 100644 --- a/src/BlockEntities/DispenserEntity.cpp +++ b/src/BlockEntities/DispenserEntity.cpp @@ -28,7 +28,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); AddDropSpenserDir(DispX, DispY, DispZ, Meta); cChunk * DispChunk = a_Chunk.GetRelNeighborChunkAdjustCoords(DispX, DispZ); - if (DispChunk == NULL) + if (DispChunk == nullptr) { // Would dispense into / interact with a non-loaded chunk, ignore the tick return; @@ -105,7 +105,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) { double MobX = 0.5 + (DispX + DispChunk->GetPosX() * cChunkDef::Width); double MobZ = 0.5 + (DispZ + DispChunk->GetPosZ() * cChunkDef::Width); - if (m_World->SpawnMob(MobX, DispY, MobZ, (eMonsterType)m_Contents.GetSlot(a_SlotNum).m_ItemDamage) >= 0) + if (m_World->SpawnMob(MobX, DispY, MobZ, static_cast<eMonsterType>(m_Contents.GetSlot(a_SlotNum).m_ItemDamage)) >= 0) { m_Contents.ChangeSlotCount(a_SlotNum, -1); } @@ -190,7 +190,7 @@ void cDispenserEntity::DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) void cDispenserEntity::SpawnProjectileFromDispenser(int a_BlockX, int a_BlockY, int a_BlockZ, cProjectileEntity::eKind a_Kind, const Vector3d & a_ShootVector) { - m_World->CreateProjectile((double)a_BlockX + 0.5, (double)a_BlockY + 0.5, (double)a_BlockZ + 0.5, a_Kind, NULL, NULL, &a_ShootVector); + m_World->CreateProjectile(static_cast<double>(a_BlockX + 0.5), static_cast<double>(a_BlockY + 0.5), static_cast<double>(a_BlockZ + 0.5), a_Kind, nullptr, nullptr, &a_ShootVector); } @@ -275,6 +275,3 @@ bool cDispenserEntity::EmptyLiquidBucket(BLOCKTYPE a_BlockInFront, int a_SlotNum m_Contents.AddItem(EmptyBucket); return true; } - - - diff --git a/src/BlockEntities/DispenserEntity.h b/src/BlockEntities/DispenserEntity.h index b33d08342..5ba87b716 100644 --- a/src/BlockEntities/DispenserEntity.h +++ b/src/BlockEntities/DispenserEntity.h @@ -17,11 +17,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDispenserEntity); + /** Constructor used for normal operation */ cDispenserEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - static const char * GetClassStatic(void) { return "cDispenserEntity"; } - // tolua_begin /** Spawns a projectile of the given kind in front of the dispenser with the specified speed. */ diff --git a/src/BlockEntities/DropSpenserEntity.cpp b/src/BlockEntities/DropSpenserEntity.cpp index dac951b27..3f98836e7 100644 --- a/src/BlockEntities/DropSpenserEntity.cpp +++ b/src/BlockEntities/DropSpenserEntity.cpp @@ -28,7 +28,7 @@ cDropSpenserEntity::~cDropSpenserEntity() { // Tell window its owner is destroyed cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -155,13 +155,13 @@ void cDropSpenserEntity::SendTo(cClientHandle & a_Client) void cDropSpenserEntity::UsedBy(cPlayer * a_Player) { cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenWindow(new cDropSpenserWindow(m_PosX, m_PosY, m_PosZ, this)); Window = GetWindow(); } - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { diff --git a/src/BlockEntities/DropSpenserEntity.h b/src/BlockEntities/DropSpenserEntity.h index 23f0ae89a..f77a28c28 100644 --- a/src/BlockEntities/DropSpenserEntity.h +++ b/src/BlockEntities/DropSpenserEntity.h @@ -45,11 +45,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDropSpenserEntity); + cDropSpenserEntity(BLOCKTYPE a_BlockType, int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cDropSpenserEntity(); - static const char * GetClassStatic(void) { return "cDropSpenserEntity"; } - // cBlockEntity overrides: virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void SendTo(cClientHandle & a_Client) override; diff --git a/src/BlockEntities/DropperEntity.h b/src/BlockEntities/DropperEntity.h index 8e07bc6f8..91adf660f 100644 --- a/src/BlockEntities/DropperEntity.h +++ b/src/BlockEntities/DropperEntity.h @@ -25,11 +25,11 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cDropperEntity); + /// Constructor used for normal operation cDropperEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); - static const char * GetClassStatic(void) { return "cDropperEntity"; } - protected: // cDropSpenserEntity overrides: virtual void DropSpenseFromSlot(cChunk & a_Chunk, int a_SlotNum) override; diff --git a/src/BlockEntities/EnderChestEntity.cpp b/src/BlockEntities/EnderChestEntity.cpp index 0654d97dd..e18490a1e 100644 --- a/src/BlockEntities/EnderChestEntity.cpp +++ b/src/BlockEntities/EnderChestEntity.cpp @@ -23,7 +23,7 @@ cEnderChestEntity::cEnderChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, c cEnderChestEntity::~cEnderChestEntity() { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -37,14 +37,14 @@ void cEnderChestEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { diff --git a/src/BlockEntities/EnderChestEntity.h b/src/BlockEntities/EnderChestEntity.h index 2719eb5e4..17abd880a 100644 --- a/src/BlockEntities/EnderChestEntity.h +++ b/src/BlockEntities/EnderChestEntity.h @@ -18,11 +18,11 @@ class cEnderChestEntity : public: // tolua_end + BLOCKENTITY_PROTODEF(cEnderChestEntity); + cEnderChestEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cEnderChestEntity(); - static const char * GetClassStatic(void) { return "cEnderChestEntity"; } - // cBlockEntity overrides: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override { UNUSED(a_Client); } diff --git a/src/BlockEntities/FlowerPotEntity.cpp b/src/BlockEntities/FlowerPotEntity.cpp index 01560f814..64b7edd02 100644 --- a/src/BlockEntities/FlowerPotEntity.cpp +++ b/src/BlockEntities/FlowerPotEntity.cpp @@ -28,7 +28,7 @@ void cFlowerPotEntity::UsedBy(cPlayer * a_Player) { return; } - + cItem SelectedItem = a_Player->GetInventory().GetEquippedItem(); if (IsFlower(SelectedItem.m_ItemType, SelectedItem.m_ItemDamage)) { @@ -59,11 +59,11 @@ void cFlowerPotEntity::Destroy(void) // Drop the contents as pickups: if (!m_Item.IsEmpty()) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); cItems Pickups; Pickups.Add(m_Item); m_World->SpawnItemPickups(Pickups, m_PosX + 0.5, m_PosY + 0.5, m_PosZ + 0.5); - + m_Item.Empty(); } } @@ -88,7 +88,7 @@ bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData) } case E_BLOCK_TALL_GRASS: { - return (m_ItemData == (short) 2); + return (m_ItemData == static_cast<short>(2)); } default: { @@ -96,7 +96,3 @@ bool cFlowerPotEntity::IsFlower(short m_ItemType, short m_ItemData) } } } - - - - diff --git a/src/BlockEntities/FlowerPotEntity.h b/src/BlockEntities/FlowerPotEntity.h index b68d3b118..fc886c51f 100644 --- a/src/BlockEntities/FlowerPotEntity.h +++ b/src/BlockEntities/FlowerPotEntity.h @@ -36,7 +36,9 @@ public: // tolua_end - /** Creates a new flowerpot entity at the specified block coords. a_World may be NULL */ + BLOCKENTITY_PROTODEF(cFlowerPotEntity); + + /** Creates a new flowerpot entity at the specified block coords. a_World may be nullptr */ cFlowerPotEntity(int a_BlocX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual void Destroy(void) override; @@ -59,8 +61,6 @@ public: static bool IsFlower(short m_ItemType, short m_ItemData); - static const char * GetClassStatic(void) { return "cFlowerPotEntity"; } - private: cItem m_Item; diff --git a/src/BlockEntities/FurnaceEntity.cpp b/src/BlockEntities/FurnaceEntity.cpp index 4452fc00a..d2ec2bd1e 100644 --- a/src/BlockEntities/FurnaceEntity.cpp +++ b/src/BlockEntities/FurnaceEntity.cpp @@ -5,6 +5,7 @@ #include "../UI/Window.h" #include "../Entities/Player.h" #include "../Root.h" +#include "../Chunk.h" @@ -13,8 +14,9 @@ enum { - PROGRESSBAR_SMELTING = 0, - PROGRESSBAR_FUEL = 1, + PROGRESSBAR_FUEL = 0, + PROGRESSBAR_SMELTING = 2, + PROGRESSBAR_SMELTING_CONFIRM = 3, } ; @@ -22,17 +24,15 @@ enum cFurnaceEntity::cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World) : - super(E_BLOCK_FURNACE, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), - m_BlockType(a_BlockType), + super(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, ContentsWidth, ContentsHeight, a_World), m_BlockMeta(a_BlockMeta), - m_CurrentRecipe(NULL), - m_IsCooking((a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ) == E_BLOCK_LIT_FURNACE)), + m_CurrentRecipe(nullptr), + m_IsDestroyed(false), + m_IsCooking(a_BlockType == E_BLOCK_LIT_FURNACE), m_NeedCookTime(0), m_TimeCooked(0), m_FuelBurnTime(0), - m_TimeBurned(0), - m_LastProgressFuel(0), - m_LastProgressCook(0) + m_TimeBurned(0) { m_Contents.AddListener(*this); } @@ -45,7 +45,7 @@ cFurnaceEntity::~cFurnaceEntity() { // Tell window its owner is destroyed cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { Window->OwnerDestroyed(); } @@ -57,27 +57,28 @@ cFurnaceEntity::~cFurnaceEntity() void cFurnaceEntity::UsedBy(cPlayer * a_Player) { - if (GetWindow() == NULL) + cWindow * Window = GetWindow(); + if (Window == nullptr) { OpenWindow(new cFurnaceWindow(m_PosX, m_PosY, m_PosZ, this)); + Window = GetWindow(); } - cWindow * Window = GetWindow(); - if (Window != NULL) + + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { a_Player->OpenWindow(Window); - BroadcastProgress(PROGRESSBAR_FUEL, (short)m_LastProgressFuel); - BroadcastProgress(PROGRESSBAR_SMELTING, (short)m_LastProgressCook); } } + + UpdateProgressBars(true); } -/// Restarts cooking. Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active. Returns true if cooking. bool cFurnaceEntity::ContinueCooking(void) { UpdateInput(); @@ -92,14 +93,16 @@ bool cFurnaceEntity::ContinueCooking(void) bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); - UNUSED(a_Chunk); + if (m_FuelBurnTime <= 0) { - // No fuel is burning, reset progressbars and bail out - if ((m_LastProgressCook > 0) || (m_LastProgressFuel > 0)) - { - UpdateProgressBars(); - } + // If a furnace is out of fuel, the progress bar reverses at twice the speed of cooking. + m_TimeCooked = std::max((m_TimeCooked - 2), 0); + + // Reset progressbars, block type, and bail out + m_BlockType = E_BLOCK_FURNACE; + a_Chunk.FastSetBlock(GetRelX(), m_PosY, GetRelZ(), E_BLOCK_FURNACE, m_BlockMeta); + UpdateProgressBars(); return false; } @@ -112,16 +115,16 @@ bool cFurnaceEntity::Tick(float a_Dt, cChunk & a_Chunk) FinishOne(); } } - + m_TimeBurned++; if (m_TimeBurned >= m_FuelBurnTime) { // The current fuel has been exhausted, use another one, if possible BurnNewFuel(); } - + UpdateProgressBars(); - + return true; } @@ -139,12 +142,12 @@ void cFurnaceEntity::SendTo(cClientHandle & a_Client) -void cFurnaceEntity::BroadcastProgress(int a_ProgressbarID, short a_Value) +void cFurnaceEntity::BroadcastProgress(short a_ProgressbarID, short a_Value) { cWindow * Window = GetWindow(); - if (Window != NULL) + if (Window != nullptr) { - Window->BroadcastProgress(a_ProgressbarID, a_Value); + Window->SetProperty(a_ProgressbarID, a_Value); } } @@ -152,7 +155,6 @@ void cFurnaceEntity::BroadcastProgress(int a_ProgressbarID, short a_Value) -/// One item finished cooking void cFurnaceEntity::FinishOne() { m_TimeCooked = 0; @@ -166,8 +168,6 @@ void cFurnaceEntity::FinishOne() m_Contents.ChangeSlotCount(fsOutput, m_CurrentRecipe->Out->m_ItemCount); } m_Contents.ChangeSlotCount(fsInput, -m_CurrentRecipe->In->m_ItemCount); - - UpdateIsCooking(); } @@ -181,12 +181,11 @@ void cFurnaceEntity::BurnNewFuel(void) if (NewTime == 0) { // The item in the fuel slot is not suitable - m_FuelBurnTime = 0; - m_TimeBurned = 0; + SetBurnTimes(0, 0); SetIsCooking(false); return; } - + // Is the input and output ready for cooking? if (!CanCookInputToOutput()) { @@ -194,8 +193,7 @@ void cFurnaceEntity::BurnNewFuel(void) } // Burn one new fuel: - m_FuelBurnTime = NewTime; - m_TimeBurned = 0; + SetBurnTimes(NewTime, 0); SetIsCooking(true); if (m_Contents.GetSlot(fsFuel).m_ItemType == E_ITEM_LAVA_BUCKET) { @@ -214,33 +212,19 @@ void cFurnaceEntity::BurnNewFuel(void) void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) { super::OnSlotChanged(a_ItemGrid, a_SlotNum); - - if (m_World == NULL) + + if (m_IsDestroyed) { - // The furnace isn't initialized yet, do no processing return; } - + ASSERT(a_ItemGrid == &m_Contents); switch (a_SlotNum) { - case fsInput: - { - UpdateInput(); - break; - } - - case fsFuel: - { - UpdateFuel(); - break; - } - - case fsOutput: - { - UpdateOutput(); - break; - } + case fsInput: UpdateInput(); break; + case fsFuel: UpdateFuel(); break; + case fsOutput: UpdateOutput(); break; + default: ASSERT(!"Invalid furnace slot update!"); break; } } @@ -249,7 +233,6 @@ void cFurnaceEntity::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) -/// Updates the current recipe, based on the current input void cFurnaceEntity::UpdateInput(void) { if (!m_Contents.GetSlot(fsInput).IsEqual(m_LastInput)) @@ -258,20 +241,20 @@ void cFurnaceEntity::UpdateInput(void) m_TimeCooked = 0; } m_LastInput = m_Contents.GetSlot(fsInput); - + cFurnaceRecipe * FR = cRoot::Get()->GetFurnaceRecipe(); m_CurrentRecipe = FR->GetRecipeFrom(m_Contents.GetSlot(fsInput)); if (!CanCookInputToOutput()) { - // This input cannot be cooked - m_NeedCookTime = 0; + // This input cannot be cooked, reset cook counter immediately + SetCookTimes(0, 0); SetIsCooking(false); } else { m_NeedCookTime = m_CurrentRecipe->CookTime; SetIsCooking(true); - + // Start burning new fuel if there's no flame now: if (GetFuelBurnTimeLeft() <= 0) { @@ -284,7 +267,6 @@ void cFurnaceEntity::UpdateInput(void) -/// Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate void cFurnaceEntity::UpdateFuel(void) { if (m_FuelBurnTime > m_TimeBurned) @@ -292,7 +274,7 @@ void cFurnaceEntity::UpdateFuel(void) // The current fuel is still burning, don't modify anything: return; } - + // The current fuel is spent, try to burn some more: BurnNewFuel(); } @@ -301,18 +283,16 @@ void cFurnaceEntity::UpdateFuel(void) -/// Called when the output slot changes; starts burning if space became available void cFurnaceEntity::UpdateOutput(void) { if (!CanCookInputToOutput()) { // Cannot cook anymore: - m_TimeCooked = 0; - m_NeedCookTime = 0; + SetCookTimes(0, 0); SetIsCooking(false); return; } - + // No need to burn new fuel, the Tick() function will take care of that // Can cook, start cooking if not already underway: @@ -324,38 +304,14 @@ void cFurnaceEntity::UpdateOutput(void) -/// Updates the m_IsCooking, based on the input slot, output slot and m_FuelBurnTime / m_TimeBurned -void cFurnaceEntity::UpdateIsCooking(void) -{ - if ( - !CanCookInputToOutput() || // Cannot cook this - (m_FuelBurnTime <= 0) || // No fuel - (m_TimeBurned >= m_FuelBurnTime) // Fuel burnt out - ) - { - // Reset everything - SetIsCooking(false); - m_TimeCooked = 0; - m_NeedCookTime = 0; - return; - } - - SetIsCooking(true); -} - - - - - -/// Returns true if the input can be cooked into output and the item counts allow for another cooking operation bool cFurnaceEntity::CanCookInputToOutput(void) const { - if (m_CurrentRecipe == NULL) + if (m_CurrentRecipe == nullptr) { // This input cannot be cooked return false; } - + const cItem & Slot = m_Contents.GetSlot(fsOutput); if (Slot.IsEmpty()) { @@ -368,13 +324,13 @@ bool cFurnaceEntity::CanCookInputToOutput(void) const // The output slot is blocked with something that cannot be stacked with the recipe's output return false; } - + if (Slot.IsFullStack()) { // Cannot add any more items to the output slot return false; } - + return true; } @@ -382,25 +338,20 @@ bool cFurnaceEntity::CanCookInputToOutput(void) const -/// Broadcasts progressbar updates, if needed -void cFurnaceEntity::UpdateProgressBars(void) +void cFurnaceEntity::UpdateProgressBars(bool a_ForceUpdate) { // In order to preserve bandwidth, an update is sent only every 10th tick - // That's why the comparisons use the division by eight - - int CurFuel = (m_FuelBurnTime > 0) ? (200 - 200 * m_TimeBurned / m_FuelBurnTime) : 0; - if ((CurFuel / 8) != (m_LastProgressFuel / 8)) + if (!a_ForceUpdate && (m_World->GetWorldAge() % 10 != 0)) { - BroadcastProgress(PROGRESSBAR_FUEL, (short)CurFuel); - m_LastProgressFuel = CurFuel; + return; } + + int CurFuel = (m_FuelBurnTime > 0) ? 200 - (200 * m_TimeBurned / m_FuelBurnTime) : 0; + BroadcastProgress(PROGRESSBAR_FUEL, static_cast<short>(CurFuel)); int CurCook = (m_NeedCookTime > 0) ? (200 * m_TimeCooked / m_NeedCookTime) : 0; - if ((CurCook / 8) != (m_LastProgressCook / 8)) - { - BroadcastProgress(PROGRESSBAR_SMELTING, (short)CurCook); - m_LastProgressCook = CurCook; - } + BroadcastProgress(PROGRESSBAR_SMELTING_CONFIRM, 200); // Post 1.8, Mojang requires a random packet with an ID of three and value of 200. Wat. Wat. Wat. + BroadcastProgress(PROGRESSBAR_SMELTING, static_cast<short>(CurCook)); } @@ -413,13 +364,12 @@ void cFurnaceEntity::SetIsCooking(bool a_IsCooking) { return; } - m_IsCooking = a_IsCooking; - - // Light or extinguish the furnace: - m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, m_IsCooking ? E_BLOCK_LIT_FURNACE : E_BLOCK_FURNACE, m_BlockMeta); -} - - - + // Only light the furnace as it is extinguished only when the fuel runs out, not when cooking stops - handled in this::Tick() + if (m_IsCooking) + { + m_BlockType = E_BLOCK_LIT_FURNACE; + m_World->FastSetBlock(m_PosX, m_PosY, m_PosZ, E_BLOCK_LIT_FURNACE, m_BlockMeta); + } +} diff --git a/src/BlockEntities/FurnaceEntity.h b/src/BlockEntities/FurnaceEntity.h index ed3317af6..71c2fe127 100644 --- a/src/BlockEntities/FurnaceEntity.h +++ b/src/BlockEntities/FurnaceEntity.h @@ -38,114 +38,128 @@ public: // tolua_end - /// Constructor used for normal operation + BLOCKENTITY_PROTODEF(cFurnaceEntity); + + /** Constructor used for normal operation */ cFurnaceEntity(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cWorld * a_World); virtual ~cFurnaceEntity(); - static const char * GetClassStatic() { return "cFurnaceEntity"; } - // cBlockEntity overrides: virtual void SendTo(cClientHandle & a_Client) override; virtual bool Tick(float a_Dt, cChunk & a_Chunk) override; virtual void UsedBy(cPlayer * a_Player) override; + virtual void Destroy() override + { + m_IsDestroyed = true; + super::Destroy(); + } - /// Restarts cooking. Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active. Returns true if cooking. + /** Restarts cooking + Used after the furnace is loaded from storage to set up the internal variables so that cooking continues, if it was active + Returns true if cooking */ bool ContinueCooking(void); - - void ResetCookTimer(); // tolua_begin - /// Returns the item in the input slot + /** Returns the item in the input slot */ const cItem & GetInputSlot(void) const { return GetSlot(fsInput); } - /// Returns the item in the fuel slot + /** Returns the item in the fuel slot */ const cItem & GetFuelSlot(void) const { return GetSlot(fsFuel); } - /// Returns the item in the output slot + /** Returns the item in the output slot */ const cItem & GetOutputSlot(void) const { return GetSlot(fsOutput); } - /// Sets the item in the input slot + /** Sets the item in the input slot */ void SetInputSlot(const cItem & a_Item) { SetSlot(fsInput, a_Item); } - /// Sets the item in the fuel slot + /** Sets the item in the fuel slot */ void SetFuelSlot(const cItem & a_Item) { SetSlot(fsFuel, a_Item); } - /// Sets the item in the output slot + /** Sets the item in the output slot */ void SetOutputSlot(const cItem & a_Item) { SetSlot(fsOutput, a_Item); } - /// Returns the time that the current item has been cooking, in ticks - int GetTimeCooked(void) const {return m_TimeCooked; } + /** Returns the time that the current item has been cooking, in ticks */ + int GetTimeCooked(void) const { return m_TimeCooked; } - /// Returns the time until the current item finishes cooking, in ticks + /** Returns the time until the current item finishes cooking, in ticks */ int GetCookTimeLeft(void) const { return m_NeedCookTime - m_TimeCooked; } - /// Returns the time until the current fuel is depleted, in ticks - int GetFuelBurnTimeLeft(void) const {return m_FuelBurnTime - m_TimeBurned; } + /** Returns the time until the current fuel is depleted, in ticks */ + int GetFuelBurnTimeLeft(void) const { return m_FuelBurnTime - m_TimeBurned; } - /// Returns true if there's time left before the current fuel is depleted + /** Returns true if there's time left before the current fuel is depleted */ bool HasFuelTimeLeft(void) const { return (GetFuelBurnTimeLeft() > 0); } // tolua_end - void SetBurnTimes(int a_FuelBurnTime, int a_TimeBurned) {m_FuelBurnTime = a_FuelBurnTime; m_TimeBurned = a_TimeBurned; } - void SetCookTimes(int a_NeedCookTime, int a_TimeCooked) {m_NeedCookTime = a_NeedCookTime; m_TimeCooked = a_TimeCooked; } + void SetBurnTimes(int a_FuelBurnTime, int a_TimeBurned) + { + m_FuelBurnTime = a_FuelBurnTime; + m_TimeBurned = a_TimeBurned; + } + + void SetCookTimes(int a_NeedCookTime, int a_TimeCooked) + { + m_NeedCookTime = a_NeedCookTime; + m_TimeCooked = a_TimeCooked; + } protected: - - /// Block type of the block currently represented by this entity (changes when furnace lights up) - BLOCKTYPE m_BlockType; - /// Block meta of the block currently represented by this entity + /** Block meta of the block currently represented by this entity */ NIBBLETYPE m_BlockMeta; - /// The recipe for the current input slot + /** The recipe for the current input slot */ const cFurnaceRecipe::cRecipe * m_CurrentRecipe; - /// The item that is being smelted + /** The item that is being smelted */ cItem m_LastInput; + + /** Set to true when the furnace entity has been destroyed to prevent the block being set again */ + bool m_IsDestroyed; - bool m_IsCooking; ///< Set to true if the furnace is cooking an item - - // All timers are in ticks - int m_NeedCookTime; ///< Amount of time needed to fully cook current item - int m_TimeCooked; ///< Amount of time that the current item has been cooking - int m_FuelBurnTime; ///< Amount of time that the current fuel can burn (in total); zero if no fuel burning - int m_TimeBurned; ///< Amount of time that the current fuel has been burning - - int m_LastProgressFuel; ///< Last value sent as the progress for the fuel - int m_LastProgressCook; ///< Last value sent as the progress for the cooking + /** Set to true if the furnace is cooking an item */ + bool m_IsCooking; + /** Amount of ticks needed to fully cook current item */ + int m_NeedCookTime; + + /** Amount of ticks that the current item has been cooking */ + int m_TimeCooked; + + /** Amount of ticks that the current fuel can burn (in total); zero if no fuel burning */ + int m_FuelBurnTime; + + /** Amount of ticks that the current fuel has been burning */ + int m_TimeBurned; - /// Sends the specified progressbar value to all clients of the window - void BroadcastProgress(int a_ProgressbarID, short a_Value); + /** Sends the specified progressbar value to all clients of the window */ + void BroadcastProgress(short a_ProgressbarID, short a_Value); - /// One item finished cooking + /** One item finished cooking */ void FinishOne(); - /// Starts burning a new fuel, if possible + /** Starts burning a new fuel, if possible */ void BurnNewFuel(void); - /// Updates the recipe, based on the current input + /** Updates the recipe, based on the current input */ void UpdateInput(void); - /// Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate + /** Called when the fuel slot changes or when the fuel is spent, burns another piece of fuel if appropriate */ void UpdateFuel(void); - /// Called when the output slot changes + /** Called when the output slot changes */ void UpdateOutput(void); - /// Updates the m_IsCooking, based on the input slot, output slot and m_FuelBurnTime / m_TimeBurned - void UpdateIsCooking(void); - - /// Returns true if the input can be cooked into output and the item counts allow for another cooking operation + /** Returns true if the input can be cooked into output and the item counts allow for another cooking operation */ bool CanCookInputToOutput(void) const; - /// Broadcasts progressbar updates, if needed - void UpdateProgressBars(void); + /** Broadcasts progressbar updates, if needed */ + void UpdateProgressBars(bool a_ForceUpdate = false); - /// Sets the m_IsCooking variable, updates the furnace block type based on the value + /** Sets the m_IsCooking variable, updates the furnace block type based on the value */ void SetIsCooking(bool a_IsCooking); // cItemGrid::cListener overrides: diff --git a/src/BlockEntities/HopperEntity.cpp b/src/BlockEntities/HopperEntity.cpp index 103f516fc..fe3fb85c4 100644 --- a/src/BlockEntities/HopperEntity.cpp +++ b/src/BlockEntities/HopperEntity.cpp @@ -58,7 +58,7 @@ bool cHopperEntity::Tick(float a_Dt, cChunk & a_Chunk) { UNUSED(a_Dt); Int64 CurrentTick = a_Chunk.GetWorld()->GetWorldAge(); - + bool res = false; res = MoveItemsIn (a_Chunk, CurrentTick) || res; res = MovePickupsIn(a_Chunk, CurrentTick) || res; @@ -74,7 +74,7 @@ void cHopperEntity::SendTo(cClientHandle & a_Client) { // The hopper entity doesn't need anything sent to the client when it's created / gets in the viewdistance // All the actual handling is in the cWindow UI code that gets called when the hopper is rclked - + UNUSED(a_Client); } @@ -86,14 +86,14 @@ void cHopperEntity::UsedBy(cPlayer * a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } - + // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player->GetWindow() != Window) { @@ -138,7 +138,7 @@ bool cHopperEntity::MoveItemsIn(cChunk & a_Chunk, Int64 a_CurrentTick) // Too early after the previous transfer return false; } - + // Try moving an item in: bool res = false; switch (a_Chunk.GetBlock(m_RelX, m_PosY + 1, m_RelZ)) @@ -161,17 +161,17 @@ bool cHopperEntity::MoveItemsIn(cChunk & a_Chunk, Int64 a_CurrentTick) case E_BLOCK_DROPPER: case E_BLOCK_HOPPER: { - res = MoveItemsFromGrid(*(cBlockEntityWithItems *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); + res = MoveItemsFromGrid(*static_cast<cBlockEntityWithItems *>(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ))); break; } } - + // If the item has been moved, reset the last tick: if (res) { m_LastMoveItemsInTick = a_CurrentTick; } - + return res; } @@ -197,7 +197,7 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) virtual bool Item(cEntity * a_Entity) override { - ASSERT(a_Entity != NULL); + ASSERT(a_Entity != nullptr); if (!a_Entity->IsPickup() || a_Entity->IsDestroyed()) { @@ -205,12 +205,12 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) } Vector3f EntityPos = a_Entity->GetPosition(); - Vector3f BlockPos(m_Pos.x + 0.5f, (float)m_Pos.y + 1, m_Pos.z + 0.5f); // One block above hopper, and search from center outwards + Vector3f BlockPos(m_Pos.x + 0.5f, static_cast<float>(m_Pos.y) + 1, m_Pos.z + 0.5f); // One block above hopper, and search from center outwards double Distance = (EntityPos - BlockPos).Length(); if (Distance < 0.5) { - if (TrySuckPickupIn((cPickup *)a_Entity)) + if (TrySuckPickupIn(static_cast<cPickup *>(a_Entity))) { return false; } @@ -238,9 +238,9 @@ bool cHopperEntity::MovePickupsIn(cChunk & a_Chunk, Int64 a_CurrentTick) m_bFoundPickupsAbove = true; int PreviousCount = m_Contents.GetSlot(i).m_ItemCount; - + Item.m_ItemCount -= m_Contents.ChangeSlotCount(i, Item.m_ItemCount) - PreviousCount; // Set count to however many items were added - + if (Item.IsEmpty()) { a_Pickup->Destroy(); // Kill pickup if all items were added @@ -280,7 +280,7 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) // Too early after the previous transfer return false; } - + // Get the coords of the block where to output items: int OutX, OutY, OutZ; NIBBLETYPE Meta = a_Chunk.GetMeta(m_RelX, m_PosY, m_RelZ); @@ -294,17 +294,17 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) // Cannot output below the zero-th block level return false; } - + // Convert coords to relative: int OutRelX = OutX - a_Chunk.GetPosX() * cChunkDef::Width; int OutRelZ = OutZ - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * DestChunk = a_Chunk.GetRelNeighborChunkAdjustCoords(OutRelX, OutRelZ); - if (DestChunk == NULL) + if (DestChunk == nullptr) { // The destination chunk has been unloaded, don't tick return false; } - + // Call proper moving function, based on the blocktype present at the coords: bool res = false; switch (DestChunk->GetBlock(OutRelX, OutY, OutRelZ)) @@ -327,8 +327,8 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) case E_BLOCK_DROPPER: case E_BLOCK_HOPPER: { - cBlockEntityWithItems * BlockEntity = (cBlockEntityWithItems *)DestChunk->GetBlockEntity(OutX, OutY, OutZ); - if (BlockEntity == NULL) + cBlockEntityWithItems * BlockEntity = static_cast<cBlockEntityWithItems *>(DestChunk->GetBlockEntity(OutX, OutY, OutZ)); + if (BlockEntity == nullptr) { LOGWARNING("%s: A block entity was not found where expected at {%d, %d, %d}", __FUNCTION__, OutX, OutY, OutZ); return false; @@ -337,13 +337,13 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) break; } } - + // If the item has been moved, reset the last tick: if (res) { m_LastMoveItemsOutTick = a_CurrentTick; } - + return res; } @@ -354,8 +354,8 @@ bool cHopperEntity::MoveItemsOut(cChunk & a_Chunk, Int64 a_CurrentTick) /// Moves items from a chest (dblchest) above the hopper into this hopper. Returns true if contents have changed. bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) { - cChestEntity * MainChest = (cChestEntity *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ); - if (MainChest == NULL) + cChestEntity * MainChest = static_cast<cChestEntity *>(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); + if (MainChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); return false; @@ -365,7 +365,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) // Moved the item from the chest directly above the hopper return true; } - + // Check if the chest is a double-chest (chest directly above was empty), if so, try to move from there: static const struct { @@ -383,7 +383,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) int x = m_RelX + Coords[i].x; int z = m_RelZ + Coords[i].z; cChunk * Neighbor = a_Chunk.GetRelNeighborChunkAdjustCoords(x, z); - if (Neighbor == NULL) + if (Neighbor == nullptr) { continue; } @@ -395,8 +395,8 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) continue; } - cChestEntity * SideChest = (cChestEntity *)Neighbor->GetBlockEntity(m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z); - if (SideChest == NULL) + cChestEntity * SideChest = static_cast<cChestEntity *>(Neighbor->GetBlockEntity(m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z)); + if (SideChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX + Coords[i].x, m_PosY + 1, m_PosZ + Coords[i].z); } @@ -409,7 +409,7 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) } return false; } - + // The chest was single and nothing could be moved return false; } @@ -421,13 +421,13 @@ bool cHopperEntity::MoveItemsFromChest(cChunk & a_Chunk) /// Moves items from a furnace above the hopper into this hopper. Returns true if contents have changed. bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) { - cFurnaceEntity * Furnace = (cFurnaceEntity *)a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ); - if (Furnace == NULL) + cFurnaceEntity * Furnace = static_cast<cFurnaceEntity *>(a_Chunk.GetBlockEntity(m_PosX, m_PosY + 1, m_PosZ)); + if (Furnace == nullptr) { LOGWARNING("%s: A furnace entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, m_PosX, m_PosY + 1, m_PosZ); return false; } - + // Try move from the output slot: if (MoveItemsFromSlot(*Furnace, cFurnaceEntity::fsOutput, true)) { @@ -435,7 +435,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) Furnace->SetOutputSlot(NewOutput.AddCount(-1)); return true; } - + // No output moved, check if we can move an empty bucket out of the fuel slot: if (Furnace->GetFuelSlot().m_ItemType == E_ITEM_BUCKET) { @@ -445,7 +445,7 @@ bool cHopperEntity::MoveItemsFromFurnace(cChunk & a_Chunk) return true; } } - + // Nothing can be moved return false; } @@ -458,7 +458,7 @@ bool cHopperEntity::MoveItemsFromGrid(cBlockEntityWithItems & a_Entity) { cItemGrid & Grid = a_Entity.GetContents(); int NumSlots = Grid.GetNumSlots(); - + // First try adding items of types already in the hopper: for (int i = 0; i < NumSlots; i++) { @@ -519,7 +519,7 @@ bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_Sl // Plugin disagrees with the move continue; } - + m_Contents.ChangeSlotCount(i, 1); return true; } @@ -535,8 +535,8 @@ bool cHopperEntity::MoveItemsFromSlot(cBlockEntityWithItems & a_Entity, int a_Sl bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_BlockY, int a_BlockZ) { // Try the chest directly connected to the hopper: - cChestEntity * ConnectedChest = (cChestEntity *)a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); - if (ConnectedChest == NULL) + cChestEntity * ConnectedChest = static_cast<cChestEntity *>(a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ)); + if (ConnectedChest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d}", __FUNCTION__, a_BlockX, a_BlockY, a_BlockZ); return false; @@ -566,7 +566,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block int x = RelX + Coords[i].x; int z = RelZ + Coords[i].z; cChunk * Neighbor = a_Chunk.GetRelNeighborChunkAdjustCoords(x, z); - if (Neighbor == NULL) + if (Neighbor == nullptr) { continue; } @@ -578,8 +578,8 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block continue; } - cChestEntity * Chest = (cChestEntity *)Neighbor->GetBlockEntity(a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z); - if (Chest == NULL) + cChestEntity * Chest = static_cast<cChestEntity *>(Neighbor->GetBlockEntity(a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z)); + if (Chest == nullptr) { LOGWARNING("%s: A chest entity was not found where expected, at {%d, %d, %d} (%d, %d)", __FUNCTION__, a_BlockX + Coords[i].x, a_BlockY, a_BlockZ + Coords[i].z, x, z); continue; @@ -590,7 +590,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block } return false; } - + // The chest was single and nothing could be moved return false; } @@ -602,7 +602,7 @@ bool cHopperEntity::MoveItemsToChest(cChunk & a_Chunk, int a_BlockX, int a_Block /// Moves items to the furnace at the specified coords. Returns true if contents have changed bool cHopperEntity::MoveItemsToFurnace(cChunk & a_Chunk, int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYPE a_HopperMeta) { - cFurnaceEntity * Furnace = (cFurnaceEntity *)a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); + cFurnaceEntity * Furnace = static_cast<cFurnaceEntity *>(a_Chunk.GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ)); if (a_HopperMeta == E_META_HOPPER_FACING_YM) { // Feed the input slot of the furnace @@ -684,7 +684,3 @@ bool cHopperEntity::MoveItemsToSlot(cBlockEntityWithItems & a_Entity, int a_DstS return false; } } - - - - diff --git a/src/BlockEntities/HopperEntity.h b/src/BlockEntities/HopperEntity.h index 5d06581c2..7070bbad3 100644 --- a/src/BlockEntities/HopperEntity.h +++ b/src/BlockEntities/HopperEntity.h @@ -31,6 +31,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cHopperEntity); + /// Constructor used for normal operation cHopperEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); @@ -40,8 +42,6 @@ public: */ bool GetOutputBlockPos(NIBBLETYPE a_BlockMeta, int & a_OutputX, int & a_OutputY, int & a_OutputZ); - static const char * GetClassStatic(void) { return "cHopperEntity"; } - protected: Int64 m_LastMoveItemsInTick; diff --git a/src/BlockEntities/JukeboxEntity.cpp b/src/BlockEntities/JukeboxEntity.cpp index bb9b335e0..473526855 100644 --- a/src/BlockEntities/JukeboxEntity.cpp +++ b/src/BlockEntities/JukeboxEntity.cpp @@ -79,7 +79,7 @@ bool cJukeboxEntity::EjectRecord(void) } cItems Drops; - Drops.push_back(cItem(m_Record, 1, 0)); + Drops.push_back(cItem(static_cast<short>(m_Record), 1, 0)); m_Record = 0; m_World->SpawnItemPickups(Drops, m_PosX + 0.5, m_PosY + 1, m_PosZ + 0.5, 8); m_World->BroadcastSoundParticleEffect(1005, m_PosX, m_PosY, m_PosZ, 0); @@ -113,7 +113,3 @@ void cJukeboxEntity::SetRecord(int a_Record) { m_Record = a_Record; } - - - - diff --git a/src/BlockEntities/JukeboxEntity.h b/src/BlockEntities/JukeboxEntity.h index 49d2faa89..7a69d6499 100644 --- a/src/BlockEntities/JukeboxEntity.h +++ b/src/BlockEntities/JukeboxEntity.h @@ -26,6 +26,8 @@ public: // tolua_end + BLOCKENTITY_PROTODEF(cJukeboxEntity); + cJukeboxEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); virtual ~cJukeboxEntity(); @@ -51,8 +53,6 @@ public: // tolua_end - static const char * GetClassStatic(void) { return "cJukeboxEntity"; } - virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle &) override {} diff --git a/src/BlockEntities/MobHeadEntity.h b/src/BlockEntities/MobHeadEntity.h index fcdeaa8a6..7132ef558 100644 --- a/src/BlockEntities/MobHeadEntity.h +++ b/src/BlockEntities/MobHeadEntity.h @@ -34,7 +34,9 @@ public: // tolua_end - /** Creates a new mob head entity at the specified block coords. a_World may be NULL */ + BLOCKENTITY_PROTODEF(cMobHeadEntity); + + /** Creates a new mob head entity at the specified block coords. a_World may be nullptr */ cMobHeadEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cWorld * a_World); // tolua_begin @@ -62,8 +64,6 @@ public: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override; - static const char * GetClassStatic(void) { return "cMobHeadEntity"; } - private: eMobHeadType m_Type; diff --git a/src/BlockEntities/NoteEntity.h b/src/BlockEntities/NoteEntity.h index d1ffa126a..fc5f27d07 100644 --- a/src/BlockEntities/NoteEntity.h +++ b/src/BlockEntities/NoteEntity.h @@ -40,7 +40,9 @@ public: // tolua_end - /// Creates a new note entity. a_World may be NULL + BLOCKENTITY_PROTODEF(cNoteEntity); + + /// Creates a new note entity. a_World may be nullptr cNoteEntity(int a_X, int a_Y, int a_Z, cWorld * a_World); virtual ~cNoteEntity() {} @@ -64,8 +66,6 @@ public: } } - static const char * GetClassStatic(void) { return "cNoteEntity"; } - private: char m_Pitch; } ; // tolua_export diff --git a/src/BlockEntities/SignEntity.cpp b/src/BlockEntities/SignEntity.cpp index d048d0218..9a2695b3f 100644 --- a/src/BlockEntities/SignEntity.cpp +++ b/src/BlockEntities/SignEntity.cpp @@ -45,7 +45,7 @@ void cSignEntity::SetLines(const AString & a_Line1, const AString & a_Line2, con void cSignEntity::SetLine(int a_Index, const AString & a_Line) { - if ((a_Index < 0) || (a_Index >= (int)ARRAYCOUNT(m_Line))) + if ((a_Index < 0) || (a_Index >= static_cast<int>(ARRAYCOUNT(m_Line)))) { LOGWARNING("%s: setting a non-existent line %d (value \"%s\"", __FUNCTION__, a_Index, a_Line.c_str()); return; @@ -59,7 +59,7 @@ void cSignEntity::SetLine(int a_Index, const AString & a_Line) AString cSignEntity::GetLine(int a_Index) const { - if ((a_Index < 0) || (a_Index >= (int)ARRAYCOUNT(m_Line))) + if ((a_Index < 0) || (a_Index >= static_cast<int>(ARRAYCOUNT(m_Line)))) { LOGWARNING("%s: requesting a non-existent line %d", __FUNCTION__, a_Index); return ""; @@ -75,7 +75,3 @@ void cSignEntity::SendTo(cClientHandle & a_Client) { a_Client.SendUpdateSign(m_PosX, m_PosY, m_PosZ, m_Line[0], m_Line[1], m_Line[2], m_Line[3]); } - - - - diff --git a/src/BlockEntities/SignEntity.h b/src/BlockEntities/SignEntity.h index 53c43b758..52baa486d 100644 --- a/src/BlockEntities/SignEntity.h +++ b/src/BlockEntities/SignEntity.h @@ -34,7 +34,9 @@ public: // tolua_end - /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be NULL + BLOCKENTITY_PROTODEF(cSignEntity); + + /// Creates a new empty sign entity at the specified block coords and block type (wall or standing). a_World may be nullptr cSignEntity(BLOCKTYPE a_BlockType, int a_X, int a_Y, int a_Z, cWorld * a_World); // tolua_begin @@ -53,8 +55,6 @@ public: virtual void UsedBy(cPlayer * a_Player) override; virtual void SendTo(cClientHandle & a_Client) override; - static const char * GetClassStatic(void) { return "cSignEntity"; } - private: AString m_Line[4]; diff --git a/src/BlockID.cpp b/src/BlockID.cpp index 755c721db..c98e0cad1 100644 --- a/src/BlockID.cpp +++ b/src/BlockID.cpp @@ -4,7 +4,7 @@ #include "Globals.h" #include "BlockID.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Item.h" #include "Mobs/Monster.h" @@ -217,7 +217,12 @@ BLOCKTYPE BlockStringToType(const AString & a_BlockTypeString) bool StringToItem(const AString & a_ItemTypeString, cItem & a_Item) { - return gsBlockIDMap.ResolveItem(TrimString(a_ItemTypeString), a_Item); + AString ItemName = TrimString(a_ItemTypeString); + if (ItemName.substr(0, 10) == "minecraft:") + { + ItemName = ItemName.substr(10); + } + return gsBlockIDMap.ResolveItem(ItemName, a_Item); } diff --git a/src/BlockID.h b/src/BlockID.h index bb06722d2..24de2dc8a 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -1,7 +1,13 @@ #pragma once +// The following hackery is to allow typed C++ enum for C++ code, yet have ToLua process the values. +// ToLua doesn't understand typed enums, so we use preprocessor to hide it from ToLua. + +enum ENUM_BLOCK_ID : BLOCKTYPE +#if 0 +enum ENUM_BLOCK_ID // tolua_export +#endif // tolua_begin -enum ENUM_BLOCK_ID { E_BLOCK_AIR = 0, E_BLOCK_STONE = 1, @@ -221,6 +227,10 @@ enum ENUM_BLOCK_ID }; // tolua_end + + + + // tolua_begin enum ENUM_ITEM_ID { diff --git a/src/BlockInServerPluginInterface.h b/src/BlockInServerPluginInterface.h index e82435364..70c9944a8 100644 --- a/src/BlockInServerPluginInterface.h +++ b/src/BlockInServerPluginInterface.h @@ -6,14 +6,30 @@ #include "Root.h" #include "Bindings/PluginManager.h" -class cBlockInServerPluginInterface : public cBlockPluginInterface + + + + +class cBlockInServerPluginInterface : + public cBlockPluginInterface { public: cBlockInServerPluginInterface(cWorld & a_World) : m_World(a_World) {} + + virtual bool CallHookBlockSpread(int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) + { + return cPluginManager::Get()->CallHookBlockSpread(m_World, a_BlockX, a_BlockY, a_BlockZ, a_Source); + } + virtual bool CallHookBlockToPickups(cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) override { - return cRoot::Get()->GetPluginManager()->CallHookBlockToPickups(&m_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups); + return cPluginManager::Get()->CallHookBlockToPickups(m_World, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, a_Pickups); } + private: cWorld & m_World; }; + + + + diff --git a/src/BlockInfo.cpp b/src/BlockInfo.cpp index bdd3a9c26..bcab21e77 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -9,7 +9,7 @@ cBlockInfo::~cBlockInfo() { delete m_Handler; - m_Handler = NULL; + m_Handler = nullptr; } @@ -17,7 +17,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) { for (unsigned int i = 0; i < 256; ++i) { - if (a_Info[i].m_Handler == NULL) + if (a_Info[i].m_Handler == nullptr) { a_Info[i].m_Handler = cBlockHandler::CreateBlockHandler((BLOCKTYPE) i); } diff --git a/src/BlockInfo.h b/src/BlockInfo.h index 1e4cf2ca0..4709f2357 100644 --- a/src/BlockInfo.h +++ b/src/BlockInfo.h @@ -102,7 +102,7 @@ protected: , m_FullyOccupiesVoxel(false) , m_CanBeTerraformed(false) , m_PlaceSound("") - , m_Handler(NULL) + , m_Handler(nullptr) {} /** Cleans up the stored values */ diff --git a/src/Blocks/BlockDeadBush.h b/src/Blocks/BlockDeadBush.h index 5b687c710..09df16893 100644 --- a/src/Blocks/BlockDeadBush.h +++ b/src/Blocks/BlockDeadBush.h @@ -17,15 +17,25 @@ public: } - virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override - { - // Don't drop anything - } - - virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return (a_RelY > 0) && (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) == E_BLOCK_SAND); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); + switch (BelowBlock) + { + case E_BLOCK_CLAY: + case E_BLOCK_HARDENED_CLAY: + case E_BLOCK_STAINED_CLAY: + case E_BLOCK_SAND: + { + return true; + } + default: return false; + } } } ; diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index 19f889372..aae6719e2 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -72,7 +72,7 @@ public: int BlockY = a_RelY + OfsY; int BlockZ = a_RelZ + OfsZ; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(BlockX, BlockZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Unloaded chunk continue; @@ -89,7 +89,7 @@ public: Chunk->GetBlockTypeMeta(BlockX, BlockY + 1, BlockZ, AboveDest, AboveMeta); if (cBlockInfo::GetHandler(AboveDest)->CanDirtGrowGrass(AboveMeta)) { - if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread(Chunk->GetWorld(), Chunk->GetPosX() * cChunkDef::Width + BlockX, BlockY, Chunk->GetPosZ() * cChunkDef::Width + BlockZ, ssGrassSpread)) + if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread(*Chunk->GetWorld(), Chunk->GetPosX() * cChunkDef::Width + BlockX, BlockY, Chunk->GetPosZ() * cChunkDef::Width + BlockZ, ssGrassSpread)) { Chunk->FastSetBlock(BlockX, BlockY, BlockZ, E_BLOCK_GRASS, 0); } diff --git a/src/Blocks/BlockHandler.cpp b/src/Blocks/BlockHandler.cpp index 904e0a921..60f13a747 100644 --- a/src/Blocks/BlockHandler.cpp +++ b/src/Blocks/BlockHandler.cpp @@ -4,6 +4,7 @@ #include "../Item.h" #include "../World.h" #include "../Chunk.h" +#include "BlockPluginInterface.h" #include "BlockAnvil.h" #include "BlockBed.h" #include "BlockBigFlower.h" @@ -82,7 +83,6 @@ #include "BlockWorkbench.h" -#include "BlockPluginInterface.h" @@ -99,9 +99,9 @@ public: for (BLOCKTYPE Type = 0; Type < E_BLOCK_MAX_TYPE_ID; Type++) { cBlockHandler * Handler = cBlockInfo::GetHandler(Type); - if (Handler == NULL) + if (Handler == nullptr) { - printf("NULL handler for block type %d!\n", Type); + printf("nullptr handler for block type %d!\n", Type); continue; } AString BlockName = ItemTypeToString(Type); @@ -441,7 +441,7 @@ void cBlockHandler::DropBlock(cChunkInterface & a_ChunkInterface, cWorldInterfac if (a_CanDrop) { - if ((a_Digger != NULL) && (a_Digger->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchSilkTouch) > 0)) + if ((a_Digger != nullptr) && (a_Digger->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchSilkTouch) > 0)) { switch (m_BlockType) { @@ -562,7 +562,7 @@ void cBlockHandler::Check(cChunkInterface & a_ChunkInterface, cBlockPluginInterf { int BlockX = a_RelX + a_Chunk.GetPosX() * cChunkDef::Width; int BlockZ = a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width; - DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); } a_Chunk.SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); diff --git a/src/Blocks/BlockHandler.h b/src/Blocks/BlockHandler.h index 83de836cb..f2298afb5 100644 --- a/src/Blocks/BlockHandler.h +++ b/src/Blocks/BlockHandler.h @@ -78,7 +78,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta); /** Handles the dropping, but not destruction, of a block based on what ConvertTo(Verbatim)Pickups() returns, including the spawning of pickups and alertion of plugins - @param a_Digger The entity causing the drop; it may be NULL + @param a_Digger The entity causing the drop; it may be nullptr @param a_CanDrop Informs the handler whether the block should be dropped at all. One example when this is false is when stone is destroyed by hand @param a_DropVerbatim Calls ConvertToVerbatimPickups() instead of its counterpart, meaning the block itself is dropped by default (due to a speical tool or enchantment) */ diff --git a/src/Blocks/BlockLeaves.h b/src/Blocks/BlockLeaves.h index add571675..bd9a7414e 100644 --- a/src/Blocks/BlockLeaves.h +++ b/src/Blocks/BlockLeaves.h @@ -109,7 +109,7 @@ public: } // Decay the leaves: - DropBlock(a_ChunkInterface, a_WorldInterface, a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, a_WorldInterface, a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); a_ChunkInterface.DigBlock(a_WorldInterface, BlockX, a_RelY, BlockZ); } } ; diff --git a/src/Blocks/BlockLever.h b/src/Blocks/BlockLever.h index 3b63b396c..f5bedea6c 100644 --- a/src/Blocks/BlockLever.h +++ b/src/Blocks/BlockLever.h @@ -1,9 +1,9 @@ #pragma once #include "BlockHandler.h" +#include "../Chunk.h" #include "MetaRotator.h" - - +#include "BlockSlab.h" class cBlockLeverHandler : @@ -93,13 +93,35 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - NIBBLETYPE Meta; - a_Chunk.UnboundedRelGetBlockMeta(a_RelX, a_RelY, a_RelZ, Meta); + NIBBLETYPE Meta = a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ); + + eBlockFace Face = BlockMetaDataToBlockFace(Meta); + + AddFaceDirection(a_RelX, a_RelY, a_RelZ, Face, true); + + if ((a_RelY < 0) || (a_RelY >= cChunkDef::Height -1)) + { + return false; + } + + BLOCKTYPE BlockIsOn; + a_Chunk.UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockIsOn, Meta); - AddFaceDirection(a_RelX, a_RelY, a_RelZ, BlockMetaDataToBlockFace(Meta), true); - BLOCKTYPE BlockIsOn; a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, BlockIsOn); - return (a_RelY > 0) && cBlockInfo::FullyOccupiesVoxel(BlockIsOn); + if (cBlockInfo::FullyOccupiesVoxel(BlockIsOn)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BlockIsOn)) + { + // Check if the slab is turned up side down + if (((Meta & 0x08) == 0x08) && (Face == BLOCK_FACE_TOP)) + { + return true; + } + } + + return false; } diff --git a/src/Blocks/BlockPiston.cpp b/src/Blocks/BlockPiston.cpp index 34d11f675..8d245cabe 100644 --- a/src/Blocks/BlockPiston.cpp +++ b/src/Blocks/BlockPiston.cpp @@ -139,7 +139,7 @@ void cBlockPistonHandler::ExtendPiston(int a_BlockX, int a_BlockY, int a_BlockZ, { cChunkInterface ChunkInterface(a_World->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*a_World); - Handler->DropBlock(ChunkInterface, *a_World, PluginInterface, NULL, a_BlockX, a_BlockY, a_BlockZ); + Handler->DropBlock(ChunkInterface, *a_World, PluginInterface, nullptr, a_BlockX, a_BlockY, a_BlockZ); } } diff --git a/src/Blocks/BlockPluginInterface.h b/src/Blocks/BlockPluginInterface.h index 3a36c40b1..b769bcf3e 100644 --- a/src/Blocks/BlockPluginInterface.h +++ b/src/Blocks/BlockPluginInterface.h @@ -1,7 +1,11 @@ #pragma once -/** This interface is used to decouple block handlers from the cPluginManager dependancy through cWorld. + + + + +/** This interface is used to decouple block handlers from the cPluginManager dependency through cWorld. The block handlers call this interface, which is then implemented by the specific classes that the caller provides. */ @@ -10,5 +14,10 @@ class cBlockPluginInterface public: virtual ~cBlockPluginInterface() {} + virtual bool CallHookBlockSpread(int a_BlockX, int a_BlockY, int a_BlockZ, eSpreadSource a_Source) = 0; virtual bool CallHookBlockToPickups(cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, cItems & a_Pickups) = 0; }; + + + + diff --git a/src/Blocks/BlockRedstone.h b/src/Blocks/BlockRedstone.h index 37d61ed73..2785eb479 100644 --- a/src/Blocks/BlockRedstone.h +++ b/src/Blocks/BlockRedstone.h @@ -3,6 +3,7 @@ #include "BlockHandler.h" #include "../World.h" +#include "BlockSlab.h" @@ -16,11 +17,33 @@ public: : cBlockHandler(a_BlockType) { } - + + virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return ((a_RelY > 0) && cBlockInfo::FullyOccupiesVoxel(a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ))); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock; + NIBBLETYPE BelowBlockMeta; + a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY - 1, a_RelZ, BelowBlock, BelowBlockMeta); + + if (cBlockInfo::FullyOccupiesVoxel(BelowBlock)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BelowBlock)) + { + // Check if the slab is turned up side down + if ((BelowBlockMeta & 0x08) == 0x08) + { + return true; + } + } + return false; } diff --git a/src/Blocks/BlockRedstoneRepeater.h b/src/Blocks/BlockRedstoneRepeater.h index 1eb67f714..e8262dc40 100644 --- a/src/Blocks/BlockRedstoneRepeater.h +++ b/src/Blocks/BlockRedstoneRepeater.h @@ -5,6 +5,7 @@ #include "Chunk.h" #include "MetaRotator.h" #include "ChunkInterface.h" +#include "BlockSlab.h" @@ -44,6 +45,7 @@ public: } + virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { // Reset meta to zero @@ -59,7 +61,28 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return ((a_RelY > 0) && cBlockInfo::IsSolid(a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ))); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock; + NIBBLETYPE BelowBlockMeta; + a_Chunk.GetBlockTypeMeta(a_RelX, a_RelY - 1, a_RelZ, BelowBlock, BelowBlockMeta); + + if (cBlockInfo::FullyOccupiesVoxel(BelowBlock)) + { + return true; + } + else if (cBlockSlabHandler::IsAnySlabType(BelowBlock)) + { + // Check if the slab is turned up side down + if ((BelowBlockMeta & 0x08) == 0x08) + { + return true; + } + } + return false; } diff --git a/src/Blocks/BlockSignPost.h b/src/Blocks/BlockSignPost.h index 40e15c253..d97501651 100644 --- a/src/Blocks/BlockSignPost.h +++ b/src/Blocks/BlockSignPost.h @@ -35,7 +35,7 @@ public: } BLOCKTYPE Type = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); - return ((Type == E_BLOCK_SIGN_POST) || cBlockInfo::IsSolid(Type)); + return ((Type == E_BLOCK_SIGN_POST) || (Type == E_BLOCK_WALLSIGN) || cBlockInfo::IsSolid(Type)); } diff --git a/src/Blocks/BlockSlab.h b/src/Blocks/BlockSlab.h index ffe2414f7..d762154df 100644 --- a/src/Blocks/BlockSlab.h +++ b/src/Blocks/BlockSlab.h @@ -13,6 +13,7 @@ #include "../Items/ItemHandler.h" #include "Root.h" #include "ChunkInterface.h" +#include "../Entities/Player.h" diff --git a/src/Blocks/BlockTallGrass.h b/src/Blocks/BlockTallGrass.h index f520414a7..8e821b899 100644 --- a/src/Blocks/BlockTallGrass.h +++ b/src/Blocks/BlockTallGrass.h @@ -2,6 +2,7 @@ #pragma once #include "BlockHandler.h" +#include "ChunkInterface.h" @@ -10,6 +11,7 @@ class cBlockTallGrassHandler : public cBlockHandler { + typedef cBlockHandler super; public: cBlockTallGrassHandler(BLOCKTYPE a_BlockType) : cBlockHandler(a_BlockType) @@ -26,32 +28,58 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { // Drop seeds, sometimes - MTRand r1; - if (r1.randInt(10) == 5) + cFastRandom Random; + if (Random.NextInt(8) == 0) { a_Pickups.push_back(cItem(E_ITEM_SEEDS, 1, 0)); } } - virtual void OnDestroyedByPlayer(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ) override + virtual void DropBlock(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cBlockPluginInterface & a_BlockPluginInterface, cEntity * a_Digger, int a_BlockX, int a_BlockY, int a_BlockZ, bool a_CanDrop) override { - NIBBLETYPE Meta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); - - if ((!a_Player->IsGameModeCreative()) && (a_Player->GetEquippedItem().m_ItemType == E_ITEM_SHEARS)) + if (a_CanDrop && (a_Digger != NULL) && (a_Digger->GetEquippedWeapon().m_ItemType == E_ITEM_SHEARS)) { - cItems Pickups; - Pickups.Add(E_BLOCK_TALL_GRASS, 1, Meta); - a_WorldInterface.SpawnItemPickups(Pickups, a_BlockX, a_BlockY, a_BlockZ); - - a_Player->UseEquippedItem(); + NIBBLETYPE Meta = a_ChunkInterface.GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); + cItems Drops; + Drops.Add(m_BlockType, 1, Meta); + + // Allow plugins to modify the pickups: + a_BlockPluginInterface.CallHookBlockToPickups(a_Digger, a_BlockX, a_BlockY, a_BlockZ, m_BlockType, Meta, Drops); + + // Spawn the pickups: + if (!Drops.empty()) + { + MTRand r1; + + // Mid-block position first + double MicroX, MicroY, MicroZ; + MicroX = a_BlockX + 0.5; + MicroY = a_BlockY + 0.5; + MicroZ = a_BlockZ + 0.5; + + // Add random offset second + MicroX += r1.rand(1) - 0.5; + MicroZ += r1.rand(1) - 0.5; + + a_WorldInterface.SpawnItemPickups(Drops, MicroX, MicroY, MicroZ); + } + return; } + + super::DropBlock(a_ChunkInterface, a_WorldInterface, a_BlockPluginInterface, a_Digger, a_BlockX, a_BlockY, a_BlockZ, a_CanDrop); } virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { - return ((a_RelY > 0) && (a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ) != E_BLOCK_AIR)); + if (a_RelY <= 0) + { + return false; + } + + BLOCKTYPE BelowBlock = a_Chunk.GetBlock(a_RelX, a_RelY - 1, a_RelZ); + return IsBlockTypeOfDirt(BelowBlock); } } ; diff --git a/src/Blocks/BlockVine.h b/src/Blocks/BlockVine.h index 06d84f2d4..00d7a69b8 100644 --- a/src/Blocks/BlockVine.h +++ b/src/Blocks/BlockVine.h @@ -23,10 +23,6 @@ public: BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta ) override { - UNUSED(a_Player); - UNUSED(a_CursorX); - UNUSED(a_CursorY); - UNUSED(a_CursorZ); // TODO: Disallow placement where the vine doesn't attach to something properly BLOCKTYPE BlockType = 0; NIBBLETYPE BlockMeta; @@ -80,7 +76,21 @@ public: /// Returns true if the specified block type is good for vines to attach to static bool IsBlockAttachable(BLOCKTYPE a_BlockType) { - return ((a_BlockType == E_BLOCK_LEAVES) || (a_BlockType == E_BLOCK_NEW_LEAVES) || cBlockInfo::IsSolid(a_BlockType)); + switch (a_BlockType) + { + case E_BLOCK_GLASS: + case E_BLOCK_STAINED_GLASS: + case E_BLOCK_CHEST: + case E_BLOCK_TRAPPED_CHEST: + { + // You can't attach a vine to this solid blocks. + return false; + } + default: + { + return cBlockInfo::IsSolid(a_BlockType); + } + } } @@ -138,7 +148,7 @@ public: { int BlockX = a_RelX + a_Chunk.GetPosX() * cChunkDef::Width; int BlockZ = a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width; - DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, NULL, BlockX, a_RelY, BlockZ); + DropBlock(a_ChunkInterface, *a_Chunk.GetWorld(), a_PluginInterface, nullptr, BlockX, a_RelY, BlockZ); } a_Chunk.SetBlock(a_RelX, a_RelY, a_RelZ, E_BLOCK_AIR, 0); return; @@ -166,23 +176,31 @@ public: return false; } + virtual void OnUpdate(cChunkInterface & a_ChunkInterface, cWorldInterface & a_WorldInterface, cBlockPluginInterface & a_BlockPluginInterface, cChunk & a_Chunk, int a_RelX, int a_RelY, int a_RelZ) { UNUSED(a_ChunkInterface); UNUSED(a_WorldInterface); - UNUSED(a_BlockPluginInterface); + // Vine cannot grow down if at the bottom: + if (a_RelY < 1) + { + return; + } + + // Grow one block down, if possible: BLOCKTYPE Block; a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY - 1, a_RelZ, Block); if (Block == E_BLOCK_AIR) { - if (!cRoot::Get()->GetPluginManager()->CallHookBlockSpread((cWorld*) &a_WorldInterface, a_RelX + a_Chunk.GetPosX() * cChunkDef::Width, a_RelY - 1, a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width, ssVineSpread)) + if (!a_BlockPluginInterface.CallHookBlockSpread(a_RelX + a_Chunk.GetPosX() * cChunkDef::Width, a_RelY - 1, a_RelZ + a_Chunk.GetPosZ() * cChunkDef::Width, ssVineSpread)) { a_Chunk.UnboundedRelSetBlock(a_RelX, a_RelY - 1, a_RelZ, E_BLOCK_VINES, a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ)); } } } + virtual NIBBLETYPE MetaRotateCCW(NIBBLETYPE a_Meta) override { return ((a_Meta >> 1) | (a_Meta << 3)) & 0x0f; // Rotate bits to the right diff --git a/src/Blocks/BroadcastInterface.h b/src/Blocks/BroadcastInterface.h index cf332b153..bf464627d 100644 --- a/src/Blocks/BroadcastInterface.h +++ b/src/Blocks/BroadcastInterface.h @@ -7,6 +7,6 @@ public: virtual ~cBroadcastInterface() {} virtual void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) = 0; - virtual void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL) = 0; - virtual void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL) = 0; + virtual void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr) = 0; + virtual void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr) = 0; }; diff --git a/src/ByteBuffer.cpp b/src/ByteBuffer.cpp index dc6b32a44..012105ca1 100644 --- a/src/ByteBuffer.cpp +++ b/src/ByteBuffer.cpp @@ -165,7 +165,7 @@ cByteBuffer::~cByteBuffer() { CheckValid(); delete[] m_Buffer; - m_Buffer = NULL; + m_Buffer = nullptr; } diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 9d0e2cede..096fa824d 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -34,6 +34,7 @@ SET (SRCS FastRandom.cpp FurnaceRecipe.cpp Globals.cpp + IniFile.cpp Inventory.cpp Item.cpp ItemGrid.cpp @@ -98,6 +99,7 @@ SET (HDRS ForEachChunkProvider.h FurnaceRecipe.h Globals.h + IniFile.h Inventory.h Item.h ItemGrid.h @@ -320,4 +322,4 @@ endif () if (WIN32) target_link_libraries(${EXECUTABLE} expat tolualib ws2_32.lib Psapi.lib) endif() -target_link_libraries(${EXECUTABLE} luaexpat iniFile jsoncpp polarssl zlib sqlite lua SQLiteCpp) +target_link_libraries(${EXECUTABLE} luaexpat jsoncpp polarssl zlib sqlite lua SQLiteCpp) diff --git a/src/CheckBasicStyle.lua b/src/CheckBasicStyle.lua index b244b1fbc..76ae8c325 100644 --- a/src/CheckBasicStyle.lua +++ b/src/CheckBasicStyle.lua @@ -41,6 +41,7 @@ local g_ShouldProcessExt = --- The list of files not to be processed: local g_IgnoredFiles = { + "Bindings/Bindings.h", "Bindings/Bindings.cpp", "LeakFinder.cpp", "LeakFinder.h", diff --git a/src/Chunk.cpp b/src/Chunk.cpp index 96b8eda4e..a0224322a 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -95,19 +95,19 @@ cChunk::cChunk( m_RedstoneSimulatorData(a_World->GetRedstoneSimulator()->CreateChunkData()), m_AlwaysTicked(0) { - if (a_NeighborXM != NULL) + if (a_NeighborXM != nullptr) { a_NeighborXM->m_NeighborXP = this; } - if (a_NeighborXP != NULL) + if (a_NeighborXP != nullptr) { a_NeighborXP->m_NeighborXM = this; } - if (a_NeighborZM != NULL) + if (a_NeighborZM != nullptr) { a_NeighborZM->m_NeighborZP = this; } - if (a_NeighborZP != NULL) + if (a_NeighborZP != nullptr) { a_NeighborZP->m_NeighborZM = this; } @@ -119,7 +119,7 @@ cChunk::cChunk( cChunk::~cChunk() { - cPluginManager::Get()->CallHookChunkUnloaded(m_World, m_PosX, m_PosZ); + cPluginManager::Get()->CallHookChunkUnloaded(*m_World, m_PosX, m_PosZ); // LOGINFO("### delete cChunk() (%i, %i) from %p, thread 0x%x ###", m_PosX, m_PosZ, this, GetCurrentThreadId()); @@ -141,28 +141,28 @@ cChunk::~cChunk() } } - if (m_NeighborXM != NULL) + if (m_NeighborXM != nullptr) { - m_NeighborXM->m_NeighborXP = NULL; + m_NeighborXM->m_NeighborXP = nullptr; } - if (m_NeighborXP != NULL) + if (m_NeighborXP != nullptr) { - m_NeighborXP->m_NeighborXM = NULL; + m_NeighborXP->m_NeighborXM = nullptr; } - if (m_NeighborZM != NULL) + if (m_NeighborZM != nullptr) { - m_NeighborZM->m_NeighborZP = NULL; + m_NeighborZM->m_NeighborZP = nullptr; } - if (m_NeighborZP != NULL) + if (m_NeighborZP != nullptr) { - m_NeighborZP->m_NeighborZM = NULL; + m_NeighborZP->m_NeighborZM = nullptr; } delete m_WaterSimulatorData; - m_WaterSimulatorData = NULL; + m_WaterSimulatorData = nullptr; delete m_LavaSimulatorData; - m_LavaSimulatorData = NULL; + m_LavaSimulatorData = nullptr; delete m_RedstoneSimulatorData; - m_RedstoneSimulatorData = NULL; + m_RedstoneSimulatorData = nullptr; } @@ -333,7 +333,7 @@ void cChunk::SetAllData(cSetChunkData & a_SetChunkData) { BLOCKTYPE EntityBlockType = (*itr)->GetBlockType(); BLOCKTYPE WorldBlockType = GetBlock((*itr)->GetRelX(), (*itr)->GetPosY(), (*itr)->GetRelZ()); - ASSERT(EntityBlockType == WorldBlockType); + ASSERT(WorldBlockType == EntityBlockType); } // for itr - m_BlockEntities #endif // _DEBUG @@ -581,7 +581,7 @@ void cChunk::SpawnMobs(cMobSpawner& a_MobSpawner) } cEntity * newMob = a_MobSpawner.TryToSpawnHere(this, TryX, TryY, TryZ, Biome, MaxNbOfSuccess); - if (newMob == NULL) + if (newMob == nullptr) { continue; } @@ -639,7 +639,7 @@ void cChunk::Tick(float a_Dt) { // Remove all entities that are travelling to another world MarkDirty(); - (*itr)->SetWorldTravellingFrom(NULL); + (*itr)->SetWorldTravellingFrom(nullptr); itr = m_Entities.erase(itr); } else if ( @@ -668,7 +668,7 @@ void cChunk::Tick(float a_Dt) void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ) { cBlockHandler * Handler = BlockHandler(GetBlock(a_RelX, a_RelY, a_RelZ)); - ASSERT(Handler != NULL); // Happenned on server restart, FS #243 + ASSERT(Handler != nullptr); // Happenned on server restart, FS #243 cChunkInterface ChunkInterface(this->GetWorld()->GetChunkMap()); cBlockInServerPluginInterface PluginInterface(*this->GetWorld()); Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, a_RelX, a_RelY, a_RelZ); @@ -681,10 +681,10 @@ void cChunk::TickBlock(int a_RelX, int a_RelY, int a_RelZ) void cChunk::MoveEntityToNewChunk(cEntity * a_Entity) { cChunk * Neighbor = GetNeighborChunk(a_Entity->GetChunkX() * cChunkDef::Width, a_Entity->GetChunkZ() * cChunkDef::Width); - if (Neighbor == NULL) + if (Neighbor == nullptr) { Neighbor = m_ChunkMap->GetChunkNoLoad(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); - if (Neighbor == NULL) + if (Neighbor == nullptr) { // TODO: What to do with this? LOGWARNING("%s: Failed to move entity, destination chunk unreachable. Entity lost", __FUNCTION__); @@ -847,7 +847,7 @@ void cChunk::TickBlocks(void) } cBlockHandler * Handler = BlockHandler(GetBlock(m_BlockTickX, m_BlockTickY, m_BlockTickZ)); - ASSERT(Handler != NULL); // Happenned on server restart, FS #243 + ASSERT(Handler != nullptr); // Happenned on server restart, FS #243 Handler->OnUpdate(ChunkInterface, *this->GetWorld(), PluginInterface, *this, m_BlockTickX, m_BlockTickY, m_BlockTickZ); } // for i - tickblocks } @@ -1127,7 +1127,7 @@ bool cChunk::UnboundedRelGetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1148,7 +1148,7 @@ bool cChunk::UnboundedRelGetBlockType(int a_RelX, int a_RelY, int a_RelZ, BLOCKT return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1169,7 +1169,7 @@ bool cChunk::UnboundedRelGetBlockMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1190,7 +1190,7 @@ bool cChunk::UnboundedRelGetBlockBlockLight(int a_RelX, int a_RelY, int a_RelZ, return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1211,7 +1211,7 @@ bool cChunk::UnboundedRelGetBlockSkyLight(int a_RelX, int a_RelY, int a_RelZ, NI return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1232,7 +1232,7 @@ bool cChunk::UnboundedRelGetBlockLights(int a_RelX, int a_RelY, int a_RelZ, NIBB return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1254,7 +1254,7 @@ bool cChunk::UnboundedRelSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1275,7 +1275,7 @@ bool cChunk::UnboundedRelFastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKT return false; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { // The chunk is not available, bail out return false; @@ -1296,7 +1296,7 @@ void cChunk::UnboundedQueueTickBlock(int a_RelX, int a_RelY, int a_RelZ) return; } cChunk * Chunk = GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->QueueTickBlock(a_RelX, a_RelY, a_RelZ); } @@ -1452,12 +1452,12 @@ void cChunk::SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, // If there was a block entity, remove it: Vector3i WorldPos = PositionToWorldPosition(a_RelX, a_RelY, a_RelZ); cBlockEntity * BlockEntity = GetBlockEntity(WorldPos); - if (BlockEntity != NULL) + if (BlockEntity != nullptr) { BlockEntity->Destroy(); RemoveBlockEntity(BlockEntity); delete BlockEntity; - BlockEntity = NULL; + BlockEntity = nullptr; } // If the new block is a block entity, create the entity object: @@ -1619,7 +1619,7 @@ void cChunk::FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockT void cChunk::SendBlockTo(int a_RelX, int a_RelY, int a_RelZ, cClientHandle * a_Client) { - if (a_Client == NULL) + if (a_Client == nullptr) { // Queue the block for all clients in the chunk (will be sent in Tick()) m_PendingSendBlocks.push_back(sSetBlock(m_PosX, m_PosZ, a_RelX, a_RelY, a_RelZ, GetBlock(a_RelX, a_RelY, a_RelZ), GetMeta(a_RelX, a_RelY, a_RelZ))); @@ -1673,7 +1673,7 @@ cBlockEntity * cChunk::GetBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ) } } // for itr - m_BlockEntities[] - return NULL; + return nullptr; } @@ -1708,7 +1708,7 @@ void cChunk::SetAlwaysTicked(bool a_AlwaysTicked) 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) + if (be != nullptr) { be->UsedBy(a_Player); } @@ -1742,7 +1742,7 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max // Re-send the chunk to all clients: for (cClientHandleList::iterator itr = m_LoadedByClient.begin(); itr != m_LoadedByClient.end(); ++itr) { - m_World->ForceSendChunkTo(m_PosX, m_PosZ, (*itr)); + m_World->ForceSendChunkTo(m_PosX, m_PosZ, cChunkSender::E_CHUNK_PRIORITY_MEDIUM, (*itr)); } // for itr - m_LoadedByClient[] } @@ -1750,11 +1750,11 @@ void cChunk::SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_Max -void cChunk::CollectPickupsByPlayer(cPlayer * a_Player) +void cChunk::CollectPickupsByPlayer(cPlayer & a_Player) { - double PosX = a_Player->GetPosX(); - double PosY = a_Player->GetPosY(); - double PosZ = a_Player->GetPosZ(); + 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) { @@ -2614,7 +2614,7 @@ BLOCKTYPE cChunk::GetBlock(int a_RelX, int a_RelY, int a_RelZ) const -void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) +void cChunk::GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const { a_BlockType = GetBlock(a_RelX, a_RelY, a_RelZ); a_BlockMeta = m_ChunkData.GetMeta(a_RelX, a_RelY, a_RelZ); @@ -2664,10 +2664,10 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) bool ReturnThis = true; if (a_RelX < 0) { - if (m_NeighborXM != NULL) + if (m_NeighborXM != nullptr) { cChunk * Candidate = m_NeighborXM->GetRelNeighborChunk(a_RelX + cChunkDef::Width, a_RelZ); - if (Candidate != NULL) + if (Candidate != nullptr) { return Candidate; } @@ -2677,10 +2677,10 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) } else if (a_RelX >= cChunkDef::Width) { - if (m_NeighborXP != NULL) + if (m_NeighborXP != nullptr) { cChunk * Candidate = m_NeighborXP->GetRelNeighborChunk(a_RelX - cChunkDef::Width, a_RelZ); - if (Candidate != NULL) + if (Candidate != nullptr) { return Candidate; } @@ -2691,24 +2691,24 @@ cChunk * cChunk::GetRelNeighborChunk(int a_RelX, int a_RelZ) if (a_RelZ < 0) { - if (m_NeighborZM != NULL) + if (m_NeighborZM != nullptr) { return m_NeighborZM->GetRelNeighborChunk(a_RelX, a_RelZ + cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } - return NULL; + return nullptr; } else if (a_RelZ >= cChunkDef::Width) { - if (m_NeighborZP != NULL) + if (m_NeighborZP != nullptr) { return m_NeighborZP->GetRelNeighborChunk(a_RelX, a_RelZ - cChunkDef::Width); // For requests crossing both X and Z, the X-first way has been already tried } - return NULL; + return nullptr; } - return (ReturnThis ? this : NULL); + return (ReturnThis ? this : nullptr); } @@ -2731,27 +2731,27 @@ cChunk * cChunk::GetRelNeighborChunkAdjustCoords(int & a_RelX, int & a_RelZ) con // Request for a different chunk, calculate chunk offset: int RelX = a_RelX; // Make a local copy of the coords (faster access) int RelZ = a_RelZ; - while ((RelX >= Width) && (ToReturn != NULL)) + while ((RelX >= Width) && (ToReturn != nullptr)) { RelX -= Width; ToReturn = ToReturn->m_NeighborXP; } - while ((RelX < 0) && (ToReturn != NULL)) + while ((RelX < 0) && (ToReturn != nullptr)) { RelX += Width; ToReturn = ToReturn->m_NeighborXM; } - while ((RelZ >= Width) && (ToReturn != NULL)) + while ((RelZ >= Width) && (ToReturn != nullptr)) { RelZ -= Width; ToReturn = ToReturn->m_NeighborZP; } - while ((RelZ < 0) && (ToReturn != NULL)) + while ((RelZ < 0) && (ToReturn != nullptr)) { RelZ += Width; ToReturn = ToReturn->m_NeighborZM; } - if (ToReturn != NULL) + if (ToReturn != nullptr) { a_RelX = RelX; a_RelZ = RelZ; @@ -2821,7 +2821,7 @@ void cChunk::BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cons { // We can operate on entity pointers, we're inside the ChunkMap's CS lock which guards the list cBlockEntity * Entity = GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); - if (Entity == NULL) + if (Entity == nullptr) { return; } @@ -3158,7 +3158,7 @@ void cChunk::BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_Block void cChunk::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client) { cBlockEntity * Entity = GetBlockEntity(a_BlockX, a_BlockY, a_BlockZ); - if (Entity == NULL) + if (Entity == nullptr) { return; } diff --git a/src/Chunk.h b/src/Chunk.h index bc66b6528..6f4ac5cac 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -33,7 +33,7 @@ class cChunkMap; class cBeaconEntity; class cBoundingBox; class cChestEntity; -class cCHunkDataCallback; +class cChunkDataCallback; class cCommandBlockEntity; class cDispenserEntity; class cFurnaceEntity; @@ -186,17 +186,17 @@ public: void FastSetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_BlockType, BLOCKTYPE a_BlockMeta, bool a_SendToClients = true); // Doesn't force block updates on neighbors, use for simple changes such as grass growing etc. BLOCKTYPE GetBlock(int a_RelX, int a_RelY, int a_RelZ) const; BLOCKTYPE GetBlock(const Vector3i & a_RelCoords) const { return GetBlock(a_RelCoords.x, a_RelCoords.y, a_RelCoords.z); } - void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta); + void GetBlockTypeMeta(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta) const; void GetBlockInfo (int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE & a_BlockType, NIBBLETYPE & a_Meta, NIBBLETYPE & a_SkyLight, NIBBLETYPE & a_BlockLight); /** Returns the chunk into which the specified block belongs, by walking the neighbors. - Will return self if appropriate. Returns NULL if not reachable through neighbors. + Will return self if appropriate. Returns nullptr if not reachable through neighbors. */ cChunk * GetNeighborChunk(int a_BlockX, int a_BlockZ); /** Returns the chunk into which the relatively-specified block belongs, by walking the neighbors. - Will return self if appropriate. Returns NULL if not reachable through neighbors. + Will return self if appropriate. Returns nullptr if not reachable through neighbors. */ cChunk * GetRelNeighborChunk(int a_RelX, int a_RelZ); @@ -218,7 +218,7 @@ public: Sends the chunk to all relevant clients. */ void SetAreaBiome(int a_MinRelX, int a_MaxRelX, int a_MinRelZ, int a_MaxRelZ, EMCSBiome a_Biome); - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); /** Sets the sign text. Returns true if successful. Also sends update packets to all clients in the chunk */ bool SetSignLines(int a_RelX, int a_RelY, int a_RelZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4); @@ -316,28 +316,28 @@ public: // Broadcast various packets to all clients of this chunk: // (Please keep these alpha-sorted) void BroadcastAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); - void BroadcastChunkData (cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL); - void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); - void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); + void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastChunkData (cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity (const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr); + void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); + void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ); void SendBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, cClientHandle & a_Client); diff --git a/src/ChunkData.cpp b/src/ChunkData.cpp index 03b0224a6..57b27c5e0 100644 --- a/src/ChunkData.cpp +++ b/src/ChunkData.cpp @@ -36,7 +36,7 @@ cChunkData::cChunkData(cAllocationPool<cChunkData::sChunkSection> & a_Pool) : { for (size_t i = 0; i < NumSections; i++) { - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -56,7 +56,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { Free(m_Sections[i]); - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -96,7 +96,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { Free(m_Sections[i]); - m_Sections[i] = NULL; + m_Sections[i] = nullptr; } } @@ -120,7 +120,7 @@ cChunkData::~cChunkData() for (size_t i = 0; i < NumSections; i++) { m_Sections[i] = other.m_Sections[i]; - other.m_Sections[i] = NULL; + other.m_Sections[i] = nullptr; } } @@ -137,7 +137,7 @@ cChunkData::~cChunkData() { Free(m_Sections[i]); m_Sections[i] = other.m_Sections[i]; - other.m_Sections[i] = NULL; + other.m_Sections[i] = nullptr; } } return *this; @@ -154,7 +154,7 @@ BLOCKTYPE cChunkData::GetBlock(int a_X, int a_Y, int a_Z) const ASSERT((a_Y >= 0) && (a_Y < cChunkDef::Height)); ASSERT((a_Z >= 0) && (a_Z < cChunkDef::Width)); int Section = a_Y / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_X, a_Y - (Section * SectionHeight), a_Z); return m_Sections[Section]->m_BlockTypes[Index]; @@ -182,14 +182,14 @@ void cChunkData::SetBlock(int a_RelX, int a_RelY, int a_RelZ, BLOCKTYPE a_Block) } int Section = a_RelY / SectionHeight; - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { if (a_Block == 0x00) { return; } m_Sections[Section] = Allocate(); - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { ASSERT(!"Failed to allocate a new section in Chunkbuffer"); return; @@ -212,7 +212,7 @@ NIBBLETYPE cChunkData::GetMeta(int a_RelX, int a_RelY, int a_RelZ) const (a_RelZ < cChunkDef::Width) && (a_RelZ > -1)) { int Section = a_RelY / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockMetas[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -243,14 +243,14 @@ bool cChunkData::SetMeta(int a_RelX, int a_RelY, int a_RelZ, NIBBLETYPE a_Nibble } int Section = a_RelY / SectionHeight; - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { if ((a_Nibble & 0xf) == 0x00) { return false; } m_Sections[Section] = Allocate(); - if (m_Sections[Section] == NULL) + if (m_Sections[Section] == nullptr) { ASSERT(!"Failed to allocate a new section in Chunkbuffer"); return false; @@ -279,7 +279,7 @@ NIBBLETYPE cChunkData::GetBlockLight(int a_RelX, int a_RelY, int a_RelZ) const ) { int Section = a_RelY / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -302,7 +302,7 @@ NIBBLETYPE cChunkData::GetSkyLight(int a_RelX, int a_RelY, int a_RelZ) const if ((a_RelX < cChunkDef::Width) && (a_RelX > -1) && (a_RelY < cChunkDef::Height) && (a_RelY > -1) && (a_RelZ < cChunkDef::Width) && (a_RelZ > -1)) { int Section = a_RelY / SectionHeight; - if (m_Sections[Section] != NULL) + if (m_Sections[Section] != nullptr) { int Index = cChunkDef::MakeIndexNoCheck(a_RelX, a_RelY - (Section * SectionHeight), a_RelZ); return (m_Sections[Section]->m_BlockSkyLight[Index / 2] >> ((Index & 1) * 4)) & 0x0f; @@ -325,7 +325,7 @@ cChunkData cChunkData::Copy(void) const cChunkData copy(m_Pool); for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { copy.m_Sections[i] = copy.Allocate(); *copy.m_Sections[i] = *m_Sections[i]; @@ -354,7 +354,7 @@ void cChunkData::CopyBlockTypes(BLOCKTYPE * a_Dest, size_t a_Idx, size_t a_Lengt { size_t ToCopy = std::min(+SectionBlockCount - StartPos, a_Length); a_Length -= ToCopy; - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { BLOCKTYPE * blockbuffer = m_Sections[i]->m_BlockTypes; memcpy(&a_Dest[(i * SectionBlockCount) + StartPos - a_Idx], blockbuffer + StartPos, sizeof(BLOCKTYPE) * ToCopy); @@ -375,7 +375,7 @@ void cChunkData::CopyMetas(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockMetas, sizeof(m_Sections[i]->m_BlockMetas)); } @@ -394,7 +394,7 @@ void cChunkData::CopyBlockLight(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockLight, sizeof(m_Sections[i]->m_BlockLight)); } @@ -413,7 +413,7 @@ void cChunkData::CopySkyLight(NIBBLETYPE * a_Dest) const { for (size_t i = 0; i < NumSections; i++) { - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(&a_Dest[i * SectionBlockCount / 2], &m_Sections[i]->m_BlockSkyLight, sizeof(m_Sections[i]->m_BlockSkyLight)); } @@ -430,12 +430,12 @@ void cChunkData::CopySkyLight(NIBBLETYPE * a_Dest) const void cChunkData::SetBlockTypes(const BLOCKTYPE * a_Src) { - ASSERT(a_Src != NULL); + ASSERT(a_Src != nullptr); for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockTypes, &a_Src[i * SectionBlockCount], sizeof(m_Sections[i]->m_BlockTypes)); continue; @@ -462,12 +462,12 @@ void cChunkData::SetBlockTypes(const BLOCKTYPE * a_Src) void cChunkData::SetMetas(const NIBBLETYPE * a_Src) { - ASSERT(a_Src != NULL); + ASSERT(a_Src != nullptr); for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockMetas, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockMetas)); continue; @@ -495,7 +495,7 @@ void cChunkData::SetMetas(const NIBBLETYPE * a_Src) void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) { - if (a_Src == NULL) + if (a_Src == nullptr) { return; } @@ -503,7 +503,7 @@ void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockLight, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockLight)); continue; @@ -530,7 +530,7 @@ void cChunkData::SetBlockLight(const NIBBLETYPE * a_Src) void cChunkData::SetSkyLight(const NIBBLETYPE * a_Src) { - if (a_Src == NULL) + if (a_Src == nullptr) { return; } @@ -538,7 +538,7 @@ void cChunkData::SetSkyLight(const NIBBLETYPE * a_Src) for (size_t i = 0; i < NumSections; i++) { // If the section is already allocated, copy the data into it: - if (m_Sections[i] != NULL) + if (m_Sections[i] != nullptr) { memcpy(m_Sections[i]->m_BlockSkyLight, &a_Src[i * SectionBlockCount / 2], sizeof(m_Sections[i]->m_BlockSkyLight)); continue; diff --git a/src/ChunkData.h b/src/ChunkData.h index fe8b068a2..2ab629b29 100644 --- a/src/ChunkData.h +++ b/src/ChunkData.h @@ -88,12 +88,12 @@ public: /** Copies the blocklight data from the specified flat array into the internal representation. Allocates sectios that are needed for the operation. - Allows a_Src to be NULL, in which case it doesn't do anything. */ + Allows a_Src to be nullptr, in which case it doesn't do anything. */ void SetBlockLight(const NIBBLETYPE * a_Src); /** Copies the skylight data from the specified flat array into the internal representation. Allocates sectios that are needed for the operation. - Allows a_Src to be NULL, in which case it doesn't do anything. */ + Allows a_Src to be nullptr, in which case it doesn't do anything. */ void SetSkyLight(const NIBBLETYPE * a_Src); struct sChunkSection @@ -118,7 +118,7 @@ private: sChunkSection * Allocate(void); /** Frees the specified section, previously allocated using Allocate(). - Note that a_Section may be NULL. */ + Note that a_Section may be nullptr. */ void Free(sChunkSection * a_Section); /** Sets the data in the specified section to their default values. */ diff --git a/src/ChunkDef.h b/src/ChunkDef.h index f4ed66c4b..260aace58 100644 --- a/src/ChunkDef.h +++ b/src/ChunkDef.h @@ -66,7 +66,7 @@ public: /// The type used for any heightmap operations and storage; idx = x + Width * z; Height points to the highest non-air block in the column typedef HEIGHTTYPE HeightMap[Width * Width]; - + /** The type used for any biomemap operations and storage inside MCServer, using MCServer biomes (need not correspond to client representation!) idx = x + Width * z // Need to verify this with the protocol spec, currently unknown! @@ -95,8 +95,8 @@ public: a_X = a_X - a_ChunkX * Width; a_Z = a_Z - a_ChunkZ * Width; } - - + + /// Converts absolute block coords to chunk coords: inline static void BlockToChunk(int a_X, int a_Z, int & a_ChunkX, int & a_ChunkZ) { @@ -165,15 +165,15 @@ public: ASSERT((a_Z >= 0) && (a_Z < Width)); a_BlockTypes[MakeIndexNoCheck(a_X, a_Y, a_Z)] = a_Type; } - - + + inline static void SetBlock(BLOCKTYPE * a_BlockTypes, int a_Index, BLOCKTYPE a_Type) { ASSERT((a_Index >= 0) && (a_Index <= NumBlocks)); a_BlockTypes[a_Index] = a_Type; } - - + + inline static BLOCKTYPE GetBlock(const BLOCKTYPE * a_BlockTypes, int a_X, int a_Y, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); @@ -181,39 +181,39 @@ public: ASSERT((a_Z >= 0) && (a_Z < Width)); return a_BlockTypes[MakeIndexNoCheck(a_X, a_Y, a_Z)]; } - - + + inline static BLOCKTYPE GetBlock(const BLOCKTYPE * a_BlockTypes, int a_Idx) { ASSERT((a_Idx >= 0) && (a_Idx < NumBlocks)); return a_BlockTypes[a_Idx]; } - - + + inline static int GetHeight(const HeightMap & a_HeightMap, int a_X, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); return a_HeightMap[a_X + Width * a_Z]; } - - + + inline static void SetHeight(HeightMap & a_HeightMap, int a_X, int a_Z, unsigned char a_Height) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); a_HeightMap[a_X + Width * a_Z] = a_Height; } - - + + inline static EMCSBiome GetBiome(const BiomeMap & a_BiomeMap, int a_X, int a_Z) { ASSERT((a_X >= 0) && (a_X < Width)); ASSERT((a_Z >= 0) && (a_Z < Width)); return a_BiomeMap[a_X + Width * a_Z]; } - - + + inline static void SetBiome(BiomeMap & a_BiomeMap, int a_X, int a_Z, EMCSBiome a_Biome) { ASSERT((a_X >= 0) && (a_X < Width)); @@ -226,11 +226,11 @@ public: { if ((a_BlockIdx > -1) && (a_BlockIdx < NumBlocks)) { - if ((size_t)(a_BlockIdx / 2) >= a_Buffer.size()) + if (static_cast<size_t>(a_BlockIdx / 2) >= a_Buffer.size()) { return (a_IsSkyLightNibble ? 0xff : 0); } - return (a_Buffer[(size_t)(a_BlockIdx / 2)] >> ((a_BlockIdx & 1) * 4)) & 0x0f; + return (a_Buffer[static_cast<size_t>(a_BlockIdx / 2)] >> ((a_BlockIdx & 1) * 4)) & 0x0f; } ASSERT(!"cChunkDef::GetNibble(): index out of chunk range!"); return 0; @@ -241,7 +241,7 @@ public: { if ((x < Width) && (x > -1) && (y < Height) && (y > -1) && (z < Width) && (z > -1)) { - size_t Index = (size_t)MakeIndexNoCheck(x, y, z); + size_t Index = static_cast<size_t>(MakeIndexNoCheck(x, y, z)); if ((Index / 2) >= a_Buffer.size()) { return (a_IsSkyLightNibble ? 0xff : 0); @@ -258,7 +258,7 @@ public: if ((x < Width) && (x > -1) && (y < Height) && (y > -1) && (z < Width) && (z > -1)) { int Index = MakeIndexNoCheck(x, y, z); - return (a_Buffer[(size_t)(Index / 2)] >> ((Index & 1) * 4)) & 0x0f; + return (a_Buffer[static_cast<size_t>(Index / 2)] >> ((Index & 1) * 4)) & 0x0f; } ASSERT(!"cChunkDef::GetNibble(): coords out of chunk range!"); return 0; @@ -272,11 +272,11 @@ public: ASSERT(!"cChunkDef::SetNibble(): index out of range!"); return; } - if ((size_t)(a_BlockIdx / 2) >= a_Buffer.size()) + if (static_cast<size_t>(a_BlockIdx / 2) >= a_Buffer.size()) { - a_Buffer.resize((size_t)((a_BlockIdx / 2) + 1)); + a_Buffer.resize(static_cast<size_t>((a_BlockIdx / 2) + 1)); } - a_Buffer[(size_t)(a_BlockIdx / 2)] = PackNibble(a_Buffer, (size_t)a_BlockIdx, a_Nibble); + a_Buffer[static_cast<size_t>(a_BlockIdx / 2)] = PackNibble(a_Buffer, static_cast<size_t>(a_BlockIdx), a_Nibble); } @@ -292,7 +292,7 @@ public: return; } - size_t Index = (size_t)MakeIndexNoCheck(x, y, z); + size_t Index = static_cast<size_t>(MakeIndexNoCheck(x, y, z)); if ((Index / 2) >= a_Buffer.size()) { a_Buffer.resize(((Index / 2) + 1)); @@ -336,7 +336,7 @@ public: /// Called for clients that are in Chunk1 and not in Chunk2, virtual void Removed(cClientHandle * a_Client) = 0; - + /// Called for clients that are in Chunk2 and not in Chunk1. virtual void Added(cClientHandle * a_Client) = 0; } ; @@ -373,9 +373,9 @@ class cChunkCoords public: int m_ChunkX; int m_ChunkZ; - + cChunkCoords(int a_ChunkX, int a_ChunkZ) : m_ChunkX(a_ChunkX), m_ChunkZ(a_ChunkZ) {} - + bool operator == (const cChunkCoords & a_Other) const { return ((m_ChunkX == a_Other.m_ChunkX) && (m_ChunkZ == a_Other.m_ChunkZ)); @@ -432,12 +432,12 @@ public: int y; int z; X Data; - + cCoordWithData(int a_X, int a_Y, int a_Z) : x(a_X), y(a_Y), z(a_Z), Data() { } - + cCoordWithData(int a_X, int a_Y, int a_Z, const X & a_Data) : x(a_X), y(a_Y), z(a_Z), Data(a_Data) { @@ -478,7 +478,3 @@ public: typedef cCoordWithDoubleData <BLOCKTYPE, bool> cCoordWithBlockAndBool; typedef std::vector<cCoordWithBlockAndBool> cCoordWithBlockAndBoolVector; - - - - diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 299fe0eca..8a8f17a1b 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -88,10 +88,10 @@ cChunkMap::cChunkLayer * cChunkMap::GetLayer(int a_LayerX, int a_LayerZ) // Not found, create new: cChunkLayer * Layer = new cChunkLayer(a_LayerX, a_LayerZ, this, *m_Pool); - if (Layer == NULL) + if (Layer == nullptr) { LOGERROR("cChunkMap: Cannot create new layer, server out of memory?"); - return NULL; + return nullptr; } m_Layers.push_back(Layer); return Layer; @@ -125,7 +125,7 @@ cChunkMap::cChunkLayer * cChunkMap::FindLayer(int a_LayerX, int a_LayerZ) } // for itr - m_Layers[] // Not found - return NULL; + return nullptr; } @@ -148,16 +148,16 @@ cChunkPtr cChunkMap::GetChunk(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } cChunkPtr Chunk = Layer->GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { - return NULL; + return nullptr; } if (!Chunk->IsValid() && !Chunk->IsQueued()) { @@ -177,16 +177,16 @@ cChunkPtr cChunkMap::GetChunkNoGen(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } cChunkPtr Chunk = Layer->GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { - return NULL; + return nullptr; } if (!Chunk->IsValid() && !Chunk->IsQueued()) { @@ -206,10 +206,10 @@ cChunkPtr cChunkMap::GetChunkNoLoad( int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); // m_CSLayers should already be locked by the operation that called us cChunkLayer * Layer = GetLayerForChunk( a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { // An error must have occurred, since layers are automatically created if they don't exist - return NULL; + return nullptr; } return Layer->GetChunk(a_ChunkX, a_ChunkZ); @@ -227,7 +227,7 @@ bool cChunkMap::LockedGetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -249,7 +249,7 @@ bool cChunkMap::LockedGetBlockType(int a_BlockX, int a_BlockY, int a_BlockZ, BLO int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -270,7 +270,7 @@ bool cChunkMap::LockedGetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIB int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -289,7 +289,7 @@ bool cChunkMap::LockedSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTY int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -308,7 +308,7 @@ bool cChunkMap::LockedFastSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLO int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -326,9 +326,9 @@ cChunk * cChunkMap::FindChunk(int a_ChunkX, int a_ChunkZ) ASSERT(m_CSLayers.IsLockedByCurrentThread()); cChunkLayer * Layer = FindLayerForChunk(a_ChunkX, a_ChunkZ); - if (Layer == NULL) + if (Layer == nullptr) { - return NULL; + return nullptr; } return Layer->FindChunk(a_ChunkX, a_ChunkZ); } @@ -341,7 +341,7 @@ void cChunkMap::BroadcastAttachEntity(const cEntity & a_Entity, const cEntity * { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -361,7 +361,7 @@ void cChunkMap::BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, c z = a_BlockZ; cChunkDef::BlockToChunk(x, z, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -380,7 +380,7 @@ void cChunkMap::BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a cChunkDef::BlockToChunk(a_blockX, a_blockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -398,7 +398,7 @@ void cChunkMap::BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, c int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -413,7 +413,7 @@ void cChunkMap::BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSeriali { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -429,7 +429,7 @@ void cChunkMap::BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -445,7 +445,7 @@ void cChunkMap::BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHa { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -461,7 +461,7 @@ void cChunkMap::BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -477,7 +477,7 @@ void cChunkMap::BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotN { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -493,7 +493,7 @@ void cChunkMap::BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -509,7 +509,7 @@ void cChunkMap::BroadcastEntityLook(const cEntity & a_Entity, const cClientHandl { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -525,7 +525,7 @@ void cChunkMap::BroadcastEntityMetadata(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -541,7 +541,7 @@ void cChunkMap::BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, ch { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -557,7 +557,7 @@ void cChunkMap::BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -573,7 +573,7 @@ void cChunkMap::BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, c { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -589,7 +589,7 @@ void cChunkMap::BroadcastEntityVelocity(const cEntity & a_Entity, const cClientH { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -605,7 +605,7 @@ void cChunkMap::BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animat { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -624,7 +624,7 @@ void cChunkMap::BroadcastParticleEffect(const AString & a_ParticleName, float a_ cChunkDef::BlockToChunk((int) a_SrcX, (int) a_SrcZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -641,7 +641,7 @@ void cChunkMap::BroadcastRemoveEntityEffect(const cEntity & a_Entity, int a_Effe cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -660,7 +660,7 @@ void cChunkMap::BroadcastSoundEffect(const AString & a_SoundName, double a_X, do cChunkDef::BlockToChunk((int)std::floor(a_X), (int)std::floor(a_Z), ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -679,7 +679,7 @@ void cChunkMap::BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_S cChunkDef::BlockToChunk(a_SrcX, a_SrcZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -695,7 +695,7 @@ void cChunkMap::BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity.GetChunkX(), a_Entity.GetChunkZ()); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -713,7 +713,7 @@ void cChunkMap::BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, c int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -732,7 +732,7 @@ void cChunkMap::BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_Bl cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -750,7 +750,7 @@ void cChunkMap::SendBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, cClien int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -768,7 +768,7 @@ void cChunkMap::UseBlockEntity(cPlayer * a_Player, int a_BlockX, int a_BlockY, i int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -783,7 +783,7 @@ bool cChunkMap::DoWithChunk(int a_ChunkX, int a_ChunkZ, cChunkCallback & a_Callb { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -800,7 +800,7 @@ void cChunkMap::WakeUpSimulators(int a_BlockX, int a_BlockY, int a_BlockZ) int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -822,6 +822,7 @@ void cChunkMap::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_M int MinChunkX, MinChunkZ, MaxChunkX, MaxChunkZ; cChunkDef::BlockToChunk(a_MinBlockX, a_MinBlockZ, MinChunkX, MinChunkZ); cChunkDef::BlockToChunk(a_MaxBlockX, a_MaxBlockZ, MaxChunkX, MaxChunkZ); + cCSLock Lock(m_CSLayers); for (int z = MinChunkZ; z <= MaxChunkZ; z++) { int MinZ = std::max(a_MinBlockZ, z * cChunkDef::Width); @@ -829,7 +830,7 @@ void cChunkMap::WakeUpSimulatorsInArea(int a_MinBlockX, int a_MaxBlockX, int a_M for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoGen(x, z); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -857,7 +858,7 @@ void cChunkMap::MarkRedstoneDirty(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -872,7 +873,7 @@ void cChunkMap::MarkChunkDirty(int a_ChunkX, int a_ChunkZ, bool a_MarkRedstoneDi { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -891,7 +892,7 @@ void cChunkMap::MarkChunkSaving(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -906,7 +907,7 @@ void cChunkMap::MarkChunkSaved (int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -924,7 +925,7 @@ void cChunkMap::SetChunkData(cSetChunkData & a_SetChunkData) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -954,7 +955,7 @@ void cChunkMap::SetChunkData(cSetChunkData & a_SetChunkData) } // Notify plugins of the chunk becoming available - cPluginManager::Get()->CallHookChunkAvailable(m_World, ChunkX, ChunkZ); + cPluginManager::Get()->CallHookChunkAvailable(*m_World, ChunkX, ChunkZ); } @@ -969,7 +970,7 @@ void cChunkMap::ChunkLighted( { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -985,7 +986,7 @@ bool cChunkMap::GetChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataCallback & a_ { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1001,7 +1002,7 @@ bool cChunkMap::GetChunkBlockTypes(int a_ChunkX, int a_ChunkZ, BLOCKTYPE * a_Blo { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1017,7 +1018,7 @@ bool cChunkMap::IsChunkQueued(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->IsQueued(); + return (Chunk != nullptr) && Chunk->IsQueued(); } @@ -1028,7 +1029,7 @@ bool cChunkMap::IsChunkValid(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->IsValid(); + return (Chunk != nullptr) && Chunk->IsValid(); } @@ -1039,7 +1040,7 @@ bool cChunkMap::HasChunkAnyClients(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - return (Chunk != NULL) && Chunk->HasAnyClients(); + return (Chunk != nullptr) && Chunk->HasAnyClients(); } @@ -1054,7 +1055,7 @@ int cChunkMap::GetHeight(int a_BlockX, int a_BlockZ) int ChunkX, ChunkZ, BlockY = 0; cChunkDef::AbsoluteToRelative(a_BlockX, BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return 0; } @@ -1081,7 +1082,7 @@ bool cChunkMap::TryGetHeight(int a_BlockX, int a_BlockZ, int & a_Height) int ChunkX, ChunkZ, BlockY = 0; cChunkDef::AbsoluteToRelative(a_BlockX, BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1104,7 +1105,7 @@ void cChunkMap::FastSetBlocks(sSetBlockList & a_BlockList) int ChunkZ = a_BlockList.front().ChunkZ; cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { for (sSetBlockList::iterator itr = a_BlockList.begin(); itr != a_BlockList.end();) { @@ -1145,11 +1146,11 @@ void cChunkMap::FastSetBlocks(sSetBlockList & a_BlockList) -void cChunkMap::CollectPickupsByPlayer(cPlayer * a_Player) +void cChunkMap::CollectPickupsByPlayer(cPlayer & a_Player) { - int BlockX = (int)(a_Player->GetPosX()); // Truncating doesn't matter much; we're scanning entire chunks anyway - int BlockY = (int)(a_Player->GetPosY()); - int BlockZ = (int)(a_Player->GetPosZ()); + int BlockX = (int)(a_Player.GetPosX()); // Truncating doesn't matter much; we're scanning entire chunks anyway + int BlockY = (int)(a_Player.GetPosY()); + int BlockZ = (int)(a_Player.GetPosZ()); int ChunkX = 0, ChunkZ = 0; cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); int OtherChunkX = ChunkX + ((BlockX > 8) ? 1 : -1); @@ -1193,7 +1194,7 @@ BLOCKTYPE cChunkMap::GetBlock(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBlock(a_BlockX, a_BlockY, a_BlockZ); } @@ -1222,7 +1223,7 @@ NIBBLETYPE cChunkMap::GetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetMeta(a_BlockX, a_BlockY, a_BlockZ); } @@ -1240,7 +1241,7 @@ NIBBLETYPE cChunkMap::GetBlockSkyLight(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetSkyLight(a_BlockX, a_BlockY, a_BlockZ); } @@ -1258,7 +1259,7 @@ NIBBLETYPE cChunkMap::GetBlockBlockLight(int a_BlockX, int a_BlockY, int a_Block cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBlockLight(a_BlockX, a_BlockY, a_BlockZ); } @@ -1277,7 +1278,7 @@ void cChunkMap::SetBlockMeta(int a_BlockX, int a_BlockY, int a_BlockZ, NIBBLETYP cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetMeta(a_BlockX, a_BlockY, a_BlockZ, a_BlockMeta); } @@ -1300,7 +1301,7 @@ void cChunkMap::SetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_B cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetBlock(X, Y, Z, a_BlockType, a_BlockMeta, a_SendToClients); m_World->GetSimulatorManager()->WakeUp(a_BlockX, a_BlockY, a_BlockZ, Chunk); @@ -1319,7 +1320,7 @@ void cChunkMap::QueueSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYP cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->QueueSetBlock(X, Y, Z, a_BlockType, a_BlockMeta, a_Tick, a_PreviousBlockType); } @@ -1336,7 +1337,7 @@ bool cChunkMap::GetBlockTypeMeta(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCK cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->GetBlockTypeMeta(X, Y, Z, a_BlockType, a_BlockMeta); return true; @@ -1355,7 +1356,7 @@ bool cChunkMap::GetBlockInfo(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk( ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->GetBlockInfo(X, Y, Z, a_BlockType, a_Meta, a_SkyLight, a_BlockLight); return true; @@ -1373,7 +1374,7 @@ void cChunkMap::ReplaceBlocks(const sSetBlockVector & a_Blocks, BLOCKTYPE a_Filt for (sSetBlockVector::const_iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1394,7 +1395,7 @@ void cChunkMap::ReplaceTreeBlocks(const sSetBlockVector & a_Blocks) for (sSetBlockVector::const_iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1429,7 +1430,7 @@ EMCSBiome cChunkMap::GetBiomeAt (int a_BlockX, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { return Chunk->GetBiomeAt(X, Z); } @@ -1450,7 +1451,7 @@ bool cChunkMap::SetBiomeAt(int a_BlockX, int a_BlockZ, EMCSBiome a_Biome) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetBiomeAt(X, Z, a_Biome); return true; @@ -1483,7 +1484,7 @@ bool cChunkMap::SetAreaBiome(int a_MinX, int a_MaxX, int a_MinZ, int a_MaxZ, EMC int MinRelZ = (z == MinChunkZ) ? MinZ : 0; int MaxRelZ = (z == MaxChunkZ) ? MaxZ : cChunkDef::Width - 1; cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk != NULL) && Chunk->IsValid()) + if ((Chunk != nullptr) && Chunk->IsValid()) { Chunk->SetAreaBiome(MinRelX, MaxRelX, MinRelZ, MaxRelZ, a_Biome); } @@ -1507,7 +1508,7 @@ bool cChunkMap::GetBlocks(sSetBlockVector & a_Blocks, bool a_ContinueOnFailure) for (sSetBlockVector::iterator itr = a_Blocks.begin(); itr != a_Blocks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->ChunkX, itr->ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { if (!a_ContinueOnFailure) { @@ -1535,7 +1536,7 @@ bool cChunkMap::DigBlock(int a_X, int a_Y, int a_Z) { cCSLock Lock(m_CSLayers); cChunkPtr DestChunk = GetChunk( ChunkX, ChunkZ); - if ((DestChunk == NULL) || !DestChunk->IsValid()) + if ((DestChunk == nullptr) || !DestChunk->IsValid()) { return false; } @@ -1558,7 +1559,7 @@ void cChunkMap::SendBlockTo(int a_X, int a_Y, int a_Z, cPlayer * a_Player) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(ChunkX, ChunkZ); - if ((Chunk != NULL) && (Chunk->IsValid())) + if ((Chunk != nullptr) && (Chunk->IsValid())) { Chunk->SendBlockTo(a_X, a_Y, a_Z, a_Player->GetClientHandle()); } @@ -1572,12 +1573,12 @@ void cChunkMap::CompareChunkClients(int a_ChunkX1, int a_ChunkZ1, int a_ChunkX2, { cCSLock Lock(m_CSLayers); cChunkPtr Chunk1 = GetChunkNoGen(a_ChunkX1, a_ChunkZ1); - if (Chunk1 == NULL) + if (Chunk1 == nullptr) { return; } cChunkPtr Chunk2 = GetChunkNoGen(a_ChunkX2, a_ChunkZ2); - if (Chunk2 == NULL) + if (Chunk2 == nullptr) { return; } @@ -1639,7 +1640,7 @@ bool cChunkMap::AddChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Cli { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunk(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return false; } @@ -1654,7 +1655,7 @@ void cChunkMap::RemoveChunkClient(int a_ChunkX, int a_ChunkZ, cClientHandle * a_ { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -1684,7 +1685,7 @@ void cChunkMap::AddEntity(cEntity * a_Entity) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); if ( - (Chunk == NULL) || // Chunk not present at all + (Chunk == nullptr) || // Chunk not present at all (!Chunk->IsValid() && !a_Entity->IsPlayer()) // Chunk present, but no valid data; players need to spawn in such chunks (#953) ) { @@ -1705,7 +1706,7 @@ void cChunkMap::AddEntityIfNotPresent(cEntity * a_Entity) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); if ( - (Chunk == NULL) || // Chunk not present at all + (Chunk == nullptr) || // Chunk not present at all (!Chunk->IsValid() && !a_Entity->IsPlayer()) // Chunk present, but no valid data; players need to spawn in such chunks (#953) ) { @@ -1747,7 +1748,7 @@ void cChunkMap::RemoveEntity(cEntity * a_Entity) cChunkPtr Chunk = GetChunkNoGen(a_Entity->GetChunkX(), a_Entity->GetChunkZ()); // Even if a chunk is not valid, it may still contain entities such as players; make sure to remove them (#1190) - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -1779,7 +1780,7 @@ bool cChunkMap::ForEachEntityInChunk(int a_ChunkX, int a_ChunkZ, cEntityCallback { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -1805,7 +1806,7 @@ bool cChunkMap::ForEachEntityInBox(const cBoundingBox & a_Box, cEntityCallback & for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoGen(x, z); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { continue; } @@ -1980,7 +1981,7 @@ void cChunkMap::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_ } // Ensure that the damage dealt is inversely proportional to the distance to the TNT centre - the closer a player is, the harder they are hit - a_Entity->TakeDamage(dtExplosion, NULL, (int)((1 / DistanceFromExplosion.Length()) * 6 * m_ExplosionSize), 0); + a_Entity->TakeDamage(dtExplosion, nullptr, (int)((1 / DistanceFromExplosion.Length()) * 6 * m_ExplosionSize), 0); } // Apply force to entities around the explosion - code modified from World.cpp DoExplosionAt() @@ -2038,7 +2039,7 @@ bool cChunkMap::ForEachBlockEntityInChunk(int a_ChunkX, int a_ChunkZ, cBlockEnti { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2053,7 +2054,7 @@ bool cChunkMap::ForEachChestInChunk(int a_ChunkX, int a_ChunkZ, cChestCallback & { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2068,7 +2069,7 @@ bool cChunkMap::ForEachDispenserInChunk(int a_ChunkX, int a_ChunkZ, cDispenserCa { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2083,7 +2084,7 @@ bool cChunkMap::ForEachDropperInChunk(int a_ChunkX, int a_ChunkZ, cDropperCallba { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2098,7 +2099,7 @@ bool cChunkMap::ForEachDropSpenserInChunk(int a_ChunkX, int a_ChunkZ, cDropSpens { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2113,7 +2114,7 @@ bool cChunkMap::ForEachFurnaceInChunk(int a_ChunkX, int a_ChunkZ, cFurnaceCallba { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(a_ChunkX, a_ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2131,7 +2132,7 @@ bool cChunkMap::DoWithBlockEntityAt(int a_BlockX, int a_BlockY, int a_BlockZ, cB cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2149,7 +2150,7 @@ bool cChunkMap::DoWithBeaconAt(int a_BlockX, int a_BlockY, int a_BlockZ, cBeacon cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2167,7 +2168,7 @@ bool cChunkMap::DoWithChestAt(int a_BlockX, int a_BlockY, int a_BlockZ, cChestCa cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2185,7 +2186,7 @@ bool cChunkMap::DoWithDispenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDis cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2203,7 +2204,7 @@ bool cChunkMap::DoWithDropperAt(int a_BlockX, int a_BlockY, int a_BlockZ, cDropp cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2221,7 +2222,7 @@ bool cChunkMap::DoWithDropSpenserAt(int a_BlockX, int a_BlockY, int a_BlockZ, cD cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2239,7 +2240,7 @@ bool cChunkMap::DoWithFurnaceAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFurna cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2256,7 +2257,7 @@ bool cChunkMap::DoWithNoteBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, cNot cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2273,7 +2274,7 @@ bool cChunkMap::DoWithCommandBlockAt(int a_BlockX, int a_BlockY, int a_BlockZ, c cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2291,7 +2292,7 @@ bool cChunkMap::DoWithMobHeadAt(int a_BlockX, int a_BlockY, int a_BlockZ, cMobHe cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2309,7 +2310,7 @@ bool cChunkMap::DoWithFlowerPotAt(int a_BlockX, int a_BlockY, int a_BlockZ, cFlo cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2327,7 +2328,7 @@ bool cChunkMap::GetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, AString & cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2352,7 +2353,7 @@ void cChunkMap::ChunkLoadFailed(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { return; } @@ -2369,7 +2370,7 @@ bool cChunkMap::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const ASt int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoGen(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return false; } @@ -2384,7 +2385,7 @@ void cChunkMap::MarkChunkRegenerating(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Not present return; @@ -2400,7 +2401,7 @@ bool cChunkMap::IsChunkLighted(int a_ChunkX, int a_ChunkZ) { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Not present return false; @@ -2421,7 +2422,7 @@ bool cChunkMap::ForEachChunkInRect(int a_MinChunkX, int a_MaxChunkX, int a_MinCh for (int x = a_MinChunkX; x <= a_MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk == NULL) || (!Chunk->IsValid())) + if ((Chunk == nullptr) || (!Chunk->IsValid())) { // Not present / not valid Result = false; @@ -2463,7 +2464,7 @@ bool cChunkMap::WriteBlockArea(cBlockArea & a_Area, int a_MinBlockX, int a_MinBl for (int x = MinChunkX; x <= MaxChunkX; x++) { cChunkPtr Chunk = GetChunkNoLoad(x, z); - if ((Chunk == NULL) || (!Chunk->IsValid())) + if ((Chunk == nullptr) || (!Chunk->IsValid())) { // Not present / not valid Result = false; @@ -2504,7 +2505,7 @@ void cChunkMap::GrowMelonPumpkin(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCK cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowMelonPumpkin(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_Rand); } @@ -2521,7 +2522,7 @@ void cChunkMap::GrowSugarcane(int a_BlockX, int a_BlockY, int a_BlockZ, int a_Nu cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowSugarcane(a_BlockX, a_BlockY, a_BlockZ, a_NumBlocksToGrow); } @@ -2538,7 +2539,7 @@ void cChunkMap::GrowCactus(int a_BlockX, int a_BlockY, int a_BlockZ, int a_NumBl cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->GrowCactus(a_BlockX, a_BlockY, a_BlockZ, a_NumBlocksToGrow); } @@ -2555,7 +2556,7 @@ void cChunkMap::SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->SetNextBlockTick(a_BlockX, a_BlockY, a_BlockZ); } @@ -2610,7 +2611,7 @@ void cChunkMap::TickBlock(int a_BlockX, int a_BlockY, int a_BlockZ) int ChunkX, ChunkZ; cChunkDef::AbsoluteToRelative(a_BlockX, a_BlockY, a_BlockZ, ChunkX, ChunkZ); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if ((Chunk == NULL) || !Chunk->IsValid()) + if ((Chunk == nullptr) || !Chunk->IsValid()) { return; } @@ -2679,7 +2680,7 @@ void cChunkMap::QueueTickBlock(int a_BlockX, int a_BlockY, int a_BlockZ) cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(ChunkX, ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->QueueTickBlock(a_BlockX, a_BlockY, a_BlockZ); } @@ -2693,7 +2694,7 @@ void cChunkMap::SetChunkAlwaysTicked(int a_ChunkX, int a_ChunkZ, bool a_AlwaysTi { cCSLock Lock(m_CSLayers); cChunkPtr Chunk = GetChunkNoLoad(a_ChunkX, a_ChunkZ); - if (Chunk != NULL) + if (Chunk != nullptr) { Chunk->SetAlwaysTicked(a_AlwaysTicked); } @@ -2729,7 +2730,7 @@ cChunkMap::cChunkLayer::~cChunkLayer() for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { delete m_Chunks[i]; - m_Chunks[i] = NULL; // Must zero out, because further chunk deletions query the chunkmap for entities and that would touch deleted data + m_Chunks[i] = nullptr; // Must zero out, because further chunk deletions query the chunkmap for entities and that would touch deleted data } // for i - m_Chunks[] } @@ -2747,11 +2748,11 @@ cChunkPtr cChunkMap::cChunkLayer::GetChunk( int a_ChunkX, int a_ChunkZ) if (!((LocalX < LAYER_SIZE) && (LocalZ < LAYER_SIZE) && (LocalX > -1) && (LocalZ > -1))) { ASSERT(!"Asking a cChunkLayer for a chunk that doesn't belong to it!"); - return NULL; + return nullptr; } int Index = LocalX + LocalZ * LAYER_SIZE; - if (m_Chunks[Index] == NULL) + if (m_Chunks[Index] == nullptr) { cChunk * neixm = (LocalX > 0) ? m_Chunks[Index - 1] : m_Parent->FindChunk(a_ChunkX - 1, a_ChunkZ); cChunk * neixp = (LocalX < LAYER_SIZE - 1) ? m_Chunks[Index + 1] : m_Parent->FindChunk(a_ChunkX + 1, a_ChunkZ); @@ -2774,7 +2775,7 @@ cChunk * cChunkMap::cChunkLayer::FindChunk(int a_ChunkX, int a_ChunkZ) if (!((LocalX < LAYER_SIZE) && (LocalZ < LAYER_SIZE) && (LocalX > -1) && (LocalZ > -1))) { ASSERT(!"Asking a cChunkLayer for a chunk that doesn't belong to it!"); - return NULL; + return nullptr; } int Index = LocalX + LocalZ * LAYER_SIZE; @@ -2791,7 +2792,7 @@ void cChunkMap::cChunkLayer::CollectMobCensus(cMobCensus& a_ToFill) // We do count every Mobs in the world. But we are assuming that every chunk not loaded by any client // doesn't affect us. Normally they should not have mobs because every "too far" mobs despawn // If they have (f.i. when player disconnect) we assume we don't have to make them live or despawn - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) { m_Chunks[i]->CollectMobCensus(a_ToFill); } @@ -2808,7 +2809,7 @@ void cChunkMap::cChunkLayer::SpawnMobs(cMobSpawner& a_MobSpawner) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { // We only spawn close to players - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->HasAnyClients()) { m_Chunks[i]->SpawnMobs(a_MobSpawner); } @@ -2824,7 +2825,7 @@ void cChunkMap::cChunkLayer::Tick(float a_Dt) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { // Only tick chunks that are valid and should be ticked: - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->ShouldBeTicked()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->ShouldBeTicked()) { m_Chunks[i]->Tick(a_Dt); } @@ -2839,7 +2840,7 @@ void cChunkMap::cChunkLayer::RemoveClient(cClientHandle * a_Client) { for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if (m_Chunks[i] != NULL) + if (m_Chunks[i] != nullptr) { m_Chunks[i]->RemoveClient(a_Client); } @@ -2855,7 +2856,7 @@ bool cChunkMap::cChunkLayer::ForEachEntity(cEntityCallback & a_Callback) // Calls the callback for each entity in the entire world; returns true if all entities processed, false if the callback aborted by returning true for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (!m_Chunks[i]->ForEachEntity(a_Callback)) { @@ -2875,7 +2876,7 @@ bool cChunkMap::cChunkLayer::DoWithEntityByID(int a_EntityID, cEntityCallback & // Calls the callback if the entity with the specified ID is found, with the entity object as the callback param. Returns true if entity found. for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (m_Chunks[i]->DoWithEntityByID(a_EntityID, a_Callback, a_CallbackReturn)) { @@ -2894,7 +2895,7 @@ bool cChunkMap::cChunkLayer::HasEntity(int a_EntityID) { for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid()) { if (m_Chunks[i]->HasEntity(a_EntityID)) { @@ -2914,7 +2915,7 @@ int cChunkMap::cChunkLayer::GetNumChunksLoaded(void) const int NumChunks = 0; for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if (m_Chunks[i] != NULL) + if (m_Chunks[i] != nullptr) { NumChunks++; } @@ -2932,7 +2933,7 @@ void cChunkMap::cChunkLayer::GetChunkStats(int & a_NumChunksValid, int & a_NumCh int NumDirty = 0; for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if (m_Chunks[i] == NULL) + if (m_Chunks[i] == nullptr) { continue; } @@ -2955,7 +2956,7 @@ void cChunkMap::cChunkLayer::Save(void) cWorld * World = m_Parent->GetWorld(); for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); ++i) { - if ((m_Chunks[i] != NULL) && m_Chunks[i]->IsValid() && m_Chunks[i]->IsDirty()) + if ((m_Chunks[i] != nullptr) && m_Chunks[i]->IsValid() && m_Chunks[i]->IsDirty()) { World->GetStorage().QueueSaveChunk(m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()); } @@ -2971,22 +2972,24 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) for (size_t i = 0; i < ARRAYCOUNT(m_Chunks); i++) { if ( - (m_Chunks[i] != NULL) && // Is valid + (m_Chunks[i] != nullptr) && // Is valid (m_Chunks[i]->CanUnload()) && // Can unload - !cPluginManager::Get()->CallHookChunkUnloading(m_Parent->GetWorld(), m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()) // Plugins agree + !cPluginManager::Get()->CallHookChunkUnloading(*(m_Parent->GetWorld()), m_Chunks[i]->GetPosX(), m_Chunks[i]->GetPosZ()) // Plugins agree ) { // The cChunk destructor calls our GetChunk() while removing its entities // so we still need to be able to return the chunk. Therefore we first delete, then NULLify // Doing otherwise results in bug http://forum.mc-server.org/showthread.php?tid=355 delete m_Chunks[i]; - m_Chunks[i] = NULL; + m_Chunks[i] = nullptr; } } // for i - m_Chunks[] } + + void cChunkMap::FastSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { cCSLock Lock(m_CSFastSetBlock); @@ -3031,7 +3034,7 @@ void cChunkMap::AddChunkStay(cChunkStay & a_ChunkStay) for (cChunkCoordsVector::const_iterator itr = WantedChunks.begin(); itr != WantedChunks.end(); ++itr) { cChunkPtr Chunk = GetChunk(itr->m_ChunkX, itr->m_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { continue; } @@ -3080,7 +3083,7 @@ void cChunkMap::DelChunkStay(cChunkStay & a_ChunkStay) for (cChunkCoordsVector::const_iterator itr = Chunks.begin(), end = Chunks.end(); itr != end; ++itr) { cChunkPtr Chunk = GetChunkNoLoad(itr->m_ChunkX, itr->m_ChunkZ); - if (Chunk == NULL) + if (Chunk == nullptr) { continue; } diff --git a/src/ChunkMap.h b/src/ChunkMap.h index 6e92833f1..51be5cb3d 100644 --- a/src/ChunkMap.h +++ b/src/ChunkMap.h @@ -70,29 +70,29 @@ public: // Broadcast respective packets to all clients of the chunk where the event is taking place // (Please keep these alpha-sorted) void BroadcastAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a_blockY, int a_blockZ, char a_stage, const cClientHandle * a_Exclude = NULL); + void BroadcastBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockBreakAnimation(int a_entityID, int a_blockX, int a_blockY, int a_blockZ, char a_stage, const cClientHandle * a_Exclude = nullptr); void BroadcastBlockEntity(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude); - void BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectPickup(const cPickup & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity(const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL); - void BroadcastParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); - void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); - void BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); + void BroadcastChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectPickup(const cPickup & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus(const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity(const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityAnimation(const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr); + void BroadcastParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); + void BroadcastSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); + void BroadcastSpawnEntity(cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); void BroadcastUseBed(const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ); /** Sends the block entity, if it is at the coords specified, to a_Client */ @@ -144,7 +144,7 @@ public: void FastSetQueuedBlocks(); void FastSetBlocks (sSetBlockList & a_BlockList); - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); BLOCKTYPE GetBlock (int a_BlockX, int a_BlockY, int a_BlockZ); NIBBLETYPE GetBlockMeta (int a_BlockX, int a_BlockY, int a_BlockZ); @@ -368,7 +368,7 @@ private: /** Always returns an assigned chunkptr, but the chunk needn't be valid (loaded / generated) - callers must check */ cChunkPtr GetChunk( int a_ChunkX, int a_ChunkZ); - /** Returns the specified chunk, or NULL if not created yet */ + /** Returns the specified chunk, or nullptr if not created yet */ cChunk * FindChunk(int a_ChunkX, int a_ChunkZ); int GetX(void) const {return m_LayerX; } @@ -431,10 +431,10 @@ private: typedef std::list<cChunkStay *> cChunkStays; - /** Finds the cChunkLayer object responsible for the specified chunk; returns NULL if not found. Assumes m_CSLayers is locked. */ + /** Finds the cChunkLayer object responsible for the specified chunk; returns nullptr if not found. Assumes m_CSLayers is locked. */ cChunkLayer * FindLayerForChunk(int a_ChunkX, int a_ChunkZ); - /** Returns the specified cChunkLayer object; returns NULL if not found. Assumes m_CSLayers is locked. */ + /** Returns the specified cChunkLayer object; returns nullptr if not found. Assumes m_CSLayers is locked. */ cChunkLayer * FindLayer(int a_LayerX, int a_LayerZ); /** Returns the cChunkLayer object responsible for the specified chunk; creates it if not found. */ diff --git a/src/ChunkSender.cpp b/src/ChunkSender.cpp index a3151eb3f..83d82884e 100644 --- a/src/ChunkSender.cpp +++ b/src/ChunkSender.cpp @@ -35,9 +35,9 @@ void cNotifyChunkSender::Call(int a_ChunkX, int a_ChunkZ) cChunkSender::cChunkSender(void) : super("ChunkSender"), - m_World(NULL), + m_World(nullptr), m_RemoveCount(0), - m_Notify(NULL) + m_Notify(nullptr) { m_Notify.SetChunkSender(this); } @@ -91,17 +91,45 @@ void cChunkSender::ChunkReady(int a_ChunkX, int a_ChunkZ) -void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cChunkSender::QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client) { - ASSERT(a_Client != NULL); + ASSERT(a_Client != nullptr); { + sSendChunk Chunk(a_ChunkX, a_ChunkZ, a_Client); + cCSLock Lock(m_CS); - if (std::find(m_SendChunks.begin(), m_SendChunks.end(), sSendChunk(a_ChunkX, a_ChunkZ, a_Client)) != m_SendChunks.end()) + if ( + std::find(m_SendChunksLowPriority.begin(), m_SendChunksLowPriority.end(), Chunk) != m_SendChunksLowPriority.end() || + std::find(m_SendChunksMediumPriority.begin(), m_SendChunksMediumPriority.end(), Chunk) != m_SendChunksMediumPriority.end() || + std::find(m_SendChunksHighPriority.begin(), m_SendChunksHighPriority.end(), Chunk) != m_SendChunksHighPriority.end() + ) { // Already queued, bail out return; } - m_SendChunks.push_back(sSendChunk(a_ChunkX, a_ChunkZ, a_Client)); + + switch (a_Priority) + { + case E_CHUNK_PRIORITY_LOW: + { + m_SendChunksLowPriority.push_back(Chunk); + break; + } + case E_CHUNK_PRIORITY_MEDIUM: + { + m_SendChunksMediumPriority.push_back(Chunk); + break; + } + case E_CHUNK_PRIORITY_HIGH: + { + m_SendChunksHighPriority.push_back(Chunk); + break; + } + default: + { + ASSERT(!"Unknown chunk priority!"); + } + } } m_evtQueue.Set(); } @@ -114,15 +142,33 @@ void cChunkSender::RemoveClient(cClientHandle * a_Client) { { cCSLock Lock(m_CS); - for (sSendChunkList::iterator itr = m_SendChunks.begin(); itr != m_SendChunks.end();) + for (sSendChunkList::iterator itr = m_SendChunksLowPriority.begin(); itr != m_SendChunksLowPriority.end();) { if (itr->m_Client == a_Client) { - itr = m_SendChunks.erase(itr); + itr = m_SendChunksLowPriority.erase(itr); continue; } ++itr; - } // for itr - m_SendChunks[] + } // for itr - m_SendChunksLowPriority[] + for (sSendChunkList::iterator itr = m_SendChunksMediumPriority.begin(); itr != m_SendChunksMediumPriority.end();) + { + if (itr->m_Client == a_Client) + { + itr = m_SendChunksMediumPriority.erase(itr); + continue; + } + ++itr; + } // for itr - m_SendChunksMediumPriority[] + for (sSendChunkList::iterator itr = m_SendChunksHighPriority.begin(); itr != m_SendChunksHighPriority.end();) + { + if (itr->m_Client == a_Client) + { + itr = m_SendChunksHighPriority.erase(itr); + continue; + } + ++itr; + } // for itr - m_SendChunksHighPriority[] m_RemoveCount++; } m_evtQueue.Set(); @@ -138,7 +184,7 @@ void cChunkSender::Execute(void) while (!m_ShouldTerminate) { cCSLock Lock(m_CS); - while (m_ChunksReady.empty() && m_SendChunks.empty()) + while (m_ChunksReady.empty() && m_SendChunksLowPriority.empty() && m_SendChunksMediumPriority.empty() && m_SendChunksHighPriority.empty()) { int RemoveCount = m_RemoveCount; m_RemoveCount = 0; @@ -153,23 +199,41 @@ void cChunkSender::Execute(void) return; } } // while (empty) - - if (!m_ChunksReady.empty()) + + if (!m_SendChunksHighPriority.empty()) + { + // Take one from the queue: + sSendChunk Chunk(m_SendChunksHighPriority.front()); + m_SendChunksHighPriority.pop_front(); + Lock.Unlock(); + + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); + } + else if (!m_ChunksReady.empty()) { // Take one from the queue: cChunkCoords Coords(m_ChunksReady.front()); m_ChunksReady.pop_front(); Lock.Unlock(); - SendChunk(Coords.m_ChunkX, Coords.m_ChunkZ, NULL); + SendChunk(Coords.m_ChunkX, Coords.m_ChunkZ, nullptr); + } + else if (!m_SendChunksMediumPriority.empty()) + { + // Take one from the queue: + sSendChunk Chunk(m_SendChunksMediumPriority.front()); + m_SendChunksMediumPriority.pop_front(); + Lock.Unlock(); + + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); } else { // Take one from the queue: - sSendChunk Chunk(m_SendChunks.front()); - m_SendChunks.pop_front(); + sSendChunk Chunk(m_SendChunksLowPriority.front()); + m_SendChunksLowPriority.pop_front(); Lock.Unlock(); - + SendChunk(Chunk.m_ChunkX, Chunk.m_ChunkZ, Chunk.m_Client); } Lock.Lock(); @@ -189,45 +253,42 @@ void cChunkSender::Execute(void) void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); // Ask the client if it still wants the chunk: - if (a_Client != NULL) + if ((a_Client != nullptr) && !a_Client->WantsSendChunk(a_ChunkX, a_ChunkZ)) { - if (!a_Client->WantsSendChunk(a_ChunkX, a_ChunkZ)) - { - return; - } + return; } - + // If the chunk has no clients, no need to packetize it: if (!m_World->HasChunkAnyClients(a_ChunkX, a_ChunkZ)) { return; } - + // If the chunk is not valid, do nothing - whoever needs it has queued it for loading / generating if (!m_World->IsChunkValid(a_ChunkX, a_ChunkZ)) { return; } - + // If the chunk is not lighted, queue it for relighting and get notified when it's ready: if (!m_World->IsChunkLighted(a_ChunkX, a_ChunkZ)) { m_World->QueueLightChunk(a_ChunkX, a_ChunkZ, &m_Notify); return; } - + // Query and prepare chunk data: if (!m_World->GetChunkData(a_ChunkX, a_ChunkZ, *this)) { return; } cChunkDataSerializer Data(m_BlockTypes, m_BlockMetas, m_BlockLight, m_BlockSkyLight, m_BiomeMap); - + // Send: - if (a_Client == NULL) + if (a_Client == nullptr) { m_World->BroadcastChunkData(a_ChunkX, a_ChunkZ, Data); } @@ -235,11 +296,11 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien { a_Client->SendChunkData(a_ChunkX, a_ChunkZ, Data); } - + // Send block-entity packets: for (sBlockCoords::iterator itr = m_BlockEntities.begin(); itr != m_BlockEntities.end(); ++itr) { - if (a_Client == NULL) + if (a_Client == nullptr) { m_World->BroadcastBlockEntity(itr->m_BlockX, itr->m_BlockY, itr->m_BlockZ); } @@ -249,7 +310,7 @@ void cChunkSender::SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Clien } } // for itr - m_Packets[] m_BlockEntities.clear(); - + // TODO: Send entity spawn packets } diff --git a/src/ChunkSender.h b/src/ChunkSender.h index a0e9087a9..7cd7ddd86 100644 --- a/src/ChunkSender.h +++ b/src/ChunkSender.h @@ -75,6 +75,13 @@ class cChunkSender: public: cChunkSender(void); ~cChunkSender(); + + enum eChunkPriority + { + E_CHUNK_PRIORITY_HIGH = 0, + E_CHUNK_PRIORITY_MEDIUM = 1, + E_CHUNK_PRIORITY_LOW = 2, + }; bool Start(cWorld * a_World); @@ -84,7 +91,7 @@ public: void ChunkReady(int a_ChunkX, int a_ChunkZ); /// Queues a chunk to be sent to a specific client - void QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); + void QueueSendChunkTo(int a_ChunkX, int a_ChunkZ, eChunkPriority a_Priority, cClientHandle * a_Client); /// Removes the a_Client from all waiting chunk send operations void RemoveClient(cClientHandle * a_Client); @@ -136,7 +143,9 @@ protected: cCriticalSection m_CS; cChunkCoordsList m_ChunksReady; - sSendChunkList m_SendChunks; + sSendChunkList m_SendChunksLowPriority; + sSendChunkList m_SendChunksMediumPriority; + sSendChunkList m_SendChunksHighPriority; cEvent m_evtQueue; // Set when anything is added to m_ChunksReady cEvent m_evtRemoved; // Set when removed clients are safe to be deleted int m_RemoveCount; // Number of threads waiting for a client removal (m_evtRemoved needs to be set this many times) @@ -158,7 +167,7 @@ protected: virtual void Entity (cEntity * a_Entity) override; virtual void BlockEntity (cBlockEntity * a_Entity) override; - /// Sends the specified chunk to a_Client, or to all chunk clients if a_Client == NULL + /// Sends the specified chunk to a_Client, or to all chunk clients if a_Client == nullptr void SendChunk(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); } ; diff --git a/src/ChunkStay.cpp b/src/ChunkStay.cpp index 38aa89a37..0772787de 100644 --- a/src/ChunkStay.cpp +++ b/src/ChunkStay.cpp @@ -12,7 +12,7 @@ cChunkStay::cChunkStay(void) : - m_ChunkMap(NULL) + m_ChunkMap(nullptr) { } @@ -31,7 +31,7 @@ cChunkStay::~cChunkStay() void cChunkStay::Clear(void) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); m_Chunks.clear(); } @@ -41,7 +41,7 @@ void cChunkStay::Clear(void) void cChunkStay::Add(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); for (cChunkCoordsVector::const_iterator itr = m_Chunks.begin(); itr != m_Chunks.end(); ++itr) { @@ -60,7 +60,7 @@ void cChunkStay::Add(int a_ChunkX, int a_ChunkZ) void cChunkStay::Remove(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); for (cChunkCoordsVector::iterator itr = m_Chunks.begin(); itr != m_Chunks.end(); ++itr) { @@ -79,7 +79,7 @@ void cChunkStay::Remove(int a_ChunkX, int a_ChunkZ) void cChunkStay::Enable(cChunkMap & a_ChunkMap) { - ASSERT(m_ChunkMap == NULL); + ASSERT(m_ChunkMap == nullptr); m_OutstandingChunks = m_Chunks; m_ChunkMap = &a_ChunkMap; @@ -92,10 +92,10 @@ void cChunkStay::Enable(cChunkMap & a_ChunkMap) void cChunkStay::Disable(void) { - ASSERT(m_ChunkMap != NULL); + ASSERT(m_ChunkMap != nullptr); cChunkMap * ChunkMap = m_ChunkMap; - m_ChunkMap = NULL; + m_ChunkMap = nullptr; ChunkMap->DelChunkStay(*this); } diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 3b677460b..94bace43a 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -68,7 +68,7 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_ViewDistance(a_ViewDistance), m_IPString(a_Socket->GetIPString()), m_OutgoingData(64 KiB), - m_Player(NULL), + m_Player(nullptr), m_HasSentDC(false), m_LastStreamedChunkX(0x7fffffff), // bogus chunk coords to force streaming upon login m_LastStreamedChunkZ(0x7fffffff), @@ -122,10 +122,10 @@ cClientHandle::~cClientHandle() m_ChunksToSend.clear(); } - if (m_Player != NULL) + if (m_Player != nullptr) { cWorld * World = m_Player->GetWorld(); - if (World != NULL) + if (World != nullptr) { if (!m_Username.empty()) { @@ -137,7 +137,7 @@ cClientHandle::~cClientHandle() m_Player->Destroy(); } delete m_Player; - m_Player = NULL; + m_Player = nullptr; } if (!m_HasSentDC) @@ -149,7 +149,7 @@ cClientHandle::~cClientHandle() cRoot::Get()->GetServer()->RemoveClient(this); delete m_Protocol; - m_Protocol = NULL; + m_Protocol = nullptr; LOGD("ClientHandle at %p deleted", this); } @@ -173,7 +173,7 @@ void cClientHandle::Destroy(void) // DEBUG: LOGD("%s: client %p, \"%s\"", __FUNCTION__, this, m_Username.c_str()); - if ((m_Player != NULL) && (m_Player->GetWorld() != NULL)) + if ((m_Player != nullptr) && (m_Player->GetWorld() != nullptr)) { RemoveFromAllChunks(); m_Player->GetWorld()->RemoveClientFromChunkSender(this); @@ -248,9 +248,12 @@ AString cClientHandle::GenerateOfflineUUID(const AString & a_Username) // xxxxxxxx-xxxx-3xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B // Note that we generate a short UUID (without the dashes) + // First make the username lowercase: + AString lcUsername = StrToLower(a_Username); + // Generate an md5 checksum, and use it as base for the ID: unsigned char MD5[16]; - md5((const unsigned char *)a_Username.c_str(), a_Username.length(), MD5); + md5((const unsigned char *)lcUsername.c_str(), lcUsername.length(), MD5); MD5[6] &= 0x0f; // Need to trim to 4 bits only... MD5[8] &= 0x0f; // ... otherwise %01x overflows into two chars return Printf("%02x%02x%02x%02x%02x%02x3%01x%02x8%01x%02x%02x%02x%02x%02x%02x%02x", @@ -311,7 +314,7 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, return; } - ASSERT(m_Player == NULL); + ASSERT(m_Player == nullptr); m_Username = a_Name; @@ -332,7 +335,7 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, m_Player = new cPlayer(this, GetUsername()); cWorld * World = cRoot::Get()->GetWorld(m_Player->GetLoadedWorldName()); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetDefaultWorld(); } @@ -402,53 +405,145 @@ void cClientHandle::Authenticate(const AString & a_Name, const AString & a_UUID, -void cClientHandle::StreamChunks(void) +bool cClientHandle::StreamNextChunk(void) { if ((m_State < csAuthenticated) || (m_State >= csDestroying)) { - return; + return true; + } + ASSERT(m_Player != nullptr); + + int ChunkPosX = m_Player->GetChunkX(); + int ChunkPosZ = m_Player->GetChunkZ(); + if ((m_LastStreamedChunkX == ChunkPosX) && (m_LastStreamedChunkZ == ChunkPosZ)) + { + // All chunks are already loaded. Abort loading. + return true; } - ASSERT(m_Player != NULL); + // Get the look vector and normalize it. + Vector3d Position = m_Player->GetEyePosition(); + Vector3d LookVector = m_Player->GetLookVector(); + LookVector.Normalize(); - int ChunkPosX = FAST_FLOOR_DIV((int)m_Player->GetPosX(), cChunkDef::Width); - int ChunkPosZ = FAST_FLOOR_DIV((int)m_Player->GetPosZ(), cChunkDef::Width); - if ((ChunkPosX == m_LastStreamedChunkX) && (ChunkPosZ == m_LastStreamedChunkZ)) + // Lock the list + cCSLock Lock(m_CSChunkLists); + + // High priority: Load the chunks that are in the view-direction of the player (with a radius of 3) + for (int Range = 0; Range < m_ViewDistance; Range++) { - // Already streamed for this position - return; + Vector3d Vector = Position + LookVector * cChunkDef::Width * Range; + + // Get the chunk from the x/z coords. + int RangeX, RangeZ = 0; + cChunkDef::BlockToChunk(FloorC(Vector.x), FloorC(Vector.z), RangeX, RangeZ); + + for (size_t X = 0; X < 7; X++) + { + for (size_t Z = 0; Z < 7; Z++) + { + int ChunkX = RangeX + ((X >= 4) ? (3 - X) : X); + int ChunkZ = RangeZ + ((Z >= 4) ? (3 - Z) : Z); + cChunkCoords Coords(ChunkX, ChunkZ); + + // Checks if the chunk is in distance + if ((Diff(ChunkX, ChunkPosX) > m_ViewDistance) || (Diff(ChunkZ, ChunkPosZ) > m_ViewDistance)) + { + continue; + } + + // If the chunk already loading/loaded -> skip + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) + { + continue; + } + + // Unloaded chunk found -> Send it to the client. + Lock.Unlock(); + StreamChunk(ChunkX, ChunkZ, ((Range <= 2) ? cChunkSender::E_CHUNK_PRIORITY_HIGH : cChunkSender::E_CHUNK_PRIORITY_MEDIUM)); + return false; + } + } } + + // Low priority: Add all chunks that are in range. (From the center out to the edge) + for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest + { + // For each distance add chunks in a hollow square centered around current position: + cChunkCoordsList CurcleChunks; + for (int i = -d; i <= d; ++i) + { + CurcleChunks.push_back(cChunkCoords(ChunkPosX + d, ChunkPosZ + i)); + CurcleChunks.push_back(cChunkCoords(ChunkPosX - d, ChunkPosZ + i)); + } + for (int i = -d + 1; i < d; ++i) + { + CurcleChunks.push_back(cChunkCoords(ChunkPosX + i, ChunkPosZ + d)); + CurcleChunks.push_back(cChunkCoords(ChunkPosX + i, ChunkPosZ - d)); + } + + // For each the CurcleChunks list and send the first unloaded chunk: + for (cChunkCoordsList::iterator itr = CurcleChunks.begin(), end = CurcleChunks.end(); itr != end; ++itr) + { + cChunkCoords Coords = *itr; + + // If the chunk already loading/loaded -> skip + if ( + (std::find(m_ChunksToSend.begin(), m_ChunksToSend.end(), Coords) != m_ChunksToSend.end()) || + (std::find(m_LoadedChunks.begin(), m_LoadedChunks.end(), Coords) != m_LoadedChunks.end()) + ) + { + continue; + } + + // Unloaded chunk found -> Send it to the client. + Lock.Unlock(); + StreamChunk(Coords.m_ChunkX, Coords.m_ChunkZ, cChunkSender::E_CHUNK_PRIORITY_LOW); + return false; + } + } + + // All chunks are loaded -> Sets the last loaded chunk coordinates to current coordinates m_LastStreamedChunkX = ChunkPosX; m_LastStreamedChunkZ = ChunkPosZ; - - LOGD("Streaming chunks centered on [%d, %d], view distance %d", ChunkPosX, ChunkPosZ, m_ViewDistance); - - cWorld * World = m_Player->GetWorld(); - ASSERT(World != NULL); + return true; +} + + + - // Remove all loaded chunks that are no longer in range; deferred to out-of-CS: - cChunkCoordsList RemoveChunks; + +void cClientHandle::UnloadOutOfRangeChunks(void) +{ + int ChunkPosX = FAST_FLOOR_DIV((int)m_Player->GetPosX(), cChunkDef::Width); + int ChunkPosZ = FAST_FLOOR_DIV((int)m_Player->GetPosZ(), cChunkDef::Width); + + cChunkCoordsList ChunksToRemove; { cCSLock Lock(m_CSChunkLists); for (cChunkCoordsList::iterator itr = m_LoadedChunks.begin(); itr != m_LoadedChunks.end();) { - int RelX = (*itr).m_ChunkX - ChunkPosX; - int RelZ = (*itr).m_ChunkZ - ChunkPosZ; - if ((RelX > m_ViewDistance) || (RelX < -m_ViewDistance) || (RelZ > m_ViewDistance) || (RelZ < -m_ViewDistance)) + int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); + int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); + if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) { - RemoveChunks.push_back(*itr); + ChunksToRemove.push_back(*itr); itr = m_LoadedChunks.erase(itr); } else { ++itr; } - } // for itr - m_LoadedChunks[] + } + for (cChunkCoordsList::iterator itr = m_ChunksToSend.begin(); itr != m_ChunksToSend.end();) { - int RelX = (*itr).m_ChunkX - ChunkPosX; - int RelZ = (*itr).m_ChunkZ - ChunkPosZ; - if ((RelX > m_ViewDistance) || (RelX < -m_ViewDistance) || (RelZ > m_ViewDistance) || (RelZ < -m_ViewDistance)) + int DiffX = Diff((*itr).m_ChunkX, ChunkPosX); + int DiffZ = Diff((*itr).m_ChunkZ, ChunkPosZ); + if ((DiffX > m_ViewDistance) || (DiffZ > m_ViewDistance)) { itr = m_ChunksToSend.erase(itr); } @@ -456,52 +551,21 @@ void cClientHandle::StreamChunks(void) { ++itr; } - } // for itr - m_ChunksToSend[] + } } - for (cChunkCoordsList::iterator itr = RemoveChunks.begin(); itr != RemoveChunks.end(); ++itr) - { - World->RemoveChunkClient(itr->m_ChunkX, itr->m_ChunkZ, this); - m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); - } // for itr - RemoveChunks[] - - // Add all chunks that are in range and not yet in m_LoadedChunks: - // Queue these smartly - from the center out to the edge - for (int d = 0; d <= m_ViewDistance; ++d) // cycle through (square) distance, from nearest to furthest - { - // For each distance add chunks in a hollow square centered around current position: - for (int i = -d; i <= d; ++i) - { - StreamChunk(ChunkPosX + d, ChunkPosZ + i); - StreamChunk(ChunkPosX - d, ChunkPosZ + i); - } // for i - for (int i = -d + 1; i < d; ++i) - { - StreamChunk(ChunkPosX + i, ChunkPosZ + d); - StreamChunk(ChunkPosX + i, ChunkPosZ - d); - } // for i - } // for d - - // Touch chunks GENERATEDISTANCE ahead to let them generate: - for (int d = m_ViewDistance + 1; d <= m_ViewDistance + GENERATEDISTANCE; ++d) // cycle through (square) distance, from nearest to furthest + + for (cChunkCoordsList::iterator itr = ChunksToRemove.begin(); itr != ChunksToRemove.end(); ++itr) { - // For each distance touch chunks in a hollow square centered around current position: - for (int i = -d; i <= d; ++i) - { - World->TouchChunk(ChunkPosX + d, ChunkPosZ + i); - World->TouchChunk(ChunkPosX - d, ChunkPosZ + i); - } // for i - for (int i = -d + 1; i < d; ++i) - { - World->TouchChunk(ChunkPosX + i, ChunkPosZ + d); - World->TouchChunk(ChunkPosX + i, ChunkPosZ - d); - } // for i - } // for d + m_Player->GetWorld()->RemoveChunkClient(itr->m_ChunkX, itr->m_ChunkZ, this); + SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); + } } -void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) + +void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority) { if (m_State >= csDestroying) { @@ -510,7 +574,7 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) } cWorld * World = m_Player->GetWorld(); - ASSERT(World != NULL); + ASSERT(World != nullptr); if (World->AddChunkClient(a_ChunkX, a_ChunkZ, this)) { @@ -519,7 +583,7 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) m_LoadedChunks.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); m_ChunksToSend.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); } - World->SendChunkTo(a_ChunkX, a_ChunkZ, this); + World->SendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, this); } } @@ -531,16 +595,18 @@ void cClientHandle::StreamChunk(int a_ChunkX, int a_ChunkZ) void cClientHandle::RemoveFromAllChunks() { cWorld * World = m_Player->GetWorld(); - if (World != NULL) + if (World != nullptr) { World->RemoveClientFromChunks(this); } { + // Reset all chunk lists: cCSLock Lock(m_CSChunkLists); m_LoadedChunks.clear(); m_ChunksToSend.clear(); - + m_SentChunks.clear(); + // Also reset the LastStreamedChunk coords to bogus coords, // so that all chunks are streamed in subsequent StreamChunks() call (FS #407) m_LastStreamedChunkX = 0x7fffffff; @@ -593,7 +659,7 @@ bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Usernam m_Username = a_Username; // Let the plugins know about this event, they may refuse the player: - if (cRoot::Get()->GetPluginManager()->CallHookLogin(this, a_ProtocolVersion, a_Username)) + if (cRoot::Get()->GetPluginManager()->CallHookLogin(*this, a_ProtocolVersion, a_Username)) { Destroy(); return false; @@ -645,7 +711,7 @@ void cClientHandle::HandlePlayerAbilities(bool a_CanFly, bool a_IsFlying, float void cClientHandle::HandlePlayerPos(double a_PosX, double a_PosY, double a_PosZ, double a_Stance, bool a_IsOnGround) { - if ((m_Player == NULL) || (m_State != csPlaying)) + if ((m_Player == nullptr) || (m_State != csPlaying)) { // The client hasn't been spawned yet and sends nonsense, we know better return; @@ -779,7 +845,7 @@ void cClientHandle::UnregisterPluginChannels(const AStringVector & a_ChannelList void cClientHandle::HandleBeaconSelection(int a_PrimaryEffect, int a_SecondaryEffect) { cWindow * Window = m_Player->GetWindow(); - if ((Window == NULL) || (Window->GetWindowType() != cWindow::wtBeacon)) + if ((Window == nullptr) || (Window->GetWindowType() != cWindow::wtBeacon)) { return; } @@ -855,7 +921,7 @@ void cClientHandle::HandleCommandBlockEntityChange(int a_EntityID, const AString void cClientHandle::HandleAnvilItemName(const AString & a_ItemName) { - if ((m_Player->GetWindow() == NULL) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtAnvil)) + if ((m_Player->GetWindow() == nullptr) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtAnvil)) { return; } @@ -1492,7 +1558,7 @@ void cClientHandle::HandleChat(const AString & a_Message) void cClientHandle::HandlePlayerLook(float a_Rotation, float a_Pitch, bool a_IsOnGround) { - if ((m_Player == NULL) || (m_State != csPlaying)) + if ((m_Player == nullptr) || (m_State != csPlaying)) { return; } @@ -1592,7 +1658,7 @@ void cClientHandle::HandleWindowClick(char a_WindowID, short a_SlotNum, eClickAc ); cWindow * Window = m_Player->GetWindow(); - if (Window == NULL) + if (Window == nullptr) { LOGWARNING("Player \"%s\" clicked in a non-existent window. Ignoring", m_Username.c_str()); return; @@ -1684,7 +1750,7 @@ void cClientHandle::HandleUseEntity(int a_TargetEntityID, bool a_IsLeftClick) void cClientHandle::HandleRespawn(void) { - if (m_Player == NULL) + if (m_Player == nullptr) { Destroy(); return; @@ -1712,7 +1778,7 @@ void cClientHandle::HandleKeepAlive(int a_KeepAliveID) bool cClientHandle::HandleHandshake(const AString & a_Username) { - if (!cRoot::Get()->GetPluginManager()->CallHookHandshake(this, a_Username)) + if (!cRoot::Get()->GetPluginManager()->CallHookHandshake(*this, a_Username)) { if (cRoot::Get()->GetServer()->GetNumPlayers() >= cRoot::Get()->GetServer()->GetMaxPlayers()) { @@ -1774,7 +1840,7 @@ void cClientHandle::HandleEntitySprinting(int a_EntityID, bool a_IsSprinting) void cClientHandle::HandleUnmount(void) { - if (m_Player == NULL) + if (m_Player == nullptr) { return; } @@ -1866,10 +1932,11 @@ void cClientHandle::RemoveFromWorld(void) { m_Protocol->SendUnloadChunk(itr->m_ChunkX, itr->m_ChunkZ); } // for itr - Chunks[] - + // Here, we set last streamed values to bogus ones so everything is resent m_LastStreamedChunkX = 0x7fffffff; m_LastStreamedChunkZ = 0x7fffffff; + m_HasSentPlayerChunk = false; } @@ -1879,8 +1946,8 @@ void cClientHandle::RemoveFromWorld(void) bool cClientHandle::CheckBlockInteractionsRate(void) { - ASSERT(m_Player != NULL); - ASSERT(m_Player->GetWorld() != NULL); + ASSERT(m_Player != nullptr); + ASSERT(m_Player->GetWorld() != nullptr); if (m_NumBlockChangeInteractionsThisTick > MAX_BLOCK_CHANGE_INTERACTIONS) { @@ -1911,11 +1978,11 @@ void cClientHandle::Tick(float a_Dt) Destroy(); } - if (m_Player == NULL) + if (m_Player == nullptr) { return; } - + // If the chunk the player's in was just sent, spawn the player: if (m_HasSentPlayerChunk && (m_State == csDownloadingWorld)) { @@ -1936,6 +2003,26 @@ void cClientHandle::Tick(float a_Dt) } } + if ((m_State >= csAuthenticated) && (m_State < csDestroying)) + { + // Stream 4 chunks per tick + for (int i = 0; i < 4; i++) + { + // Stream the next chunk + if (StreamNextChunk()) + { + // Streaming finished. All chunks are loaded. + break; + } + } + + // Unload all chunks that are out of the view distance (all 5 seconds) + if ((m_Player->GetWorld()->GetWorldAge() % 100) == 0) + { + UnloadOutOfRangeChunks(); + } + } + // Handle block break animation: if (m_BlockDigAnimStage > -1) { @@ -1972,7 +2059,7 @@ void cClientHandle::ServerTick(float a_Dt) if (m_State == csAuthenticated) { - StreamChunks(); + StreamNextChunk(); // Remove the client handle from the server, it will be ticked from its cPlayer object from now on cRoot::Get()->GetServer()->ClientMovedToWorld(this); @@ -2024,7 +2111,17 @@ void cClientHandle::SendBlockBreakAnim(int a_EntityID, int a_BlockX, int a_Block void cClientHandle::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { - m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); + int ChunkX, ChunkZ = 0; + cChunkDef::BlockToChunk(a_BlockX, a_BlockZ, ChunkX, ChunkZ); + cChunkCoords ChunkCoords = cChunkCoords(ChunkX, ChunkZ); + + // Do not send block changes in chunks that weren't sent to the client yet: + cCSLock Lock(m_CSChunkLists); + if (std::find(m_SentChunks.begin(), m_SentChunks.end(), ChunkCoords) != m_SentChunks.end()) + { + Lock.Unlock(); + m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); + } } @@ -2034,8 +2131,15 @@ void cClientHandle::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BL void cClientHandle::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) { ASSERT(!a_Changes.empty()); // We don't want to be sending empty change packets! - - m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); + + // Do not send block changes in chunks that weren't sent to the client yet: + cChunkCoords ChunkCoords = cChunkCoords(a_ChunkX, a_ChunkZ); + cCSLock Lock(m_CSChunkLists); + if (std::find(m_SentChunks.begin(), m_SentChunks.end(), ChunkCoords) != m_SentChunks.end()) + { + Lock.Unlock(); + m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); + } } @@ -2045,10 +2149,10 @@ void cClientHandle::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlock void cClientHandle::SendChat(const AString & a_Message, eMessageType a_ChatPrefix, const AString & a_AdditionalData) { cWorld * World = GetPlayer()->GetWorld(); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetWorld(GetPlayer()->GetLoadedWorldName()); - if (World == NULL) + if (World == nullptr) { World = cRoot::Get()->GetDefaultWorld(); } @@ -2073,7 +2177,7 @@ void cClientHandle::SendChat(const cCompositeChat & a_Message) void cClientHandle::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) { - ASSERT(m_Player != NULL); + ASSERT(m_Player != nullptr); // Check chunks being sent, erase them from m_ChunksToSend: bool Found = false; @@ -2099,6 +2203,12 @@ void cClientHandle::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializ m_Protocol->SendChunkData(a_ChunkX, a_ChunkZ, a_Serializer); + // Add the chunk to the list of chunks sent to the player: + { + cCSLock Lock(m_CSChunkLists); + m_SentChunks.push_back(cChunkCoords(a_ChunkX, a_ChunkZ)); + } + // If it is the chunk the player's in, make them spawn (in the tick thread): if ((m_State == csAuthenticated) || (m_State == csDownloadingWorld)) { @@ -2628,6 +2738,12 @@ void cClientHandle::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_D void cClientHandle::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) { + // Remove the chunk from the list of chunks sent to the client: + { + cCSLock Lock(m_CSChunkLists); + m_SentChunks.remove(cChunkCoords(a_ChunkX, a_ChunkZ)); + } + m_Protocol->SendUnloadChunk(a_ChunkX, a_ChunkZ); } @@ -2702,7 +2818,7 @@ void cClientHandle::SendWindowOpen(const cWindow & a_Window) -void cClientHandle::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cClientHandle::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value); } @@ -2731,18 +2847,8 @@ void cClientHandle::SetUsername( const AString & a_Username) void cClientHandle::SetViewDistance(int a_ViewDistance) { - if (a_ViewDistance < MIN_VIEW_DISTANCE) - { - a_ViewDistance = MIN_VIEW_DISTANCE; - } - if (a_ViewDistance > MAX_VIEW_DISTANCE) - { - a_ViewDistance = MAX_VIEW_DISTANCE; - } - m_ViewDistance = a_ViewDistance; - - // Need to re-stream chunks for the change to become apparent: - StreamChunks(); + m_ViewDistance = Clamp(a_ViewDistance, MIN_VIEW_DISTANCE, MAX_VIEW_DISTANCE); + LOGD("Setted %s's view distance to %i", GetUsername().c_str(), m_ViewDistance); } @@ -2892,7 +2998,7 @@ void cClientHandle::HandleEnchantItem(Byte & a_WindowID, Byte & a_Enchantment) } if ( - (m_Player->GetWindow() == NULL) || + (m_Player->GetWindow() == nullptr) || (m_Player->GetWindow()->GetWindowID() != a_WindowID) || (m_Player->GetWindow()->GetWindowType() != cWindow::wtEnchantment) ) diff --git a/src/ClientHandle.h b/src/ClientHandle.h index a9cc29d50..082ed2fcc 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -21,6 +21,7 @@ #include "Enchantments.h" #include "UI/SlotArea.h" #include "json/json.h" +#include "ChunkSender.h" @@ -113,7 +114,11 @@ public: /** Authenticates the specified user, called by cAuthenticator */ void Authenticate(const AString & a_Name, const AString & a_UUID, const Json::Value & a_Properties); - void StreamChunks(void); + /** This function sends a new unloaded chunk to the player. Returns true if all chunks are loaded. */ + bool StreamNextChunk(); + + /** Remove all loaded chunks that are no longer in range */ + void UnloadOutOfRangeChunks(void); // Removes the client from all chunks. Used when switching worlds or destroying the player void RemoveFromAllChunks(void); @@ -204,7 +209,7 @@ public: void SendWholeInventory (const cWindow & a_Window); void SendWindowClose (const cWindow & a_Window); void SendWindowOpen (const cWindow & a_Window); - void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value); + void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value); // tolua_begin const AString & GetUsername(void) const; @@ -343,6 +348,7 @@ private: cCriticalSection m_CSChunkLists; cChunkCoordsList m_LoadedChunks; // Chunks that the player belongs to cChunkCoordsList m_ChunksToSend; // Chunks that need to be sent to the player (queued because they weren't generated yet or there's not enough time to send them) + cChunkCoordsList m_SentChunks; // Chunks that are currently sent to the client cProtocol * m_Protocol; @@ -358,7 +364,7 @@ private: cPlayer * m_Player; bool m_HasSentDC; ///< True if a D/C packet has been sent in either direction - + // Chunk position when the last StreamChunks() was called; used to avoid re-streaming while in the same chunk int m_LastStreamedChunkX; int m_LastStreamedChunkZ; @@ -444,7 +450,7 @@ private: bool CheckBlockInteractionsRate(void); /** Adds a single chunk to be streamed to the client; used by StreamChunks() */ - void StreamChunk(int a_ChunkX, int a_ChunkZ); + void StreamChunk(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority); /** Handles the DIG_STARTED dig packet: */ void HandleBlockDigStarted (int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, BLOCKTYPE a_OldBlock, NIBBLETYPE a_OldMeta); diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp index ed3409207..64fb21181 100644 --- a/src/CraftingRecipes.cpp +++ b/src/CraftingRecipes.cpp @@ -59,7 +59,7 @@ cCraftingGrid::cCraftingGrid(const cCraftingGrid & a_Original) : cCraftingGrid::~cCraftingGrid() { delete[] m_Items; - m_Items = NULL; + m_Items = nullptr; } @@ -280,10 +280,10 @@ cCraftingRecipes::~cCraftingRecipes() -void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe) +void cCraftingRecipes::GetRecipe(cPlayer & a_Player, cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe) { // Allow plugins to intercept recipes using a pre-craft hook: - if (cRoot::Get()->GetPluginManager()->CallHookPreCrafting(a_Player, &a_CraftingGrid, &a_Recipe)) + if (cRoot::Get()->GetPluginManager()->CallHookPreCrafting(a_Player, a_CraftingGrid, a_Recipe)) { return; } @@ -291,10 +291,10 @@ void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & // Built-in recipes: std::auto_ptr<cRecipe> Recipe(FindRecipe(a_CraftingGrid.GetItems(), a_CraftingGrid.GetWidth(), a_CraftingGrid.GetHeight())); a_Recipe.Clear(); - if (Recipe.get() == NULL) + if (Recipe.get() == nullptr) { // Allow plugins to intercept a no-recipe-found situation: - cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, &a_CraftingGrid, &a_Recipe); + cRoot::Get()->GetPluginManager()->CallHookCraftingNoRecipe(a_Player, a_CraftingGrid, &a_Recipe); return; } for (cRecipeSlots::const_iterator itr = Recipe->m_Ingredients.begin(); itr != Recipe->m_Ingredients.end(); ++itr) @@ -304,7 +304,7 @@ void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_Recipe.SetResult(Recipe->m_Result); // Allow plugins to intercept recipes after they are processed: - cRoot::Get()->GetPluginManager()->CallHookPostCrafting(a_Player, &a_CraftingGrid, &a_Recipe); + cRoot::Get()->GetPluginManager()->CallHookPostCrafting(a_Player, a_CraftingGrid, a_Recipe); } @@ -603,9 +603,9 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipe(const cItem * a_Craftin // Search in the possibly minimized grid, but keep the stride: const cItem * Grid = a_CraftingGrid + GridLeft + (a_GridWidth * GridTop); cRecipe * Recipe = FindRecipeCropped(Grid, GridWidth, GridHeight, a_GridWidth); - if (Recipe == NULL) + if (Recipe == nullptr) { - return NULL; + return nullptr; } // A recipe has been found, move it to correspond to the original crafting grid: @@ -637,7 +637,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipeCropped(const cItem * a_ for (int x = 0; x <= MaxOfsX; x++) for (int y = 0; y <= MaxOfsY; y++) { cRecipe * Recipe = MatchRecipe(a_CraftingGrid, a_GridWidth, a_GridHeight, a_GridStride, *itr, x, y); - if (Recipe != NULL) + if (Recipe != nullptr) { return Recipe; } @@ -645,7 +645,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::FindRecipeCropped(const cItem * a_ } // for itr - m_Recipes[] // No matching recipe found - return NULL; + return nullptr; } @@ -681,7 +681,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti ) { // Doesn't match - return NULL; + return nullptr; } HasMatched[itrS->x + a_OffsetX][itrS->y + a_OffsetY] = true; } // for itrS - Recipe->m_Ingredients[] @@ -743,7 +743,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti } // for x if (!Found) { - return NULL; + return nullptr; } } // for itrS - a_Recipe->m_Ingredients[] @@ -753,7 +753,7 @@ cCraftingRecipes::cRecipe * cCraftingRecipes::MatchRecipe(const cItem * a_Crafti if (!HasMatched[x][y] && !a_CraftingGrid[x + a_GridStride * y].IsEmpty()) { // There's an unmatched item in the grid - return NULL; + return nullptr; } } // for y, for x diff --git a/src/CraftingRecipes.h b/src/CraftingRecipes.h index fe1e15817..44444d42e 100644 --- a/src/CraftingRecipes.h +++ b/src/CraftingRecipes.h @@ -115,7 +115,7 @@ public: ~cCraftingRecipes(); /// Returns the recipe for current crafting grid. Doesn't modify the grid. Clears a_Recipe if no recipe found. - void GetRecipe(const cPlayer * a_Player, const cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe); + void GetRecipe(cPlayer & a_Player, cCraftingGrid & a_CraftingGrid, cCraftingRecipe & a_Recipe); protected: @@ -157,13 +157,13 @@ protected: /// Moves the recipe to top-left corner, sets its MinWidth / MinHeight void NormalizeIngredients(cRecipe * a_Recipe); - /// Finds a recipe matching the crafting grid. Returns a newly allocated recipe (with all its coords set) or NULL if not found. Caller must delete return value! + /// Finds a recipe matching the crafting grid. Returns a newly allocated recipe (with all its coords set) or nullptr if not found. Caller must delete return value! cRecipe * FindRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight); /// Same as FindRecipe, but the grid is guaranteed to be of minimal dimensions needed cRecipe * FindRecipeCropped(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride); - /// Checks if the grid matches the specified recipe, offset by the specified offsets. Returns a matched cRecipe * if so, or NULL if not matching. Caller must delete the return value! + /// Checks if the grid matches the specified recipe, offset by the specified offsets. Returns a matched cRecipe * if so, or nullptr if not matching. Caller must delete the return value! cRecipe * MatchRecipe(const cItem * a_CraftingGrid, int a_GridWidth, int a_GridHeight, int a_GridStride, const cRecipe * a_Recipe, int a_OffsetX, int a_OffsetY); /** Searches for anything firework related, and does the data setting if appropriate */ diff --git a/src/Defines.h b/src/Defines.h index 6355b75b4..c2f46c241 100644 --- a/src/Defines.h +++ b/src/Defines.h @@ -39,7 +39,7 @@ enum eBlockFace BLOCK_FACE_YP = 1, // Interacting with the Y+ face of the block BLOCK_FACE_ZM = 2, // Interacting with the Z- face of the block BLOCK_FACE_ZP = 3, // Interacting with the Z+ face of the block - + // Synonyms using the (deprecated) world directions: BLOCK_FACE_BOTTOM = BLOCK_FACE_YM, // Interacting with the bottom face of the block BLOCK_FACE_TOP = BLOCK_FACE_YP, // Interacting with the top face of the block @@ -101,7 +101,7 @@ enum eClickAction caDblClick, // Add new actions here caUnknown = 255, - + // Keep this list in sync with ClickActionToString() function below! } ; @@ -116,14 +116,14 @@ enum eGameMode eGameMode_Creative = 1, eGameMode_Adventure = 2, eGameMode_Spectator = 3, - + // Easier-to-use synonyms: gmNotSet = eGameMode_NotSet, gmSurvival = eGameMode_Survival, gmCreative = eGameMode_Creative, gmAdventure = eGameMode_Adventure, gmSpectator = eGameMode_Spectator, - + // These two are used to check GameMode for validity when converting from integers. gmMax, // Gets automatically assigned gmMin = 0, @@ -138,7 +138,7 @@ enum eWeather eWeather_Sunny = 0, eWeather_Rain = 1, eWeather_ThunderStorm = 2, - + // Easier-to-use synonyms: wSunny = eWeather_Sunny, wRain = eWeather_Rain, @@ -218,7 +218,7 @@ inline const char * ClickActionToString(eClickAction a_ClickAction) case caLeftPaintEnd: return "caLeftPaintEnd"; case caRightPaintEnd: return "caRightPaintEnd"; case caDblClick: return "caDblClick"; - + case caUnknown: return "caUnknown"; } ASSERT(!"Unknown click action"); @@ -472,21 +472,21 @@ inline void AddFaceDirection(int & a_BlockX, unsigned char & a_BlockY, int & a_B { int Y = a_BlockY; AddFaceDirection(a_BlockX, Y, a_BlockZ, a_BlockFace, a_bInverse); - a_BlockY = Clamp<unsigned char>((unsigned char)Y, 0, 255); + a_BlockY = Clamp<unsigned char>(static_cast<unsigned char>(Y), 0, 255); } -#define PI 3.14159265358979323846264338327950288419716939937510582097494459072381640628620899862803482534211706798f + inline void EulerToVector(double a_Pan, double a_Pitch, double & a_X, double & a_Y, double & a_Z) { // a_X = sinf ( a_Pan / 180 * PI) * cosf ( a_Pitch / 180 * PI); // a_Y = -sinf ( a_Pitch / 180 * PI); // a_Z = -cosf ( a_Pan / 180 * PI) * cosf ( a_Pitch / 180 * PI); - a_X = cos(a_Pan / 180 * PI) * cos(a_Pitch / 180 * PI); - a_Y = sin(a_Pan / 180 * PI) * cos(a_Pitch / 180 * PI); - a_Z = sin(a_Pitch / 180 * PI); + a_X = cos(a_Pan / 180 * M_PI) * cos(a_Pitch / 180 * M_PI); + a_Y = sin(a_Pan / 180 * M_PI) * cos(a_Pitch / 180 * M_PI); + a_Z = sin(a_Pitch / 180 * M_PI); } @@ -502,10 +502,10 @@ inline void VectorToEuler(double a_X, double a_Y, double a_Z, double & a_Pan, do } else { - a_Pan = atan2(a_Z, a_X) * 180 / PI - 90; + a_Pan = atan2(a_Z, a_X) * 180 / M_PI - 90; } - a_Pitch = atan2(a_Y, r) * 180 / PI; + a_Pitch = atan2(a_Y, r) * 180 / M_PI; } @@ -556,7 +556,7 @@ enum eMessageType mtPrivateMessage, // Player to player messaging identifier mtJoin, // A player has joined the server mtLeave, // A player has left the server - + // Common aliases: mtFail = mtFailure, mtError = mtFailure, @@ -626,9 +626,9 @@ namespace ItemCategory || (a_ItemID == E_ITEM_GOLD_HOE) || (a_ItemID == E_ITEM_DIAMOND_HOE); } - - - + + + inline bool IsShovel(short a_ItemID) { return (a_ItemID == E_ITEM_WOODEN_SHOVEL) @@ -648,9 +648,9 @@ namespace ItemCategory || IsHoe ( a_ItemID) || IsShovel ( a_ItemID); } - - - + + + inline bool IsHelmet(short a_ItemType) { return ( @@ -700,9 +700,9 @@ namespace ItemCategory (a_ItemType == E_ITEM_DIAMOND_BOOTS) ); } - - - + + + inline bool IsArmor(short a_ItemType) { return ( @@ -715,7 +715,3 @@ namespace ItemCategory } // tolua_end - - - - diff --git a/src/Enchantments.cpp b/src/Enchantments.cpp index 264878c22..80a9810b6 100644 --- a/src/Enchantments.cpp +++ b/src/Enchantments.cpp @@ -6,6 +6,7 @@ #include "Enchantments.h" #include "WorldStorage/FastNBT.h" #include "FastRandom.h" +#include "Noise.h" @@ -1019,3 +1020,30 @@ cEnchantments cEnchantments::GetRandomEnchantmentFromVector(cWeightedEnchantment + +cEnchantments cEnchantments::GenerateEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed) +{ + int AllWeights = 0; + for (const auto Enchantment : a_Enchantments) + { + AllWeights += Enchantment.m_Weight; + } + + cNoise Noise(a_Seed); + int RandomNumber = Noise.IntNoise1DInt(AllWeights) / 7 % AllWeights; + + for (const auto Enchantment : a_Enchantments) + { + RandomNumber -= Enchantment.m_Weight; + if (RandomNumber < 0) + { + return Enchantment.m_Enchantments; + } + } + + return cEnchantments(); +} + + + + diff --git a/src/Enchantments.h b/src/Enchantments.h index 824f6aa55..e4390a5f2 100644 --- a/src/Enchantments.h +++ b/src/Enchantments.h @@ -128,6 +128,9 @@ public: /** Gets random enchantment from Vector and returns it */ static cEnchantments GetRandomEnchantmentFromVector(cWeightedEnchantments & a_Enchantments); + /** Returns an enchantment from a Vector using cNoise. Mostly used for generators.*/ + static cEnchantments GenerateEnchantmentFromVector(cWeightedEnchantments & a_Enchantments, int a_Seed); + /** Returns true if a_Other doesn't contain exactly the same enchantments and levels */ bool operator !=(const cEnchantments & a_Other) const; diff --git a/src/Entities/ArrowEntity.cpp b/src/Entities/ArrowEntity.cpp index c265c5043..30f18f677 100644 --- a/src/Entities/ArrowEntity.cpp +++ b/src/Entities/ArrowEntity.cpp @@ -149,14 +149,14 @@ void cArrowEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) -void cArrowEntity::CollectedBy(cPlayer * a_Dest) +void cArrowEntity::CollectedBy(cPlayer & a_Dest) { - if (m_IsInGround && !m_bIsCollected && CanPickup(*a_Dest)) + if (m_IsInGround && !m_bIsCollected && CanPickup(a_Dest)) { // Do not add the arrow to the inventory when the player is in creative: - if (!a_Dest->IsGameModeCreative()) + if (!a_Dest.IsGameModeCreative()) { - int NumAdded = a_Dest->GetInventory().AddItem(E_ITEM_ARROW); + int NumAdded = a_Dest.GetInventory().AddItem(E_ITEM_ARROW); if (NumAdded == 0) { // No space in the inventory @@ -164,7 +164,7 @@ void cArrowEntity::CollectedBy(cPlayer * a_Dest) } } - GetWorld()->BroadcastCollectEntity(*this, *a_Dest); + GetWorld()->BroadcastCollectEntity(*this, a_Dest); GetWorld()->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64)); m_bIsCollected = true; } @@ -217,7 +217,7 @@ void cArrowEntity::Tick(float a_Dt, cChunk & a_Chunk) int RelPosZ = m_HitBlockPos.z - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Inside an unloaded chunk, abort return; @@ -229,3 +229,7 @@ void cArrowEntity::Tick(float a_Dt, cChunk & a_Chunk) } } } + + + + diff --git a/src/Entities/ArrowEntity.h b/src/Entities/ArrowEntity.h index a1e7a17e7..436ec0293 100644 --- a/src/Entities/ArrowEntity.h +++ b/src/Entities/ArrowEntity.h @@ -1,6 +1,11 @@ -// -// ArrowEntity.h -// + +// ArrowEntity.h + +// Declares the cArrowEntity representing the arrow that has been shot by the player or by a skeleton + + + + #pragma once @@ -19,7 +24,7 @@ class cArrowEntity : typedef cProjectileEntity super; public: - /// Determines when the arrow can be picked up (depending on player gamemode). Corresponds to the MCA file "pickup" field + /** Determines when the arrow can be picked up (depending on player gamemode). Corresponds to the MCA file "pickup" field */ enum ePickupState { psNoPickup = 0, @@ -31,33 +36,33 @@ public: CLASS_PROTODEF(cArrowEntity) - /// Creates a new arrow with psNoPickup state and default damage modifier coeff + /** Creates a new arrow with psNoPickup state and default damage modifier coeff */ cArrowEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const Vector3d & a_Speed); - /// Creates a new arrow as shot by a player, initializes it from the player object + /** Creates a new arrow as shot by a player, initializes it from the player object */ cArrowEntity(cPlayer & a_Player, double a_Force); // tolua_begin - /// Returns whether the arrow can be picked up by players + /** Returns whether the arrow can be picked up by players */ ePickupState GetPickupState(void) const { return m_PickupState; } - /// Sets a new pickup state + /** Sets a new pickup state */ void SetPickupState(ePickupState a_PickupState) { m_PickupState = a_PickupState; } - /// Returns the damage modifier coeff. + /** Returns the damage modifier coeff. */ double GetDamageCoeff(void) const { return m_DamageCoeff; } - /// Sets the damage modifier coeff + /** Sets the damage modifier coeff */ void SetDamageCoeff(double a_DamageCoeff) { m_DamageCoeff = a_DamageCoeff; } - /// Returns true if the specified player can pick the arrow up + /** Returns true if the specified player can pick the arrow up */ bool CanPickup(const cPlayer & a_Player) const; - /// Returns true if the arrow is set as critical + /** Returns true if the arrow is set as critical */ bool IsCritical(void) const { return m_IsCritical; } - /// Sets the IsCritical flag + /** Sets the IsCritical flag */ void SetIsCritical(bool a_IsCritical) { m_IsCritical = a_IsCritical; } /** Gets the block arrow is in */ @@ -70,34 +75,34 @@ public: protected: - /// Determines when the arrow can be picked up by players + /** Determines when the arrow can be picked up by players */ ePickupState m_PickupState; - /// The coefficient applied to the damage that the arrow will deal, based on the bow enchantment. 2.0 for normal arrow + /** The coefficient applied to the damage that the arrow will deal, based on the bow enchantment. 2.0 for normal arrow */ double m_DamageCoeff; - /// If true, the arrow deals more damage + /** If true, the arrow deals more damage */ bool m_IsCritical; - /// Timer for pickup collection animation or five minute timeout + /** Timer for pickup collection animation or five minute timeout */ float m_Timer; - /// Timer for client arrow position confirmation via TeleportEntity + /** Timer for client arrow position confirmation via TeleportEntity */ float m_HitGroundTimer; // Whether the arrow has already been teleported into the proper position in the ground. bool m_HasTeleported; - /// If true, the arrow is in the process of being collected - don't go to anyone else + /** If true, the arrow is in the process of being collected - don't go to anyone else */ bool m_bIsCollected; - /// Stores the block position that arrow is lodged into, sets m_IsInGround to false if it becomes air + /** Stores the block position that arrow is lodged into, sets m_IsInGround to false if it becomes air */ Vector3i m_HitBlockPos; // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void CollectedBy(cPlayer * a_Player) override; + virtual void CollectedBy(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; }; // tolua_export diff --git a/src/Entities/Boat.cpp b/src/Entities/Boat.cpp index 328a70846..953213bca 100644 --- a/src/Entities/Boat.cpp +++ b/src/Entities/Boat.cpp @@ -42,7 +42,7 @@ bool cBoat::DoTakeDamage(TakeDamageInfo & TDI) if (GetHealth() == 0) { - if (TDI.Attacker != NULL) + if (TDI.Attacker != nullptr) { if (TDI.Attacker->IsPlayer()) { @@ -64,7 +64,7 @@ void cBoat::OnRightClicked(cPlayer & a_Player) { super::OnRightClicked(a_Player); - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { diff --git a/src/Entities/Entity.cpp b/src/Entities/Entity.cpp index da85dec50..afc61c73f 100644 --- a/src/Entities/Entity.cpp +++ b/src/Entities/Entity.cpp @@ -29,8 +29,8 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d : m_UniqueID(0) , m_Health(1) , m_MaxHealth(1) - , m_AttachedTo(NULL) - , m_Attachee(NULL) + , m_AttachedTo(nullptr) + , m_Attachee(nullptr) , m_bDirtyHead(true) , m_bDirtyOrientation(true) , m_bHasSentNoSpeed(true) @@ -38,9 +38,9 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d , m_Gravity(-9.81f) , m_LastPos(a_X, a_Y, a_Z) , m_IsInitialized(false) - , m_WorldTravellingFrom(NULL) + , m_WorldTravellingFrom(nullptr) , m_EntityType(a_EntityType) - , m_World(NULL) + , m_World(nullptr) , m_IsFireproof(false) , m_TicksSinceLastBurnDamage(0) , m_TicksSinceLastLavaDamage(0) @@ -73,7 +73,7 @@ cEntity::cEntity(eEntityType a_EntityType, double a_X, double a_Y, double a_Z, d cEntity::~cEntity() { // Before deleting, the entity needs to have been removed from the world, if ever added - ASSERT((m_World == NULL) || !m_World->HasEntity(m_UniqueID)); + ASSERT((m_World == nullptr) || !m_World->HasEntity(m_UniqueID)); /* // DEBUG: @@ -85,11 +85,11 @@ cEntity::~cEntity() ); */ - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Detach(); } - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { m_Attachee->Detach(); } @@ -242,7 +242,7 @@ void cEntity::TakeDamage(eDamageType a_DamageType, cEntity * a_Attacker, int a_R TDI.FinalDamage = a_FinalDamage; Vector3d Heading(0, 0, 0); - if (a_Attacker != NULL) + if (a_Attacker != nullptr) { Heading = a_Attacker->GetLookVector() * (a_Attacker->IsSprinting() ? 16 : 11); Heading.y = 1.6; @@ -265,7 +265,7 @@ void cEntity::SetYawFromSpeed(void) SetYaw(0); return; } - SetYaw(atan2(m_Speed.x, m_Speed.z) * 180 / PI); + SetYaw(atan2(m_Speed.x, m_Speed.z) * 180 / M_PI); } @@ -282,7 +282,7 @@ void cEntity::SetPitchFromSpeed(void) SetPitch(0); return; } - SetPitch(atan2(m_Speed.y, xz) * 180 / PI); + SetPitch(atan2(m_Speed.y, xz) * 180 / M_PI); } @@ -308,7 +308,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { cPlayer * Player = (cPlayer *)a_TDI.Attacker; @@ -544,7 +544,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) m_Health = std::max(m_Health, 0); // Add knockback: - if ((IsMob() || IsPlayer()) && (a_TDI.Attacker != NULL)) + if ((IsMob() || IsPlayer()) && (a_TDI.Attacker != nullptr)) { int KnockbackLevel = a_TDI.Attacker->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchKnockback); // More common enchantment if (KnockbackLevel < 1) @@ -571,7 +571,7 @@ bool cEntity::DoTakeDamage(TakeDamageInfo & a_TDI) { KilledBy(a_TDI); - if (a_TDI.Attacker != NULL) + if (a_TDI.Attacker != nullptr) { a_TDI.Attacker->Killed(this); } @@ -778,7 +778,7 @@ void cEntity::Tick(float a_Dt, cChunk & a_Chunk) m_InvulnerableTicks--; } - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Vector3d DeltaPos = m_Pos - m_AttachedTo->GetPosition(); if (DeltaPos.Length() > 0.5) @@ -1092,7 +1092,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtOnFire, NULL, BURN_DAMAGE, 0); + TakeDamage(dtOnFire, nullptr, BURN_DAMAGE, 0); } m_TicksSinceLastBurnDamage = 0; } @@ -1163,7 +1163,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtLavaContact, NULL, LAVA_DAMAGE, 0); + TakeDamage(dtLavaContact, nullptr, LAVA_DAMAGE, 0); } m_TicksSinceLastLavaDamage = 0; } @@ -1184,7 +1184,7 @@ void cEntity::TickBurning(cChunk & a_Chunk) { if (!m_IsFireproof) { - TakeDamage(dtFireContact, NULL, FIRE_DAMAGE, 0); + TakeDamage(dtFireContact, nullptr, FIRE_DAMAGE, 0); } m_TicksSinceLastFireDamage = 0; } @@ -1213,7 +1213,7 @@ void cEntity::TickInVoid(cChunk & a_Chunk) { if (m_TicksSinceLastVoidDamage == 20) { - TakeDamage(dtInVoid, NULL, 2, 0); + TakeDamage(dtInVoid, nullptr, 2, 0); m_TicksSinceLastVoidDamage = 0; } else @@ -1239,7 +1239,7 @@ void cEntity::DetectCacti(void) (((GetPosY() - Y < 1) && (GetWorld()->GetBlock(X, Y, Z) == E_BLOCK_CACTUS)))) ) { - TakeDamage(dtCactusContact, NULL, 1, 0); + TakeDamage(dtCactusContact, nullptr, 1, 0); } } @@ -1380,7 +1380,7 @@ bool cEntity::DetectPortal() bool cEntity::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) { UNUSED(a_ShouldSendRespawn); - ASSERT(a_World != NULL); + ASSERT(a_World != nullptr); if (GetWorld() == a_World) { @@ -1406,7 +1406,7 @@ bool cEntity::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) bool cEntity::MoveToWorld(const AString & a_WorldName, bool a_ShouldSendRespawn) { cWorld * World = cRoot::Get()->GetWorld(a_WorldName); - if (World == NULL) + if (World == nullptr) { LOG("%s: Couldn't find world \"%s\".", __FUNCTION__, a_WorldName.c_str()); return false; @@ -1493,7 +1493,7 @@ void cEntity::HandleAir(void) if (m_AirTickTimer <= 0) { // Damage player - TakeDamage(dtDrowning, NULL, 1, 1, 0); + TakeDamage(dtDrowning, nullptr, 1, 1, 0); // Reset timer m_AirTickTimer = DROWNING_TICKS; } @@ -1708,7 +1708,7 @@ void cEntity::AttachTo(cEntity * a_AttachTo) // Already attached to that entity, nothing to do here return; } - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { // Detach from any previous entity: Detach(); @@ -1726,14 +1726,14 @@ void cEntity::AttachTo(cEntity * a_AttachTo) void cEntity::Detach(void) { - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { // Attached to no entity, our work is done return; } - m_AttachedTo->m_Attachee = NULL; - m_AttachedTo = NULL; - m_World->BroadcastAttachEntity(*this, NULL); + m_AttachedTo->m_Attachee = nullptr; + m_AttachedTo = nullptr; + m_World->BroadcastAttachEntity(*this, nullptr); } @@ -1956,7 +1956,7 @@ void cEntity::HandleSpeedFromAttachee(float a_Forward, float a_Sideways) void cEntity::SteerVehicle(float a_Forward, float a_Sideways) { - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { return; } diff --git a/src/Entities/Entity.h b/src/Entities/Entity.h index f0577aba2..af545fe4a 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -32,7 +32,7 @@ #define POSZ_TOINT FloorC(GetPosZ()) #define POS_TOINT Vector3i(POSXTOINT, POSYTOINT, POSZTOINT) -#define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == NULL) || !ChunkVarName->IsValid()) { return; } +#define GET_AND_VERIFY_CURRENT_CHUNK(ChunkVarName, X, Z) cChunk * ChunkVarName = a_Chunk.GetNeighborChunk(X, Z); if ((ChunkVarName == nullptr) || !ChunkVarName->IsValid()) { return; } @@ -172,13 +172,13 @@ public: /// Returns true if the entity is of the specified class or a subclass (cPawn's IsA("cEntity") returns true) virtual bool IsA(const char * a_ClassName) const; - /// Returns the topmost class name for the object - virtual const char * GetClass(void) const; - - // Returns the class name of this class + /** Returns the class name of this class */ static const char * GetClassStatic(void); - /// Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). + /** Returns the topmost class name for the object */ + virtual const char * GetClass(void) const; + + /** Returns the topmost class's parent class name for the object. cEntity returns an empty string (no parent). */ virtual const char * GetParentClass(void) const; cWorld * GetWorld(void) const { return m_World; } @@ -309,7 +309,7 @@ public: /// Returns the currently equipped boots; empty item if none virtual cItem GetEquippedBoots(void) const { return cItem(); } - /// Called when the health drops below zero. a_Killer may be NULL (environmental damage) + /// Called when the health drops below zero. a_Killer may be nullptr (environmental damage) virtual void KilledBy(TakeDamageInfo & a_TDI); /// Called when the entity kills another entity @@ -401,7 +401,7 @@ public: void SetWorldTravellingFrom(cWorld * a_World) { m_WorldTravellingFrom = a_World; } /// Updates clients of changes in the entity. - virtual void BroadcastMovementUpdate(const cClientHandle * a_Exclude = NULL); + virtual void BroadcastMovementUpdate(const cClientHandle * a_Exclude = nullptr); /// Attaches to the specified entity; detaches from any previous one first void AttachTo(cEntity * a_AttachTo); @@ -450,7 +450,7 @@ public: virtual void OnRightClicked(cPlayer & a_Player) {} /// Returns the list of drops for this pawn when it is killed. May check a_Killer for special handling (sword of looting etc.). Called from KilledBy(). - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) { UNUSED(a_Drops); UNUSED(a_Killer); @@ -471,10 +471,10 @@ protected: int m_Health; int m_MaxHealth; - /// The entity to which this entity is attached (vehicle), NULL if none + /// The entity to which this entity is attached (vehicle), nullptr if none cEntity * m_AttachedTo; - /// The entity which is attached to this entity (rider), NULL if none + /// The entity which is attached to this entity (rider), nullptr if none cEntity * m_Attachee; /** Stores whether head yaw has been set manually */ @@ -502,7 +502,7 @@ protected: bool m_IsInitialized; /** World entity is travelling from - Set to a valid world pointer by MoveToWorld; reset to NULL when the entity is removed from the old world + Set to a valid world pointer by MoveToWorld; reset to nullptr when the entity is removed from the old world Can't be a simple boolean as context switches between worlds may leave the new chunk processing (and therefore immediately removing) the entity before the old chunk could remove it */ cWorld * m_WorldTravellingFrom; diff --git a/src/Entities/EntityEffect.cpp b/src/Entities/EntityEffect.cpp index b1ddaa30e..bae686b77 100644 --- a/src/Entities/EntityEffect.cpp +++ b/src/Entities/EntityEffect.cpp @@ -216,7 +216,7 @@ cEntityEffect * cEntityEffect::CreateEntityEffect(cEntityEffect::eType a_EffectT } ASSERT(!"Unhandled entity effect type!"); - return NULL; + return nullptr; } @@ -329,7 +329,7 @@ void cEntityEffectInstantHealth::OnActivate(cPawn & a_Target) if (a_Target.IsMob() && ((cMonster &) a_Target).IsUndead()) { - a_Target.TakeDamage(dtPotionOfHarming, NULL, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage + a_Target.TakeDamage(dtPotionOfHarming, nullptr, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage return; } a_Target.Heal(amount); @@ -352,7 +352,7 @@ void cEntityEffectInstantDamage::OnActivate(cPawn & a_Target) a_Target.Heal(amount); return; } - a_Target.TakeDamage(dtPotionOfHarming, NULL, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage + a_Target.TakeDamage(dtPotionOfHarming, nullptr, amount, 0); // TODO: Store attacker in a pointer-safe way, pass to TakeDamage } @@ -452,7 +452,7 @@ void cEntityEffectPoison::OnTick(cPawn & a_Target) // Cannot take poison damage when health is at 1 if (a_Target.GetHealth() > 1) { - a_Target.TakeDamage(dtPoisoning, NULL, 1, 0); + a_Target.TakeDamage(dtPoisoning, nullptr, 1, 0); } } } @@ -473,7 +473,7 @@ void cEntityEffectWither::OnTick(cPawn & a_Target) if ((m_Ticks % frequency) == 0) { - a_Target.TakeDamage(dtWither, NULL, 1, 0); + a_Target.TakeDamage(dtWither, nullptr, 1, 0); } } diff --git a/src/Entities/ExpBottleEntity.h b/src/Entities/ExpBottleEntity.h index d36110f97..715b9947e 100644 --- a/src/Entities/ExpBottleEntity.h +++ b/src/Entities/ExpBottleEntity.h @@ -1,6 +1,11 @@ -// -// ExpBottleEntity.h -// + +// ExpBottleEntity.h + +// Declares the cExpBottleEntity class representing the thrown exp bottle + + + + #pragma once @@ -33,6 +38,10 @@ protected: /** Breaks the bottle, fires its particle effects and sounds @param a_HitPos The position where the bottle will break */ - void Break(const Vector3d &a_HitPos); + void Break(const Vector3d & a_HitPos); }; // tolua_export + + + + diff --git a/src/Entities/ExpOrb.cpp b/src/Entities/ExpOrb.cpp index 73d5cbfed..751308661 100644 --- a/src/Entities/ExpOrb.cpp +++ b/src/Entities/ExpOrb.cpp @@ -45,7 +45,7 @@ void cExpOrb::SpawnOn(cClientHandle & a_Client) void cExpOrb::Tick(float a_Dt, cChunk & a_Chunk) { cPlayer * a_ClosestPlayer(m_World->FindClosestPlayer(Vector3f(GetPosition()), 5)); - if (a_ClosestPlayer != NULL) + if (a_ClosestPlayer != nullptr) { Vector3f a_PlayerPos(a_ClosestPlayer->GetPosition()); a_PlayerPos.y++; diff --git a/src/Entities/FireChargeEntity.h b/src/Entities/FireChargeEntity.h index 5df55bec4..eb08f5324 100644 --- a/src/Entities/FireChargeEntity.h +++ b/src/Entities/FireChargeEntity.h @@ -1,6 +1,11 @@ -// -// FireChargeEntity.h -// + +// FireChargeEntity.h + +// Declares the cFireChargeEntity representing the fire charge shot by the blaze + + + + #pragma once @@ -34,3 +39,7 @@ protected: virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; } ; // tolua_export + + + + diff --git a/src/Entities/FireworkEntity.cpp b/src/Entities/FireworkEntity.cpp index 403a53c84..68d02640a 100644 --- a/src/Entities/FireworkEntity.cpp +++ b/src/Entities/FireworkEntity.cpp @@ -10,7 +10,7 @@ cFireworkEntity::cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem & a_Item) : super(pkFirework, a_Creator, a_X, a_Y, a_Z, 0.25, 0.25), - m_ExplodeTimer(0), + m_TicksToExplosion(a_Item.m_FireworkItem.m_FlightTimeInTicks), m_FireworkItem(a_Item) { } @@ -27,7 +27,9 @@ void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk) if ((PosY < 0) || (PosY >= cChunkDef::Height)) { - goto setspeed; + AddSpeedY(1); + AddPosition(GetSpeed() * (a_Dt / 1000)); + return; } if (m_IsInGround) @@ -50,7 +52,6 @@ void cFireworkEntity::HandlePhysics(float a_Dt, cChunk & a_Chunk) } } -setspeed: AddSpeedY(1); AddPosition(GetSpeed() * (a_Dt / 1000)); } @@ -63,11 +64,13 @@ void cFireworkEntity::Tick(float a_Dt, cChunk & a_Chunk) { super::Tick(a_Dt, a_Chunk); - if (m_ExplodeTimer == m_FireworkItem.m_FireworkItem.m_FlightTimeInTicks) + if (m_TicksToExplosion <= 0) { + // TODO: Notify the plugins m_World->BroadcastEntityStatus(*this, esFireworkExploding); Destroy(); + return; } - m_ExplodeTimer++; + m_TicksToExplosion -= 1; } diff --git a/src/Entities/FireworkEntity.h b/src/Entities/FireworkEntity.h index 20f18b6dc..300ec571e 100644 --- a/src/Entities/FireworkEntity.h +++ b/src/Entities/FireworkEntity.h @@ -1,6 +1,11 @@ -// -// FireworkEntity.h -// + +// FireworkEntity.h + +// Declares the cFireworkEntity class representing the flying firework rocket + + + + #pragma once @@ -24,7 +29,22 @@ public: CLASS_PROTODEF(cFireworkEntity) cFireworkEntity(cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem & a_Item); + + // tolua_begin + + /** Returns the item used to create the rocket (has all the firework effects on it) */ const cItem & GetItem(void) const { return m_FireworkItem; } + + /** Sets the item that is used to create the rocket (has all the firework effects on it) */ + void SetItem(const cItem & a_Item) { m_FireworkItem = a_Item; } + + /** Returns the number of ticks left until the firework explosion. */ + int GetTicksToExplosion(void) const { return m_TicksToExplosion; } + + /** Sets the number of ticks left until the firework explosion. */ + void SetTicksToExplosion(int a_TicksToExplosion) { m_TicksToExplosion = a_TicksToExplosion; } + + // tolua_end protected: @@ -34,7 +54,11 @@ protected: private: - int m_ExplodeTimer; + int m_TicksToExplosion; cItem m_FireworkItem; }; // tolua_export + + + + diff --git a/src/Entities/Floater.cpp b/src/Entities/Floater.cpp index 159429147..5fe6a1238 100644 --- a/src/Entities/Floater.cpp +++ b/src/Entities/Floater.cpp @@ -22,7 +22,7 @@ public: m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), - m_HitEntity(NULL) + m_HitEntity(nullptr) { } virtual bool Item(cEntity * a_Entity) override diff --git a/src/Entities/GhastFireballEntity.h b/src/Entities/GhastFireballEntity.h index 3ed72d9ef..bbce89d31 100644 --- a/src/Entities/GhastFireballEntity.h +++ b/src/Entities/GhastFireballEntity.h @@ -1,6 +1,11 @@ -// -// GhastFireballEntity.h -// + +// GhastFireballEntity.h + +// Declares the cGhastFireballEntity class representing the ghast fireball in flight. + + + + #pragma once @@ -36,3 +41,7 @@ protected: // TODO: Deflecting the fireballs by arrow- or sword- hits } ; // tolua_export + + + + diff --git a/src/Entities/HangingEntity.cpp b/src/Entities/HangingEntity.cpp index 3276bc4a0..a6b9c40c8 100644 --- a/src/Entities/HangingEntity.cpp +++ b/src/Entities/HangingEntity.cpp @@ -9,9 +9,9 @@ -cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) - : cEntity(a_EntityType, a_X, a_Y, a_Z, 0.8, 0.8) - , m_BlockFace(a_BlockFace) +cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_Facing, double a_X, double a_Y, double a_Z) : + cEntity(a_EntityType, a_X, a_Y, a_Z, 0.8, 0.8), + m_Facing(a_Facing) { SetMaxHealth(1); SetHealth(1); @@ -21,15 +21,23 @@ cHangingEntity::cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, -void cHangingEntity::SetDirection(eBlockFace a_BlockFace) +void cHangingEntity::SetFacing(eBlockFace a_Facing) { - if ((a_BlockFace < 2) || (a_BlockFace > 5)) + // Y-based faces are not allowed: + switch (a_Facing) { - ASSERT(!"Tried to set a bad direction!"); - return; + case BLOCK_FACE_NONE: + case BLOCK_FACE_YM: + case BLOCK_FACE_YP: + { + LOGWARNING("%s: Invalid facing: %d. Ignoring.", __FUNCTION__, a_Facing); + ASSERT(!"Tried to set a bad facing!"); + return; + } + default: break; } - m_BlockFace = a_BlockFace; + m_Facing = a_Facing; } @@ -41,7 +49,7 @@ void cHangingEntity::SpawnOn(cClientHandle & a_ClientHandle) int Dir = 0; // The client uses different values for item frame directions and block faces. Our constants are for the block faces, so we convert them here to item frame faces - switch (m_BlockFace) + switch (m_Facing) { case BLOCK_FACE_ZP: Dir = 0; break; case BLOCK_FACE_ZM: Dir = 2; break; @@ -49,8 +57,8 @@ void cHangingEntity::SpawnOn(cClientHandle & a_ClientHandle) case BLOCK_FACE_XP: Dir = 3; break; default: { - LOGINFO("Invalid face (%d) in a cHangingEntity at {%d, %d, %d}, adjusting to BLOCK_FACE_XP.", - m_BlockFace, (int)GetPosX(), (int)GetPosY(), (int)GetPosZ() + LOGINFO("Invalid facing (%d) in a cHangingEntity at {%d, %d, %d}, adjusting to BLOCK_FACE_XP.", + m_Facing, (int)GetPosX(), (int)GetPosY(), (int)GetPosZ() ); Dir = 3; } diff --git a/src/Entities/HangingEntity.h b/src/Entities/HangingEntity.h index 1cc0034e1..67146a20b 100644 --- a/src/Entities/HangingEntity.h +++ b/src/Entities/HangingEntity.h @@ -11,36 +11,41 @@ class cHangingEntity : public cEntity { - // tolua_end typedef cEntity super; public: + // tolua_end + CLASS_PROTODEF(cHangingEntity) cHangingEntity(eEntityType a_EntityType, eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z); - /** Returns the orientation from the hanging entity */ - eBlockFace GetDirection() const { return m_BlockFace; } // tolua_export + // tolua_begin + + /** Returns the direction in which the entity is facing. */ + eBlockFace GetFacing() const { return m_Facing; } - /** Set the orientation from the hanging entity */ - void SetDirection(eBlockFace a_BlockFace); // tolua_export + /** Set the direction in which the entity is facing. */ + void SetFacing(eBlockFace a_Facing); - /** Returns the X coord. */ - int GetTileX() const { return POSX_TOINT; } // tolua_export + /** Returns the X coord of the block in which the entity resides. */ + int GetBlockX() const { return POSX_TOINT; } - /** Returns the Y coord. */ - int GetTileY() const { return POSY_TOINT; } // tolua_export + /** Returns the Y coord of the block in which the entity resides. */ + int GetBlockY() const { return POSY_TOINT; } - /** Returns the Z coord. */ - int GetTileZ() const { return POSZ_TOINT; } // tolua_export + /** Returns the Z coord of the block in which the entity resides. */ + int GetBlockZ() const { return POSZ_TOINT; } + + // tolua_end private: virtual void SpawnOn(cClientHandle & a_ClientHandle) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override {} - eBlockFace m_BlockFace; + eBlockFace m_Facing; }; // tolua_export diff --git a/src/Entities/ItemFrame.cpp b/src/Entities/ItemFrame.cpp index f512324eb..dfffcd3ed 100644 --- a/src/Entities/ItemFrame.cpp +++ b/src/Entities/ItemFrame.cpp @@ -9,10 +9,10 @@ -cItemFrame::cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) - : cHangingEntity(etItemFrame, a_BlockFace, a_X, a_Y, a_Z) - , m_Item(E_BLOCK_AIR) - , m_Rotation(0) +cItemFrame::cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z) : + cHangingEntity(etItemFrame, a_BlockFace, a_X, a_Y, a_Z), + m_Item(E_BLOCK_AIR), + m_ItemRotation(0) { } @@ -27,10 +27,10 @@ void cItemFrame::OnRightClicked(cPlayer & a_Player) if (!m_Item.IsEmpty()) { // Item not empty, rotate, clipping values to zero to three inclusive - m_Rotation++; - if (m_Rotation >= 8) + m_ItemRotation++; + if (m_ItemRotation >= 8) { - m_Rotation = 0; + m_ItemRotation = 0; } } else if (!a_Player.GetEquippedItem().IsEmpty()) @@ -62,7 +62,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) return; } - if ((a_TDI.Attacker != NULL) && a_TDI.Attacker->IsPlayer() && !((cPlayer *)a_TDI.Attacker)->IsGameModeCreative()) + if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer() && !((cPlayer *)a_TDI.Attacker)->IsGameModeCreative()) { cItems Item; Item.push_back(m_Item); @@ -72,7 +72,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) SetHealth(GetMaxHealth()); m_Item.Empty(); - m_Rotation = 0; + m_ItemRotation = 0; SetInvulnerableTicks(0); GetWorld()->BroadcastEntityMetadata(*this); } @@ -83,7 +83,7 @@ void cItemFrame::KilledBy(TakeDamageInfo & a_TDI) void cItemFrame::GetDrops(cItems & a_Items, cEntity * a_Killer) { - if ((a_Killer != NULL) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) + if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) { a_Items.push_back(cItem(E_ITEM_ITEM_FRAME)); } diff --git a/src/Entities/ItemFrame.h b/src/Entities/ItemFrame.h index a63b78b70..ced8c37af 100644 --- a/src/Entities/ItemFrame.h +++ b/src/Entities/ItemFrame.h @@ -11,26 +11,31 @@ class cItemFrame : public cHangingEntity { - // tolua_end typedef cHangingEntity super; public: + // tolua_end + CLASS_PROTODEF(cItemFrame) cItemFrame(eBlockFace a_BlockFace, double a_X, double a_Y, double a_Z); + // tolua_begin + /** Returns the item in the frame */ - const cItem & GetItem(void) { return m_Item; } // tolua_export + const cItem & GetItem(void) { return m_Item; } /** Set the item in the frame */ - void SetItem(cItem & a_Item) { m_Item = a_Item; } // tolua_export + void SetItem(cItem & a_Item) { m_Item = a_Item; } /** Returns the rotation from the item in the frame */ - Byte GetRotation(void) const { return m_Rotation; } // tolua_export + Byte GetItemRotation(void) const { return m_ItemRotation; } /** Set the rotation from the item in the frame */ - void SetRotation(Byte a_Rotation) { m_Rotation = a_Rotation; } // tolua_export + void SetItemRotation(Byte a_ItemRotation) { m_ItemRotation = a_ItemRotation; } + + // tolua_end private: @@ -39,7 +44,7 @@ private: virtual void GetDrops(cItems & a_Items, cEntity * a_Killer) override; cItem m_Item; - Byte m_Rotation; + Byte m_ItemRotation; }; // tolua_export diff --git a/src/Entities/Minecart.cpp b/src/Entities/Minecart.cpp index f45e7bb69..22e046800 100644 --- a/src/Entities/Minecart.cpp +++ b/src/Entities/Minecart.cpp @@ -36,7 +36,7 @@ public: virtual bool Item(cEntity * a_Entity) override { - ASSERT(a_Entity != NULL); + ASSERT(a_Entity != nullptr); if (!a_Entity->IsPlayer() && !a_Entity->IsMob() && !a_Entity->IsMinecart() && !a_Entity->IsBoat()) { @@ -130,7 +130,7 @@ void cMinecart::HandlePhysics(float a_Dt, cChunk & a_Chunk) int RelPosX = POSX_TOINT - a_Chunk.GetPosX() * cChunkDef::Width; int RelPosZ = POSZ_TOINT - a_Chunk.GetPosZ() * cChunkDef::Width; cChunk * Chunk = a_Chunk.GetRelNeighborChunkAdjustCoords(RelPosX, RelPosZ); - if (Chunk == NULL) + if (Chunk == nullptr) { // Inside an unloaded chunk, bail out all processing return; @@ -806,7 +806,7 @@ bool cMinecart::TestBlockCollision(NIBBLETYPE a_RailMeta) bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta) { - cMinecartCollisionCallback MinecartCollisionCallback(GetPosition(), GetHeight(), GetWidth(), GetUniqueID(), ((m_Attachee == NULL) ? -1 : m_Attachee->GetUniqueID())); + cMinecartCollisionCallback MinecartCollisionCallback(GetPosition(), GetHeight(), GetWidth(), GetUniqueID(), ((m_Attachee == nullptr) ? -1 : m_Attachee->GetUniqueID())); int ChunkX, ChunkZ; cChunkDef::BlockToChunk(POSX_TOINT, POSZ_TOINT, ChunkX, ChunkZ); m_World->ForEachEntityInChunk(ChunkX, ChunkZ, MinecartCollisionCallback); @@ -980,7 +980,7 @@ bool cMinecart::TestEntityCollision(NIBBLETYPE a_RailMeta) bool cMinecart::DoTakeDamage(TakeDamageInfo & TDI) { - if ((TDI.Attacker != NULL) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative()) + if ((TDI.Attacker != nullptr) && TDI.Attacker->IsPlayer() && ((cPlayer *)TDI.Attacker)->IsGameModeCreative()) { Destroy(); TDI.FinalDamage = GetMaxHealth(); // Instant hit for creative @@ -1074,7 +1074,7 @@ void cRideableMinecart::OnRightClicked(cPlayer & a_Player) { super::OnRightClicked(a_Player); - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -1120,14 +1120,14 @@ void cMinecartWithChest::OnRightClicked(cPlayer & a_Player) { // If the window is not created, open it anew: cWindow * Window = GetWindow(); - if (Window == NULL) + if (Window == nullptr) { OpenNewWindow(); Window = GetWindow(); } // Open the window for the player: - if (Window != NULL) + if (Window != nullptr) { if (a_Player.GetWindow() != Window) { diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index 6b6ad36b5..40e22c641 100644 --- a/src/Entities/Minecart.h +++ b/src/Entities/Minecart.h @@ -127,7 +127,7 @@ public: ContentsWidth = 9, }; - const cItem & GetSlot(int a_Idx) const { return m_Contents.GetSlot(a_Idx); } + const cItem & GetSlot(int a_Idx) const { return m_Contents.GetSlot(a_Idx); } void SetSlot(size_t a_Idx, const cItem & a_Item) { m_Contents.SetSlot(a_Idx, a_Item); } protected: @@ -140,9 +140,9 @@ protected: { UNUSED(a_SlotNum); ASSERT(a_Grid == &m_Contents); - if (m_World != NULL) + if (m_World != nullptr) { - if (GetWindow() != NULL) + if (GetWindow() != nullptr) { GetWindow()->BroadcastWholeWindow(); } diff --git a/src/Entities/Painting.cpp b/src/Entities/Painting.cpp index e217556c7..1aa6da0a1 100644 --- a/src/Entities/Painting.cpp +++ b/src/Entities/Painting.cpp @@ -43,7 +43,7 @@ void cPainting::Tick(float a_Dt, cChunk & a_Chunk) void cPainting::GetDrops(cItems & a_Items, cEntity * a_Killer) { - if ((a_Killer != NULL) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) + if ((a_Killer != nullptr) && a_Killer->IsPlayer() && !((cPlayer *)a_Killer)->IsGameModeCreative()) { a_Items.push_back(cItem(E_ITEM_PAINTING)); } diff --git a/src/Entities/Painting.h b/src/Entities/Painting.h index 9877c95c5..078270b42 100644 --- a/src/Entities/Painting.h +++ b/src/Entities/Painting.h @@ -11,15 +11,22 @@ class cPainting : public cEntity { - // tolua_end typedef cEntity super; public: + + // tolua_end + CLASS_PROTODEF(cPainting) cPainting(const AString & a_Name, int a_Direction, double a_X, double a_Y, double a_Z); - const AString & GetName(void) const { return m_Name; } // tolua_export - int GetDirection(void) const { return m_Direction; } // tolua_export + + // tolua_begin + + const AString & GetName(void) const { return m_Name; } + int GetDirection(void) const { return m_Direction; } + + // tolua_end private: diff --git a/src/Entities/Pickup.cpp b/src/Entities/Pickup.cpp index 87b5bed07..e5e28446d 100644 --- a/src/Entities/Pickup.cpp +++ b/src/Entities/Pickup.cpp @@ -191,10 +191,8 @@ void cPickup::Tick(float a_Dt, cChunk & a_Chunk) -bool cPickup::CollectedBy(cPlayer * a_Dest) +bool cPickup::CollectedBy(cPlayer & a_Dest) { - ASSERT(a_Dest != NULL); - if (m_bCollected) { // LOG("Pickup %d cannot be collected by \"%s\", because it has already been collected.", m_UniqueID, a_Dest->GetName().c_str()); @@ -214,21 +212,21 @@ bool cPickup::CollectedBy(cPlayer * a_Dest) return false; } - int NumAdded = a_Dest->GetInventory().AddItem(m_Item); + int NumAdded = a_Dest.GetInventory().AddItem(m_Item); if (NumAdded > 0) { // Check achievements switch (m_Item.m_ItemType) { - case E_BLOCK_LOG: a_Dest->AwardAchievement(achMineWood); break; - case E_ITEM_LEATHER: a_Dest->AwardAchievement(achKillCow); break; - case E_ITEM_DIAMOND: a_Dest->AwardAchievement(achDiamonds); break; - case E_ITEM_BLAZE_ROD: a_Dest->AwardAchievement(achBlazeRod); break; + case E_BLOCK_LOG: a_Dest.AwardAchievement(achMineWood); break; + case E_ITEM_LEATHER: a_Dest.AwardAchievement(achKillCow); break; + case E_ITEM_DIAMOND: a_Dest.AwardAchievement(achDiamonds); break; + case E_ITEM_BLAZE_ROD: a_Dest.AwardAchievement(achBlazeRod); break; default: break; } m_Item.m_ItemCount -= NumAdded; - m_World->BroadcastCollectEntity(*this, *a_Dest); + m_World->BroadcastCollectEntity(*this, a_Dest); // Also send the "pop" sound effect with a somewhat random pitch (fast-random using EntityID ;) m_World->BroadcastSoundEffect("random.pop", GetPosX(), GetPosY(), GetPosZ(), 0.5, (float)(0.75 + ((float)((GetUniqueID() * 23) % 32)) / 64)); if (m_Item.m_ItemCount <= 0) diff --git a/src/Entities/Pickup.h b/src/Entities/Pickup.h index 4d5250819..d1176a7cf 100644 --- a/src/Entities/Pickup.h +++ b/src/Entities/Pickup.h @@ -19,7 +19,7 @@ class cPickup : public cEntity { typedef cEntity super; - + public: // tolua_end @@ -32,15 +32,15 @@ public: virtual void SpawnOn(cClientHandle & a_ClientHandle) override; - bool CollectedBy(cPlayer * a_Dest); // tolua_export + bool CollectedBy(cPlayer & a_Dest); // tolua_export virtual void Tick(float a_Dt, cChunk & a_Chunk) override; /** Returns the number of ticks that this entity has existed */ - int GetAge(void) const { return (int)(m_Timer / 50); } // tolua_export + int GetAge(void) const { return static_cast<int>(m_Timer / 50); } // tolua_export /** Set the number of ticks that this entity has existed */ - void SetAge(int a_Age) { m_Timer = (float)(a_Age * 50); } // tolua_export + void SetAge(int a_Age) { m_Timer = static_cast<float>(a_Age * 50); } // tolua_export /** Returns true if the pickup has already been collected */ bool IsCollected(void) const { return m_bCollected; } // tolua_export @@ -59,7 +59,3 @@ private: bool m_bIsPlayerCreated; }; // tolua_export - - - - diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index f58a0a016..5c18d8f96 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -20,7 +20,7 @@ #include "../WorldStorage/StatSerializer.h" #include "../CompositeChat.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" // 6000 ticks or 5 minutes @@ -56,8 +56,8 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_Stance(0.0), m_Inventory(*this), m_EnderChestContents(9, 3), - m_CurrentWindow(NULL), - m_InventoryWindow(NULL), + m_CurrentWindow(nullptr), + m_InventoryWindow(nullptr), m_GameMode(eGameMode_NotSet), m_IP(""), m_ClientHandle(a_Client), @@ -78,10 +78,10 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_IsChargingBow(false), m_BowCharge(0), m_FloaterID(-1), - m_Team(NULL), + m_Team(nullptr), m_TicksUntilNextSave(PLAYER_INVENTORY_SAVE_INTERVAL), m_bIsTeleporting(false), - m_UUID((a_Client != NULL) ? a_Client->GetUUID() : ""), + m_UUID((a_Client != nullptr) ? a_Client->GetUUID() : ""), m_CustomName("") { m_InventoryWindow = new cInventoryWindow(*this); @@ -96,7 +96,7 @@ cPlayer::cPlayer(cClientHandle* a_Client, const AString & a_PlayerName) : m_PlayerName = a_PlayerName; - cWorld * World = NULL; + cWorld * World = nullptr; if (!LoadFromDisk(World)) { m_Inventory.Clear(); @@ -144,10 +144,10 @@ cPlayer::~cPlayer(void) SaveToDisk(); - m_ClientHandle = NULL; + m_ClientHandle = nullptr; delete m_InventoryWindow; - m_InventoryWindow = NULL; + m_InventoryWindow = nullptr; LOGD("Player %p deleted", this); } @@ -186,12 +186,12 @@ void cPlayer::SpawnOn(cClientHandle & a_Client) void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { if (m_ClientHandle->IsDestroyed()) { // This should not happen, because destroying a client will remove it from the world, but just in case - m_ClientHandle = NULL; + m_ClientHandle = nullptr; return; } @@ -235,7 +235,6 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) CanMove = false; TeleportToCoords(m_LastPos.x, m_LastPos.y, m_LastPos.z); } - m_ClientHandle->StreamChunks(); } if (CanMove) @@ -245,7 +244,7 @@ void cPlayer::Tick(float a_Dt, cChunk & a_Chunk) if (m_Health > 0) // make sure player is alive { - m_World->CollectPickupsByPlayer(this); + m_World->CollectPickupsByPlayer(*this); if ((m_EatingFinishTick >= 0) && (m_EatingFinishTick <= m_World->GetWorldAge())) { @@ -504,7 +503,7 @@ void cPlayer::SetTouchGround(bool a_bTouchGround) if (Damage > 0) { // cPlayer makes sure damage isn't applied in creative, no need to check here - TakeDamage(dtFalling, NULL, Damage, Damage, 0); + TakeDamage(dtFalling, nullptr, Damage, Damage, 0); // Fall particles GetWorld()->BroadcastSoundParticleEffect(2006, POSX_TOINT, (int)GetPosY() - 1, POSZ_TOINT, Damage /* Used as particle effect speed modifier */); @@ -651,7 +650,7 @@ void cPlayer::AbortEating(void) void cPlayer::SendHealth(void) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { m_ClientHandle->SendHealth(); } @@ -663,7 +662,7 @@ void cPlayer::SendHealth(void) void cPlayer::SendExperience(void) { - if (m_ClientHandle != NULL) + if (m_ClientHandle != nullptr) { m_ClientHandle->SendExperience(); m_bDirtyExperience = false; @@ -859,11 +858,11 @@ bool cPlayer::DoTakeDamage(TakeDamageInfo & a_TDI) } } - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { cPlayer * Attacker = (cPlayer *)a_TDI.Attacker; - if ((m_Team != NULL) && (m_Team == Attacker->m_Team)) + if ((m_Team != nullptr) && (m_Team == Attacker->m_Team)) { if (!m_Team->AllowsFriendlyFire()) { @@ -915,7 +914,7 @@ void cPlayer::KilledBy(TakeDamageInfo & a_TDI) m_World->SpawnItemPickups(Pickups, GetPosX(), GetPosY(), GetPosZ(), 10); SaveToDisk(); // Save it, yeah the world is a tough place ! - if ((a_TDI.Attacker == NULL) && m_World->ShouldBroadcastDeathMessages()) + if ((a_TDI.Attacker == nullptr) && m_World->ShouldBroadcastDeathMessages()) { AString DamageText; switch (a_TDI.DamageType) @@ -941,7 +940,7 @@ void cPlayer::KilledBy(TakeDamageInfo & a_TDI) } GetWorld()->BroadcastChatDeath(Printf("%s %s", GetName().c_str(), DamageText.c_str())); } - else if (a_TDI.Attacker == NULL) // && !m_World->ShouldBroadcastDeathMessages() by fallthrough + else if (a_TDI.Attacker == nullptr) // && !m_World->ShouldBroadcastDeathMessages() by fallthrough { // no-op } @@ -997,7 +996,7 @@ void cPlayer::Killed(cEntity * a_Victim) void cPlayer::Respawn(void) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_Health = GetMaxHealth(); SetInvulnerableTicks(20); @@ -1107,9 +1106,9 @@ void cPlayer::SetTeam(cTeam * a_Team) cTeam * cPlayer::UpdateTeam(void) { - if (m_World == NULL) + if (m_World == nullptr) { - SetTeam(NULL); + SetTeam(nullptr); } else { @@ -1142,7 +1141,7 @@ void cPlayer::OpenWindow(cWindow * a_Window) void cPlayer::CloseWindow(bool a_CanRefuse) { - if (m_CurrentWindow == NULL) + if (m_CurrentWindow == nullptr) { m_CurrentWindow = m_InventoryWindow; return; @@ -1167,7 +1166,7 @@ void cPlayer::CloseWindow(bool a_CanRefuse) void cPlayer::CloseWindowIfID(char a_WindowID, bool a_CanRefuse) { - if ((m_CurrentWindow == NULL) || (m_CurrentWindow->GetWindowID() != a_WindowID)) + if ((m_CurrentWindow == nullptr) || (m_CurrentWindow->GetWindowID() != a_WindowID)) { return; } @@ -1354,7 +1353,7 @@ void cPlayer::MoveTo( const Vector3d & a_NewPos) // Y = -999 and X, Z = attempting to create speed, usually up to 0.03 // We cannot test m_AttachedTo, because when deattaching, the server thinks the client is already deattached while // the client may still send more of these nonsensical packets. - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { Vector3d AddSpeed(a_NewPos); AddSpeed.y = 0; @@ -1581,7 +1580,7 @@ void cPlayer::TossItems(const cItems & a_Items) bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) { - ASSERT(a_World != NULL); + ASSERT(a_World != nullptr); if (GetWorld() == a_World) { @@ -1590,7 +1589,7 @@ bool cPlayer::DoMoveToWorld(cWorld * a_World, bool a_ShouldSendRespawn) } // Send the respawn packet: - if (a_ShouldSendRespawn && (m_ClientHandle != NULL)) + if (a_ShouldSendRespawn && (m_ClientHandle != nullptr)) { m_ClientHandle->SendRespawn(a_World->GetDimension()); } @@ -1652,7 +1651,7 @@ bool cPlayer::LoadFromDisk(cWorldPtr & a_World) GetName().c_str(), m_UUID.c_str(), OfflineUUID.c_str(), OfflineUsage ); - if (a_World == NULL) + if (a_World == nullptr) { a_World = cRoot::Get()->GetDefaultWorld(); } @@ -1729,7 +1728,7 @@ bool cPlayer::LoadFromFile(const AString & a_FileName, cWorldPtr & a_World) m_LoadedWorldName = root.get("world", "world").asString(); a_World = cRoot::Get()->GetWorld(GetLoadedWorldName(), false); - if (a_World == NULL) + if (a_World == nullptr) { a_World = cRoot::Get()->GetDefaultWorld(); } @@ -1795,7 +1794,7 @@ bool cPlayer::SaveToDisk() root["SpawnY"] = GetLastBedPos().y; root["SpawnZ"] = GetLastBedPos().z; - if (m_World != NULL) + if (m_World != nullptr) { root["world"] = m_World->GetName(); if (m_GameMode == m_World->GetGameMode()) @@ -1949,7 +1948,7 @@ void cPlayer::HandleFood(void) else if ((m_FoodLevel <= 0) && (m_Health > 1)) { // Damage from starving - TakeDamage(dtStarving, NULL, 1, 1, 0); + TakeDamage(dtStarving, nullptr, 1, 1, 0); } } } @@ -2018,7 +2017,7 @@ void cPlayer::UpdateMovementStats(const Vector3d & a_DeltaPos) { StatValue Value = (StatValue)floor(a_DeltaPos.Length() * 100 + 0.5); - if (m_AttachedTo == NULL) + if (m_AttachedTo == nullptr) { if (IsClimbing()) { @@ -2091,7 +2090,7 @@ void cPlayer::ApplyFoodExhaustionFromMovement() } // If riding anything, apply no food exhaustion - if (m_AttachedTo != NULL) + if (m_AttachedTo != nullptr) { return; } @@ -2134,19 +2133,19 @@ void cPlayer::ApplyFoodExhaustionFromMovement() void cPlayer::LoadRank(void) { // Load the values from cRankManager: - cRankManager & RankMgr = cRoot::Get()->GetRankManager(); - m_Rank = RankMgr.GetPlayerRankName(m_UUID); + cRankManager * RankMgr = cRoot::Get()->GetRankManager(); + m_Rank = RankMgr->GetPlayerRankName(m_UUID); if (m_Rank.empty()) { - m_Rank = RankMgr.GetDefaultRank(); + m_Rank = RankMgr->GetDefaultRank(); } else { // Update the name: - RankMgr.UpdatePlayerName(m_UUID, m_PlayerName); + RankMgr->UpdatePlayerName(m_UUID, m_PlayerName); } - m_Permissions = RankMgr.GetPlayerPermissions(m_UUID); - RankMgr.GetRankVisuals(m_Rank, m_MsgPrefix, m_MsgSuffix, m_MsgNameColorCode); + m_Permissions = RankMgr->GetPlayerPermissions(m_UUID); + RankMgr->GetRankVisuals(m_Rank, m_MsgPrefix, m_MsgSuffix, m_MsgNameColorCode); // Break up the individual permissions on each dot, into m_SplitPermissions: m_SplitPermissions.clear(); diff --git a/src/Entities/Player.h b/src/Entities/Player.h index 22d6a2ae2..4bb51b556 100644 --- a/src/Entities/Player.h +++ b/src/Entities/Player.h @@ -176,10 +176,10 @@ public: AString GetIP(void) const { return m_IP; } // tolua_export - /** Returns the associated team, NULL if none */ + /** Returns the associated team, nullptr if none */ cTeam * GetTeam(void) { return m_Team; } // tolua_export - /** Sets the player team, NULL if none */ + /** Sets the player team, nullptr if none */ void SetTeam(cTeam * a_Team); // tolua_end diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp index acc9bd674..1768714f8 100644 --- a/src/Entities/ProjectileEntity.cpp +++ b/src/Entities/ProjectileEntity.cpp @@ -135,7 +135,7 @@ public: m_Pos(a_Pos), m_NextPos(a_NextPos), m_MinCoeff(1), - m_HitEntity(NULL) + m_HitEntity(nullptr) { } @@ -221,9 +221,9 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a super(etProjectile, a_X, a_Y, a_Z, a_Width, a_Height), m_ProjectileKind(a_Kind), m_CreatorData( - ((a_Creator != NULL) ? a_Creator->GetUniqueID() : -1), - ((a_Creator != NULL) ? (a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "") : ""), - ((a_Creator != NULL) ? a_Creator->GetEquippedWeapon().m_Enchantments : cEnchantments()) + ((a_Creator != nullptr) ? a_Creator->GetUniqueID() : -1), + ((a_Creator != nullptr) ? (a_Creator->IsPlayer() ? ((cPlayer *)a_Creator)->GetName() : "") : ""), + ((a_Creator != nullptr) ? a_Creator->GetEquippedWeapon().m_Enchantments : cEnchantments()) ), m_IsInGround(false) { @@ -251,7 +251,7 @@ cProjectileEntity::cProjectileEntity(eKind a_Kind, cEntity * a_Creator, const Ve cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed) { Vector3d Speed; - if (a_Speed != NULL) + if (a_Speed != nullptr) { Speed = *a_Speed; } @@ -269,10 +269,10 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, case pkWitherSkull: return new cWitherSkullEntity (a_Creator, a_X, a_Y, a_Z, Speed); case pkFirework: { - ASSERT(a_Item != NULL); + ASSERT(a_Item != nullptr); if (a_Item->m_FireworkItem.m_Colours.empty()) { - return NULL; + return nullptr; } return new cFireworkEntity(a_Creator, a_X, a_Y, a_Z, *a_Item); @@ -280,7 +280,7 @@ cProjectileEntity * cProjectileEntity::Create(eKind a_Kind, cEntity * a_Creator, } LOGWARNING("%s: Unknown projectile kind: %d", __FUNCTION__, a_Kind); - return NULL; + return nullptr; } @@ -424,8 +424,12 @@ void cProjectileEntity::SpawnOn(cClientHandle & a_Client) -void cProjectileEntity::CollectedBy(cPlayer * a_Dest) +void cProjectileEntity::CollectedBy(cPlayer & a_Dest) { // Overriden in arrow UNUSED(a_Dest); } + + + + diff --git a/src/Entities/ProjectileEntity.h b/src/Entities/ProjectileEntity.h index 990136a32..2a98e31c7 100644 --- a/src/Entities/ProjectileEntity.h +++ b/src/Entities/ProjectileEntity.h @@ -1,7 +1,7 @@ // ProjectileEntity.h -// Declares the cProjectileEntity class representing the common base class for projectiles, as well as individual projectile types +// Declares the cProjectileEntity class representing the common base class for projectiles @@ -23,7 +23,7 @@ class cProjectileEntity : typedef cEntity super; public: - /// The kind of the projectile. The numbers correspond to the network type ID used for spawning via the 0x17 packet. + /** The kind of the projectile. The numbers correspond to the network type ID used for spawning them in the protocol. */ enum eKind { pkArrow = 60, @@ -46,24 +46,24 @@ public: cProjectileEntity(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, double a_Width, double a_Height); cProjectileEntity(eKind a_Kind, cEntity * a_Creator, const Vector3d & a_Pos, const Vector3d & a_Speed, double a_Width, double a_Height); - static cProjectileEntity * Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed = NULL); + static cProjectileEntity * Create(eKind a_Kind, cEntity * a_Creator, double a_X, double a_Y, double a_Z, const cItem * a_Item, const Vector3d * a_Speed = nullptr); - /// Called by the physics blocktracer when the entity hits a solid block, the hit position and the face hit (BLOCK_FACE_) is given + /** Called by the physics blocktracer when the entity hits a solid block, the hit position and the face hit (BLOCK_FACE_) is given */ virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace); - /// Called by the physics blocktracer when the entity hits another entity + /** Called by the physics blocktracer when the entity hits another entity */ virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) { UNUSED(a_EntityHit); UNUSED(a_HitPos); } - /// Called by Chunk when the projectile is eligible for player collection - virtual void CollectedBy(cPlayer * a_Dest); + /** Called by Chunk when the projectile is eligible for player collection */ + virtual void CollectedBy(cPlayer & a_Dest); // tolua_begin - /// Returns the kind of the projectile (fast class identification) + /** Returns the kind of the projectile (fast class identification) */ eKind GetProjectileKind(void) const { return m_ProjectileKind; } /** Returns the unique ID of the entity who created this projectile @@ -76,15 +76,15 @@ public: */ AString GetCreatorName(void) const { return m_CreatorData.m_Name; } - /// Returns the string that is used as the entity type (class name) in MCA files + /** Returns the string that is used as the entity type (class name) in MCA files */ AString GetMCAClassName(void) const; - /// Returns true if the projectile has hit the ground and is stuck there + /** Returns true if the projectile has hit the ground and is stuck there */ bool IsInGround(void) const { return m_IsInGround; } // tolua_end - /// Sets the internal InGround flag. To be used by MCA loader only! + /** Sets the internal InGround flag. To be used by MCA loader only! */ void SetIsInGround(bool a_IsInGround) { m_IsInGround = a_IsInGround; } protected: @@ -110,11 +110,11 @@ protected: eKind m_ProjectileKind; /** The structure for containing the entity ID and name who has created this projectile - The ID and/or name may be NULL (e.g. for dispensers/mobs) + The ID and/or name may be nullptr (e.g. for dispensers/mobs) */ CreatorData m_CreatorData; - /// True if the projectile has hit the ground and is stuck there + /** True if the projectile has hit the ground and is stuck there */ bool m_IsInGround; // cEntity overrides: diff --git a/src/Entities/SplashPotionEntity.h b/src/Entities/SplashPotionEntity.h index 4afc5f204..9302d8292 100644 --- a/src/Entities/SplashPotionEntity.h +++ b/src/Entities/SplashPotionEntity.h @@ -1,6 +1,11 @@ -// -// SplashPotionEntity.h -// + +// SplashPotionEntity.h + +// Declares the cSplashPotionEntity class representing a splash potion that has been thrown + + + + #pragma once @@ -32,6 +37,7 @@ public: const cItem & a_Item ); + // tolua_begin cEntityEffect::eType GetEntityEffectType(void) const { return m_EntityEffectType; } cEntityEffect GetEntityEffect(void) const { return m_EntityEffect; } int GetPotionColor(void) const { return m_PotionColor; } @@ -39,6 +45,8 @@ public: void SetEntityEffectType(cEntityEffect::eType a_EntityEffectType) { m_EntityEffectType = a_EntityEffectType; } void SetEntityEffect(cEntityEffect a_EntityEffect) { m_EntityEffect = a_EntityEffect; } void SetPotionColor(int a_PotionColor) { m_PotionColor = a_PotionColor; } + + // tolua_end protected: @@ -77,3 +85,7 @@ private: /** Time in ticks to wait for the hit animation to begin before destroying */ int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownEggEntity.cpp b/src/Entities/ThrownEggEntity.cpp index 5ae85bee8..24c946a9c 100644 --- a/src/Entities/ThrownEggEntity.cpp +++ b/src/Entities/ThrownEggEntity.cpp @@ -44,6 +44,27 @@ void cThrownEggEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_Hit +void cThrownEggEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + + void cThrownEggEntity::TrySpawnChicken(const Vector3d & a_HitPos) { if (m_World->GetTickRandomNumber(7) == 1) diff --git a/src/Entities/ThrownEggEntity.h b/src/Entities/ThrownEggEntity.h index a0b7d5340..6ffedf5b5 100644 --- a/src/Entities/ThrownEggEntity.h +++ b/src/Entities/ThrownEggEntity.h @@ -1,6 +1,11 @@ -// -// ThrownEggEntity.h -// + +// ThrownEggEntity.h + +// Declares the cThrownEggEntity class representing a regular thrown egg + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; // Randomly decides whether to spawn a chicken where the egg lands. void TrySpawnChicken(const Vector3d & a_HitPos); @@ -56,3 +46,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownEnderPearlEntity.cpp b/src/Entities/ThrownEnderPearlEntity.cpp index c7407e6ae..8f1b62934 100644 --- a/src/Entities/ThrownEnderPearlEntity.cpp +++ b/src/Entities/ThrownEnderPearlEntity.cpp @@ -1,3 +1,4 @@ + #include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules #include "ThrownEnderPearlEntity.h" @@ -45,6 +46,27 @@ void cThrownEnderPearlEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d +void cThrownEnderPearlEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + + void cThrownEnderPearlEntity::TeleportCreator(const Vector3d & a_HitPos) { if (m_CreatorData.m_Name.empty()) diff --git a/src/Entities/ThrownEnderPearlEntity.h b/src/Entities/ThrownEnderPearlEntity.h index 436450013..475ebde87 100644 --- a/src/Entities/ThrownEnderPearlEntity.h +++ b/src/Entities/ThrownEnderPearlEntity.h @@ -1,6 +1,11 @@ -// -// ThrownEnderPearlEntity.h -// + +// ThrownEnderPearlEntity.h + +// Declares the cThrownEnderPeralEntity class representing an ender pearl being thrown + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; /** Teleports the creator where the ender pearl lands */ void TeleportCreator(const Vector3d & a_HitPos); @@ -56,3 +46,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/ThrownSnowballEntity.cpp b/src/Entities/ThrownSnowballEntity.cpp index 496397100..88e39d22e 100644 --- a/src/Entities/ThrownSnowballEntity.cpp +++ b/src/Entities/ThrownSnowballEntity.cpp @@ -43,3 +43,28 @@ void cThrownSnowballEntity::OnHitEntity(cEntity & a_EntityHit, const Vector3d & m_DestroyTimer = 5; } + + + + + +void cThrownSnowballEntity::Tick(float a_Dt, cChunk & a_Chunk) +{ + if (m_DestroyTimer > 0) + { + m_DestroyTimer--; + if (m_DestroyTimer == 0) + { + Destroy(); + return; + } + } + else + { + super::Tick(a_Dt, a_Chunk); + } +} + + + + diff --git a/src/Entities/ThrownSnowballEntity.h b/src/Entities/ThrownSnowballEntity.h index 8d195ced1..f806996cc 100644 --- a/src/Entities/ThrownSnowballEntity.h +++ b/src/Entities/ThrownSnowballEntity.h @@ -1,6 +1,11 @@ -// -// ThrownSnowballEntity.h -// + +// ThrownSnowballEntity.h + +// Declares the cThrownSnowballEntity representing a snowball that has been thrown + + + + #pragma once @@ -29,23 +34,8 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; - virtual void Tick (float a_Dt, cChunk & a_Chunk) override - { - if (m_DestroyTimer > 0) - { - m_DestroyTimer--; - if (m_DestroyTimer == 0) - { - Destroy(); - return; - } - } - else - { - super::Tick(a_Dt, a_Chunk); - } - } + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void Tick(float a_Dt, cChunk & a_Chunk) override; private: @@ -53,3 +43,7 @@ private: int m_DestroyTimer; } ; // tolua_export + + + + diff --git a/src/Entities/WitherSkullEntity.h b/src/Entities/WitherSkullEntity.h index c59acd807..43a520388 100644 --- a/src/Entities/WitherSkullEntity.h +++ b/src/Entities/WitherSkullEntity.h @@ -1,8 +1,12 @@ -// WitherSkullEntity.h +// WitherSkullEntity.h // Declares the cWitherSkullEntity class representing the entity used by both blue and black wither skulls + + + + #pragma once #include "ProjectileEntity.h" @@ -30,6 +34,10 @@ protected: // cProjectileEntity overrides: virtual void OnHitSolidBlock(const Vector3d & a_HitPos, eBlockFace a_HitFace) override; - virtual void OnHitEntity (cEntity & a_EntityHit, const Vector3d & a_HitPos) override; + virtual void OnHitEntity(cEntity & a_EntityHit, const Vector3d & a_HitPos) override; } ; // tolua_export + + + + diff --git a/src/FurnaceRecipe.cpp b/src/FurnaceRecipe.cpp index d200ef3d7..9b3b2ecbe 100644 --- a/src/FurnaceRecipe.cpp +++ b/src/FurnaceRecipe.cpp @@ -43,7 +43,7 @@ cFurnaceRecipe::~cFurnaceRecipe() { ClearRecipes(); delete m_pState; - m_pState = NULL; + m_pState = nullptr; } @@ -247,9 +247,9 @@ void cFurnaceRecipe::ClearRecipes(void) { cRecipe Recipe = *itr; delete Recipe.In; - Recipe.In = NULL; + Recipe.In = nullptr; delete Recipe.Out; - Recipe.Out = NULL; + Recipe.Out = nullptr; } m_pState->Recipes.clear(); @@ -257,7 +257,7 @@ void cFurnaceRecipe::ClearRecipes(void) { cFuel Fuel = *itr; delete Fuel.In; - Fuel.In = NULL; + Fuel.In = nullptr; } m_pState->Fuel.clear(); } diff --git a/src/FurnaceRecipe.h b/src/FurnaceRecipe.h index 6a1650695..936ef706d 100644 --- a/src/FurnaceRecipe.h +++ b/src/FurnaceRecipe.h @@ -32,7 +32,7 @@ public: int CookTime; ///< How long this recipe takes to smelt, in ticks }; - /** Returns a recipe for the specified input, NULL if no recipe found */ + /** Returns a recipe for the specified input, nullptr if no recipe found */ const cRecipe * GetRecipeFrom(const cItem & a_Ingredient) const; /** Returns the amount of time that the specified fuel burns, in ticks */ diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 8924a7999..2a4dbe794 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -5,7 +5,11 @@ #include "Globals.h" #include "BioGen.h" -#include "inifile/iniFile.h" +#include <chrono> +#include <iostream> +#include "IntGen.h" +#include "ProtIntGen.h" +#include "../IniFile.h" #include "../LinearUpscale.h" @@ -45,7 +49,7 @@ void cBioGenConstant::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cBioGenCache: -cBioGenCache::cBioGenCache(cBiomeGen * a_BioGenToCache, int a_CacheSize) : +cBioGenCache::cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize) : m_BioGenToCache(a_BioGenToCache), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -69,9 +73,9 @@ cBioGenCache::cBioGenCache(cBiomeGen * a_BioGenToCache, int a_CacheSize) : cBioGenCache::~cBioGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } @@ -145,25 +149,13 @@ void cBioGenCache::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cBioGenMulticache: -cBioGenMulticache::cBioGenMulticache(cBiomeGen * a_BioGenToCache, size_t a_CacheSize, size_t a_CachesLength) : - m_CachesLength(a_CachesLength) +cBioGenMulticache::cBioGenMulticache(cBiomeGenPtr a_BioGenToCache, size_t a_SubCacheSize, size_t a_NumSubCaches) : + m_NumSubCaches(a_NumSubCaches) { - m_Caches.reserve(a_CachesLength); - for (size_t i = 0; i < a_CachesLength; i++) + m_Caches.reserve(a_NumSubCaches); + for (size_t i = 0; i < a_NumSubCaches; i++) { - m_Caches.push_back(new cBioGenCache(a_BioGenToCache, a_CacheSize)); - } -} - - - - - -cBioGenMulticache::~cBioGenMulticache() -{ - for (cBiomeGens::iterator it = m_Caches.begin(); it != m_Caches.end(); it++) - { - delete *it; + m_Caches.push_back(cBiomeGenPtr(new cBioGenCache(a_BioGenToCache, a_SubCacheSize))); } } @@ -174,7 +166,7 @@ cBioGenMulticache::~cBioGenMulticache() void cBioGenMulticache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { const size_t coefficient = 3; - const size_t cacheIdx = ((size_t)a_ChunkX + coefficient * (size_t)a_ChunkZ) % m_CachesLength; + const size_t cacheIdx = ((size_t)a_ChunkX + coefficient * (size_t)a_ChunkZ) % m_NumSubCaches; m_Caches[cacheIdx]->GenBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } @@ -185,10 +177,9 @@ void cBioGenMulticache::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMa void cBioGenMulticache::InitializeBiomeGen(cIniFile & a_IniFile) { - for (cBiomeGens::iterator it = m_Caches.begin(); it != m_Caches.end(); it++) + for (auto itr : m_Caches) { - cBiomeGen * tmp = *it; - tmp->InitializeBiomeGen(a_IniFile); + itr->InitializeBiomeGen(a_IniFile); } } @@ -760,8 +751,8 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap int DistortZ[cChunkDef::Width + 1][cChunkDef::Width + 1]; for (int x = 0; x <= 4; x++) for (int z = 0; z <= 4; z++) { - float BlockX = BaseX + x * 4; - float BlockZ = BaseZ + z * 4; + float BlockX = static_cast<float>(BaseX + x * 4); + float BlockZ = static_cast<float>(BaseZ + z * 4); double NoiseX = m_AmpX1 * m_Noise1.CubicNoise2D(BlockX * m_FreqX1, BlockZ * m_FreqX1); NoiseX += m_AmpX2 * m_Noise2.CubicNoise2D(BlockX * m_FreqX2, BlockZ * m_FreqX2); NoiseX += m_AmpX3 * m_Noise3.CubicNoise2D(BlockX * m_FreqX3, BlockZ * m_FreqX3); @@ -785,7 +776,7 @@ void cBioGenTwoLevel::GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap int BiomeGroup = m_VoronoiLarge.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 7; int BiomeIdx = m_VoronoiSmall.GetValueAt(DistortX[x][z], DistortZ[x][z], SeedX, SeedZ, MinDist2) / 11; int MinDist1 = (DistortX[x][z] - SeedX) * (DistortX[x][z] - SeedX) + (DistortZ[x][z] - SeedZ) * (DistortZ[x][z] - SeedZ); - cChunkDef::SetBiome(a_BiomeMap, x, z, SelectBiome(BiomeGroup, BiomeIdx, (MinDist1 < MinDist2 / 4) ? 0 : 1)); + cChunkDef::SetBiome(a_BiomeMap, x, z, SelectBiome(BiomeGroup, BiomeIdx, (MinDist1 < MinDist2 / 4) ? 1 : 0)); } } } @@ -930,9 +921,217 @@ void cBioGenTwoLevel::InitializeBiomeGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// +// cBioGenGrown: + +class cBioGenGrown: + public cBiomeGen +{ +public: + cBioGenGrown(int a_Seed) + { + auto FinalRivers = + std::make_shared<cIntGenSmooth<8>> (a_Seed + 1, + std::make_shared<cIntGenZoom <10>> (a_Seed + 2, + std::make_shared<cIntGenRiver <7>> (a_Seed + 3, + std::make_shared<cIntGenZoom <9>> (a_Seed + 4, + std::make_shared<cIntGenSmooth<6>> (a_Seed + 5, + std::make_shared<cIntGenZoom <8>> (a_Seed + 8, + std::make_shared<cIntGenSmooth<6>> (a_Seed + 5, + std::make_shared<cIntGenZoom <8>> (a_Seed + 9, + std::make_shared<cIntGenSmooth<6>> (a_Seed + 5, + std::make_shared<cIntGenZoom <8>> (a_Seed + 10, + std::make_shared<cIntGenSmooth<6>> (a_Seed + 5, + std::make_shared<cIntGenSmooth<8>> (a_Seed + 6, + std::make_shared<cIntGenZoom <10>> (a_Seed + 11, + std::make_shared<cIntGenChoice<2, 7>>(a_Seed + 12 + )))))))))))))); + + auto alteration = + std::make_shared<cIntGenZoom <8>>(a_Seed, + std::make_shared<cIntGenLandOcean<6>>(a_Seed, 20 + )); + + auto alteration2 = + std::make_shared<cIntGenZoom <8>>(a_Seed + 1, + std::make_shared<cIntGenZoom <6>>(a_Seed + 2, + std::make_shared<cIntGenZoom <5>>(a_Seed + 1, + std::make_shared<cIntGenZoom <4>>(a_Seed + 2, + std::make_shared<cIntGenLandOcean<4>>(a_Seed + 1, 10 + ))))); + + auto FinalBiomes = + std::make_shared<cIntGenSmooth <8>> (a_Seed + 1, + std::make_shared<cIntGenZoom <10>>(a_Seed + 15, + std::make_shared<cIntGenSmooth <7>> (a_Seed + 1, + std::make_shared<cIntGenZoom <9>> (a_Seed + 16, + std::make_shared<cIntGenBeaches <6>> ( + std::make_shared<cIntGenZoom <8>> (a_Seed + 1, + std::make_shared<cIntGenAddIslands <6>> (a_Seed + 2004, 10, + std::make_shared<cIntGenAddToOcean <6>> (a_Seed + 10, 500, biDeepOcean, + std::make_shared<cIntGenReplaceRandomly<8>> (a_Seed + 1, biPlains, biSunflowerPlains, 20, + std::make_shared<cIntGenMBiomes <8>> (a_Seed + 5, alteration2, + std::make_shared<cIntGenAlternateBiomes<8>> (a_Seed + 1, alteration, + std::make_shared<cIntGenBiomeEdges <8>> (a_Seed + 3, + std::make_shared<cIntGenZoom <10>>(a_Seed + 2, + std::make_shared<cIntGenZoom <7>> (a_Seed + 4, + std::make_shared<cIntGenReplaceRandomly<5>> (a_Seed + 99, biIcePlains, biIcePlainsSpikes, 50, + std::make_shared<cIntGenZoom <5>> (a_Seed + 8, + std::make_shared<cIntGenAddToOcean <4>> (a_Seed + 10, 300, biDeepOcean, + std::make_shared<cIntGenAddToOcean <6>> (a_Seed + 9, 8, biMushroomIsland, + std::make_shared<cIntGenBiomes <8>> (a_Seed + 3000, + std::make_shared<cIntGenAddIslands <8>> (a_Seed + 2000, 200, + std::make_shared<cIntGenZoom <8>> (a_Seed + 5, + std::make_shared<cIntGenRareBiomeGroups<6>> (a_Seed + 5, 50, + std::make_shared<cIntGenBiomeGroupEdges<6>> ( + std::make_shared<cIntGenAddIslands <8>> (a_Seed + 2000, 200, + std::make_shared<cIntGenZoom <8>> (a_Seed + 7, + std::make_shared<cIntGenSetRandomly <6>> (a_Seed + 8, 50, bgOcean, + std::make_shared<cIntGenReplaceRandomly<6>> (a_Seed + 101, bgIce, bgTemperate, 150, + std::make_shared<cIntGenAddIslands <6>> (a_Seed + 2000, 200, + std::make_shared<cIntGenSetRandomly <6>> (a_Seed + 9, 50, bgOcean, + std::make_shared<cIntGenZoom <6>> (a_Seed + 10, + std::make_shared<cIntGenLandOcean <5>> (a_Seed + 100, 30 + ))))))))))))))))))))))))))))))); + + m_Gen = + std::make_shared<cIntGenSmooth <16>>(a_Seed, + std::make_shared<cIntGenZoom <18>>(a_Seed, + std::make_shared<cIntGenSmooth <11>>(a_Seed, + std::make_shared<cIntGenZoom <13>>(a_Seed, + std::make_shared<cIntGenMixRivers<8>> ( + FinalBiomes, FinalRivers + ))))); + } + + virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override + { + cIntGen<16, 16>::Values vals; + m_Gen->GetInts(a_ChunkX * cChunkDef::Width, a_ChunkZ * cChunkDef::Width, vals); + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + cChunkDef::SetBiome(a_Biomes, x, z, (EMCSBiome)vals[x + cChunkDef::Width * z]); + } + } + } + +protected: + std::shared_ptr<cIntGen<16, 16>> m_Gen; +}; + + + + + +//////////////////////////////////////////////////////////////////////////////// +// cBioGenGrown: + +class cBioGenProtGrown: + public cBiomeGen +{ +public: + cBioGenProtGrown(int a_Seed) + { + auto FinalRivers = + std::make_shared<cProtIntGenSmooth>(a_Seed + 1, + std::make_shared<cProtIntGenZoom >(a_Seed + 2, + std::make_shared<cProtIntGenRiver >(a_Seed + 3, + std::make_shared<cProtIntGenZoom >(a_Seed + 4, + std::make_shared<cProtIntGenSmooth>(a_Seed + 5, + std::make_shared<cProtIntGenZoom >(a_Seed + 8, + std::make_shared<cProtIntGenSmooth>(a_Seed + 5, + std::make_shared<cProtIntGenZoom >(a_Seed + 9, + std::make_shared<cProtIntGenSmooth>(a_Seed + 5, + std::make_shared<cProtIntGenZoom >(a_Seed + 10, + std::make_shared<cProtIntGenSmooth>(a_Seed + 5, + std::make_shared<cProtIntGenSmooth>(a_Seed + 6, + std::make_shared<cProtIntGenZoom >(a_Seed + 11, + std::make_shared<cProtIntGenChoice>(a_Seed + 12, 2 + )))))))))))))); + + auto alteration = + std::make_shared<cProtIntGenZoom >(a_Seed, + std::make_shared<cProtIntGenLandOcean>(a_Seed, 20 + )); + + auto alteration2 = + std::make_shared<cProtIntGenZoom >(a_Seed + 1, + std::make_shared<cProtIntGenZoom >(a_Seed + 2, + std::make_shared<cProtIntGenZoom >(a_Seed + 1, + std::make_shared<cProtIntGenZoom >(a_Seed + 2, + std::make_shared<cProtIntGenLandOcean>(a_Seed + 1, 10 + ))))); + + auto FinalBiomes = + std::make_shared<cProtIntGenSmooth >(a_Seed + 1, + std::make_shared<cProtIntGenZoom >(a_Seed + 15, + std::make_shared<cProtIntGenSmooth >(a_Seed + 1, + std::make_shared<cProtIntGenZoom >(a_Seed + 16, + std::make_shared<cProtIntGenBeaches >( + std::make_shared<cProtIntGenZoom >(a_Seed + 1, + std::make_shared<cProtIntGenAddIslands >(a_Seed + 2004, 10, + std::make_shared<cProtIntGenAddToOcean >(a_Seed + 10, 500, biDeepOcean, + std::make_shared<cProtIntGenReplaceRandomly>(a_Seed + 1, biPlains, biSunflowerPlains, 20, + std::make_shared<cProtIntGenMBiomes >(a_Seed + 5, alteration2, + std::make_shared<cProtIntGenAlternateBiomes>(a_Seed + 1, alteration, + std::make_shared<cProtIntGenBiomeEdges >(a_Seed + 3, + std::make_shared<cProtIntGenZoom >(a_Seed + 2, + std::make_shared<cProtIntGenZoom >(a_Seed + 4, + std::make_shared<cProtIntGenReplaceRandomly>(a_Seed + 99, biIcePlains, biIcePlainsSpikes, 50, + std::make_shared<cProtIntGenZoom >(a_Seed + 8, + std::make_shared<cProtIntGenAddToOcean >(a_Seed + 10, 300, biDeepOcean, + std::make_shared<cProtIntGenAddToOcean >(a_Seed + 9, 8, biMushroomIsland, + std::make_shared<cProtIntGenBiomes >(a_Seed + 3000, + std::make_shared<cProtIntGenAddIslands >(a_Seed + 2000, 200, + std::make_shared<cProtIntGenZoom >(a_Seed + 5, + std::make_shared<cProtIntGenRareBiomeGroups>(a_Seed + 5, 50, + std::make_shared<cProtIntGenBiomeGroupEdges>( + std::make_shared<cProtIntGenAddIslands >(a_Seed + 2000, 200, + std::make_shared<cProtIntGenZoom >(a_Seed + 7, + std::make_shared<cProtIntGenSetRandomly >(a_Seed + 8, 50, bgOcean, + std::make_shared<cProtIntGenReplaceRandomly>(a_Seed + 101, bgIce, bgTemperate, 150, + std::make_shared<cProtIntGenAddIslands >(a_Seed + 2000, 200, + std::make_shared<cProtIntGenSetRandomly >(a_Seed + 9, 50, bgOcean, + std::make_shared<cProtIntGenZoom >(a_Seed + 10, + std::make_shared<cProtIntGenLandOcean >(a_Seed + 100, 30 + ))))))))))))))))))))))))))))))); + + m_Gen = + std::make_shared<cProtIntGenSmooth >(a_Seed, + std::make_shared<cProtIntGenZoom >(a_Seed, + std::make_shared<cProtIntGenSmooth >(a_Seed, + std::make_shared<cProtIntGenZoom >(a_Seed, + std::make_shared<cProtIntGenMixRivers>( + FinalBiomes, FinalRivers + ))))); + } + + virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_Biomes) override + { + int vals[16 * 16]; + m_Gen->GetInts(a_ChunkX * cChunkDef::Width, a_ChunkZ * cChunkDef::Width, 16, 16, vals); + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + cChunkDef::SetBiome(a_Biomes, x, z, (EMCSBiome)vals[x + cChunkDef::Width * z]); + } + } + } + +protected: + std::shared_ptr<cProtIntGen> m_Gen; +}; + + + + + +//////////////////////////////////////////////////////////////////////////////// // cBiomeGen: -cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault) +cBiomeGenPtr cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault) { AString BiomeGenName = a_IniFile.GetValueSet("Generator", "BiomeGen", ""); if (BiomeGenName.empty()) @@ -941,7 +1140,7 @@ cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a BiomeGenName = "MultiStepMap"; } - cBiomeGen * res = NULL; + cBiomeGen * res = nullptr; a_CacheOffByDefault = false; if (NoCaseCompare(BiomeGenName, "constant") == 0) { @@ -965,6 +1164,14 @@ cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a { res = new cBioGenTwoLevel(a_Seed); } + else if (NoCaseCompare(BiomeGenName, "grown") == 0) + { + res = new cBioGenGrown(a_Seed); + } + else if (NoCaseCompare(BiomeGenName, "grownprot") == 0) + { + res = new cBioGenProtGrown(a_Seed); + } else { if (NoCaseCompare(BiomeGenName, "multistepmap") != 0) @@ -988,9 +1195,57 @@ cBiomeGen * cBiomeGen::CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a } res->InitializeBiomeGen(a_IniFile); - return res; + return cBiomeGenPtr(res); } + +//////////////////////////////////////////////////////////////////////////////// +// Performance tests: + +// Change to 1 to enable the perf test: +#if 0 + +class cBioGenPerfTest +{ +public: + cBioGenPerfTest() + { + std::cout << "BioGen performance tests commencing, please wait..." << std::endl; + TestGen("MultiStepMap", std::make_unique<cBioGenMultiStepMap>(1).get()); + TestGen("Grown", std::make_unique<cBioGenGrown>(1).get()); + TestGen("GrownProt", std::make_unique<cBioGenProtGrown>(1).get()); + std::cout << "BioGen performance tests complete." << std::endl; + } + +protected: + void TestGen(const AString && a_GenName, cBiomeGen * a_BioGen) + { + // Initialize the default settings for the generator: + cIniFile iniFile; + a_BioGen->InitializeBiomeGen(iniFile); + + // Generate the biomes: + auto start = std::chrono::system_clock::now(); + for (int z = 0; z < 100; z++) + { + for (int x = 0; x < 100; x++) + { + cChunkDef::BiomeMap biomes; + a_BioGen->GenBiomes(x, z, biomes); + } // for x + } // for z + auto dur = std::chrono::system_clock::now() - start; + double milliseconds = static_cast<double>((std::chrono::duration_cast<std::chrono::milliseconds>(dur)).count()); + + std::cout << a_GenName << ": " << 1000.0 * 100.0 * 100.0 / milliseconds << " chunks per second" << std::endl; + } +} g_BioGenPerfTest; + +#endif + + + + diff --git a/src/Generating/BioGen.h b/src/Generating/BioGen.h index 22ddfae5c..5fd0844d9 100644 --- a/src/Generating/BioGen.h +++ b/src/Generating/BioGen.h @@ -48,12 +48,12 @@ class cBioGenCache : typedef cBiomeGen super; public: - cBioGenCache(cBiomeGen * a_BioGenToCache, int a_CacheSize); // Doesn't take ownership of a_BioGenToCache - ~cBioGenCache(); + cBioGenCache(cBiomeGenPtr a_BioGenToCache, int a_CacheSize); + virtual ~cBioGenCache(); protected: - cBiomeGen * m_BioGenToCache; + cBiomeGenPtr m_BioGenToCache; struct sCacheData { @@ -87,19 +87,21 @@ class cBioGenMulticache : typedef cBiomeGen super; public: - /* - a_CacheSize defines the size of each singular cache - a_CachesLength defines how many caches are used for the multicache - */ - cBioGenMulticache(cBiomeGen * a_BioGenToCache, size_t a_CacheSize, size_t a_CachesLength); // Doesn't take ownership of a_BioGenToCache - ~cBioGenMulticache(); + /* Creates a new multicache - a cache that divides the caching into several sub-caches based on the chunk coords. + This allows us to use shorter cache depths with faster lookups for more covered area. (#381) + a_SubCacheSize defines the size of each sub-cache + a_NumSubCaches defines how many sub-caches are used for the multicache. */ + cBioGenMulticache(cBiomeGenPtr a_BioGenToCache, size_t a_SubCacheSize, size_t a_NumSubCaches); protected: - typedef std::vector<cBiomeGen *> cBiomeGens; + typedef std::vector<cBiomeGenPtr> cBiomeGenPtrs; + + /** Number of sub-caches. Pulled out of m_Caches.size() for faster access. */ + size_t m_NumSubCaches; - size_t m_CachesLength; - cBiomeGens m_Caches; + /** Individual sub-caches. */ + cBiomeGenPtrs m_Caches; virtual void GenBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) override; diff --git a/src/Generating/CMakeLists.txt b/src/Generating/CMakeLists.txt index 33d622b42..1a26bd0d5 100644 --- a/src/Generating/CMakeLists.txt +++ b/src/Generating/CMakeLists.txt @@ -46,6 +46,7 @@ SET (HDRS FinishGen.h GridStructGen.h HeiGen.h + IntGen.h MineShafts.h NetherFortGen.h Noise3DGenerator.h @@ -53,6 +54,7 @@ SET (HDRS PieceGenerator.h Prefab.h PrefabPiecePool.h + ProtIntGen.h RainbowRoadsGen.h Ravines.h RoughRavines.h @@ -65,5 +67,5 @@ SET (HDRS if(NOT MSVC) add_library(Generating ${SRCS} ${HDRS}) - target_link_libraries(Generating OSSupport iniFile Blocks) + target_link_libraries(Generating OSSupport Blocks) endif() diff --git a/src/Generating/ChunkDesc.cpp b/src/Generating/ChunkDesc.cpp index c0b646fd0..020d3bd0f 100644 --- a/src/Generating/ChunkDesc.cpp +++ b/src/Generating/ChunkDesc.cpp @@ -269,10 +269,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelX less than zero, adjusting to zero", __FUNCTION__); a_MaxRelX = 0; } - else if (a_MaxRelX >= cChunkDef::Width) + else if (a_MaxRelX > cChunkDef::Width) { LOGWARNING("%s: MaxRelX more than chunk width, adjusting to chunk width", __FUNCTION__); - a_MaxRelX = cChunkDef::Width - 1; + a_MaxRelX = cChunkDef::Width; } if (a_MinRelY < 0) @@ -290,10 +290,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelY less than zero, adjusting to zero", __FUNCTION__); a_MaxRelY = 0; } - else if (a_MaxRelY >= cChunkDef::Height) + else if (a_MaxRelY > cChunkDef::Height) { LOGWARNING("%s: MaxRelY more than chunk height, adjusting to chunk height", __FUNCTION__); - a_MaxRelY = cChunkDef::Height - 1; + a_MaxRelY = cChunkDef::Height; } if (a_MinRelZ < 0) @@ -311,10 +311,10 @@ void cChunkDesc::ReadBlockArea(cBlockArea & a_Dest, int a_MinRelX, int a_MaxRelX LOGWARNING("%s: MaxRelZ less than zero, adjusting to zero", __FUNCTION__); a_MaxRelZ = 0; } - else if (a_MaxRelZ >= cChunkDef::Width) + else if (a_MaxRelZ > cChunkDef::Width) { LOGWARNING("%s: MaxRelZ more than chunk width, adjusting to chunk width", __FUNCTION__); - a_MaxRelZ = cChunkDef::Width - 1; + a_MaxRelZ = cChunkDef::Width; } // Prepare the block area: @@ -530,10 +530,10 @@ cBlockEntity * cChunkDesc::GetBlockEntity(int a_RelX, int a_RelY, int a_RelZ) // The block entity is not created yet, try to create it and add to list: cBlockEntity * be = cBlockEntity::CreateByBlockType(GetBlockType(a_RelX, a_RelY, a_RelZ), GetBlockMeta(a_RelX, a_RelY, a_RelZ), AbsX, a_RelY, AbsZ); - if (be == NULL) + if (be == nullptr) { // No block entity for this block type - return NULL; + return nullptr; } m_BlockEntities.push_back(be); return be; diff --git a/src/Generating/ChunkDesc.h b/src/Generating/ChunkDesc.h index eeea0c957..570132790 100644 --- a/src/Generating/ChunkDesc.h +++ b/src/Generating/ChunkDesc.h @@ -172,7 +172,7 @@ public: /** Returns the block entity at the specified coords. If there is no block entity at those coords, tries to create one, based on the block type - If the blocktype doesn't support a block entity, returns NULL. */ + If the blocktype doesn't support a block entity, returns nullptr. */ cBlockEntity * GetBlockEntity(int a_RelX, int a_RelY, int a_RelZ); /** Updates the heightmap to match the current contents. diff --git a/src/Generating/ChunkGenerator.cpp b/src/Generating/ChunkGenerator.cpp index d615456c1..92e1bb31d 100644 --- a/src/Generating/ChunkGenerator.cpp +++ b/src/Generating/ChunkGenerator.cpp @@ -2,7 +2,7 @@ #include "Globals.h" #include "ChunkGenerator.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "ChunkDesc.h" #include "ComposableGenerator.h" #include "Noise3DGenerator.h" @@ -28,9 +28,9 @@ const unsigned int QUEUE_SKIP_LIMIT = 500; cChunkGenerator::cChunkGenerator(void) : super("cChunkGenerator"), m_Seed(0), // Will be overwritten by the actual generator - m_Generator(NULL), - m_PluginInterface(NULL), - m_ChunkSink(NULL) + m_Generator(nullptr), + m_PluginInterface(nullptr), + m_ChunkSink(nullptr) { } @@ -80,7 +80,7 @@ bool cChunkGenerator::Start(cPluginInterface & a_PluginInterface, cChunkSink & a m_Generator = new cComposableGenerator(*this); } - if (m_Generator == NULL) + if (m_Generator == nullptr) { LOGERROR("Generator could not start, aborting the server"); return false; @@ -103,7 +103,7 @@ void cChunkGenerator::Stop(void) Wait(); delete m_Generator; - m_Generator = NULL; + m_Generator = nullptr; } @@ -144,7 +144,7 @@ void cChunkGenerator::QueueGenerateChunk(int a_ChunkX, int a_ChunkZ, bool a_Forc void cChunkGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { - if (m_Generator != NULL) + if (m_Generator != nullptr) { m_Generator->GenerateBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } @@ -180,7 +180,7 @@ int cChunkGenerator::GetQueueLength(void) EMCSBiome cChunkGenerator::GetBiomeAt(int a_BlockX, int a_BlockZ) { - ASSERT(m_Generator != NULL); + ASSERT(m_Generator != nullptr); return m_Generator->GetBiomeAt(a_BlockX, a_BlockZ); } @@ -283,8 +283,8 @@ void cChunkGenerator::Execute(void) void cChunkGenerator::DoGenerate(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_PluginInterface != NULL); - ASSERT(m_ChunkSink != NULL); + ASSERT(m_PluginInterface != nullptr); + ASSERT(m_ChunkSink != nullptr); ASSERT(m_ChunkSink->IsChunkQueued(a_ChunkX, a_ChunkZ)); cChunkDesc ChunkDesc(a_ChunkX, a_ChunkZ); diff --git a/src/Generating/CompoGen.cpp b/src/Generating/CompoGen.cpp index 178673e32..29b831dfd 100644 --- a/src/Generating/CompoGen.cpp +++ b/src/Generating/CompoGen.cpp @@ -12,7 +12,7 @@ #include "../BlockID.h" #include "../Item.h" #include "../LinearUpscale.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" @@ -663,7 +663,7 @@ void cCompoGenNether::InitializeCompoGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cCompoGenCache: -cCompoGenCache::cCompoGenCache(cTerrainCompositionGen & a_Underlying, int a_CacheSize) : +cCompoGenCache::cCompoGenCache(cTerrainCompositionGenPtr a_Underlying, int a_CacheSize) : m_Underlying(a_Underlying), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -687,9 +687,9 @@ cCompoGenCache::cCompoGenCache(cTerrainCompositionGen & a_Underlying, int a_Cach cCompoGenCache::~cCompoGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } @@ -739,7 +739,7 @@ void cCompoGenCache::ComposeTerrain(cChunkDesc & a_ChunkDesc) // Not in the cache: m_NumMisses++; - m_Underlying.ComposeTerrain(a_ChunkDesc); + m_Underlying->ComposeTerrain(a_ChunkDesc); // Insert it as the first item in the MRU order: int Idx = m_CacheOrder[m_CacheSize - 1]; @@ -760,7 +760,7 @@ void cCompoGenCache::ComposeTerrain(cChunkDesc & a_ChunkDesc) void cCompoGenCache::InitializeCompoGen(cIniFile & a_IniFile) { - m_Underlying.InitializeCompoGen(a_IniFile); + m_Underlying->InitializeCompoGen(a_IniFile); } diff --git a/src/Generating/CompoGen.h b/src/Generating/CompoGen.h index 096b0fb5a..b145b6ba3 100644 --- a/src/Generating/CompoGen.h +++ b/src/Generating/CompoGen.h @@ -144,12 +144,12 @@ protected: -/// Caches most-recently-used chunk composition of another composition generator. Caches only the types and metas +/** Caches most-recently-used chunk composition of another composition generator. Caches only the types and metas */ class cCompoGenCache : public cTerrainCompositionGen { public: - cCompoGenCache(cTerrainCompositionGen & a_Underlying, int a_CacheSize); // Doesn't take ownership of a_Underlying + cCompoGenCache(cTerrainCompositionGenPtr a_Underlying, int a_CacheSize); // Doesn't take ownership of a_Underlying ~cCompoGenCache(); // cTerrainCompositionGen override: @@ -158,7 +158,7 @@ public: protected: - cTerrainCompositionGen & m_Underlying; + cTerrainCompositionGenPtr m_Underlying; struct sCacheData { diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 87461b944..169821050 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -7,7 +7,7 @@ #include "ComposableGenerator.h" #include "../World.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../Root.h" // Individual composed algorithms: @@ -39,7 +39,7 @@ //////////////////////////////////////////////////////////////////////////////// // cTerrainCompositionGen: -cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed) +cTerrainCompositionGenPtr cTerrainCompositionGen::CreateCompositionGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed) { AString CompoGenName = a_IniFile.GetValueSet("Generator", "CompositionGen", ""); if (CompoGenName.empty()) @@ -48,7 +48,7 @@ cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & CompoGenName = "Biomal"; } - cTerrainCompositionGen * res = NULL; + cTerrainCompositionGen * res = nullptr; if (NoCaseCompare(CompoGenName, "sameblock") == 0) { res = new cCompoGenSameBlock; @@ -102,12 +102,12 @@ cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & a_IniFile.SetValue("Generator", "CompositionGen", "Biomal"); return CreateCompositionGen(a_IniFile, a_BiomeGen, a_HeightGen, a_Seed); } - ASSERT(res != NULL); + ASSERT(res != nullptr); // Read the settings from the ini file: res->InitializeCompoGen(a_IniFile); - return res; + return cTerrainCompositionGenPtr(res); } @@ -119,12 +119,9 @@ cTerrainCompositionGen * cTerrainCompositionGen::CreateCompositionGen(cIniFile & cComposableGenerator::cComposableGenerator(cChunkGenerator & a_ChunkGenerator) : super(a_ChunkGenerator), - m_BiomeGen(NULL), - m_HeightGen(NULL), - m_CompositionGen(NULL), - m_UnderlyingBiomeGen(NULL), - m_UnderlyingHeightGen(NULL), - m_UnderlyingCompositionGen(NULL) + m_BiomeGen(), + m_HeightGen(), + m_CompositionGen() { } @@ -132,33 +129,6 @@ cComposableGenerator::cComposableGenerator(cChunkGenerator & a_ChunkGenerator) : -cComposableGenerator::~cComposableGenerator() -{ - // Delete the generating composition: - for (cFinishGenList::const_iterator itr = m_FinishGens.begin(); itr != m_FinishGens.end(); ++itr) - { - delete *itr; - } - m_FinishGens.clear(); - - delete m_CompositionGen; - m_CompositionGen = NULL; - delete m_HeightGen; - m_HeightGen = NULL; - delete m_BiomeGen; - m_BiomeGen = NULL; - delete m_UnderlyingCompositionGen; - m_UnderlyingCompositionGen = NULL; - delete m_UnderlyingHeightGen; - m_UnderlyingHeightGen = NULL; - delete m_UnderlyingBiomeGen; - m_UnderlyingBiomeGen = NULL; -} - - - - - void cComposableGenerator::Initialize(cIniFile & a_IniFile) { super::Initialize(a_IniFile); @@ -175,7 +145,7 @@ void cComposableGenerator::Initialize(cIniFile & a_IniFile) void cComposableGenerator::GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) { - if (m_BiomeGen != NULL) // Quick fix for generator deinitializing before the world storage finishes loading + if (m_BiomeGen != nullptr) // Quick fix for generator deinitializing before the world storage finishes loading { m_BiomeGen->GenBiomes(a_ChunkX, a_ChunkZ, a_BiomeMap); } @@ -245,15 +215,14 @@ void cComposableGenerator::InitBiomeGen(cIniFile & a_IniFile) CacheSize = 4; } LOGD("Using a cache for biomegen of size %d.", CacheSize); - m_UnderlyingBiomeGen = m_BiomeGen; if (MultiCacheLength > 0) { LOGD("Enabling multicache for biomegen of length %d.", MultiCacheLength); - m_BiomeGen = new cBioGenMulticache(m_UnderlyingBiomeGen, CacheSize, MultiCacheLength); + m_BiomeGen = cBiomeGenPtr(new cBioGenMulticache(m_BiomeGen, CacheSize, MultiCacheLength)); } else { - m_BiomeGen = new cBioGenCache(m_UnderlyingBiomeGen, CacheSize); + m_BiomeGen = cBiomeGenPtr(new cBioGenCache(m_BiomeGen, CacheSize)); } } @@ -264,7 +233,7 @@ void cComposableGenerator::InitBiomeGen(cIniFile & a_IniFile) void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) { bool CacheOffByDefault = false; - m_HeightGen = cTerrainHeightGen::CreateHeightGen(a_IniFile, *m_BiomeGen, m_ChunkGenerator.GetSeed(), CacheOffByDefault); + m_HeightGen = cTerrainHeightGen::CreateHeightGen(a_IniFile, m_BiomeGen, m_ChunkGenerator.GetSeed(), CacheOffByDefault); // Add a cache, if requested: int CacheSize = a_IniFile.GetValueSetI("Generator", "HeightGenCacheSize", CacheOffByDefault ? 0 : 64); @@ -278,8 +247,7 @@ void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) CacheSize = 4; } LOGD("Using a cache for Heightgen of size %d.", CacheSize); - m_UnderlyingHeightGen = m_HeightGen; - m_HeightGen = new cHeiGenCache(*m_UnderlyingHeightGen, CacheSize); + m_HeightGen = cTerrainHeightGenPtr(new cHeiGenCache(m_HeightGen, CacheSize)); } } @@ -289,13 +257,12 @@ void cComposableGenerator::InitHeightGen(cIniFile & a_IniFile) void cComposableGenerator::InitCompositionGen(cIniFile & a_IniFile) { - m_CompositionGen = cTerrainCompositionGen::CreateCompositionGen(a_IniFile, *m_BiomeGen, *m_HeightGen, m_ChunkGenerator.GetSeed()); + m_CompositionGen = cTerrainCompositionGen::CreateCompositionGen(a_IniFile, m_BiomeGen, *m_HeightGen, m_ChunkGenerator.GetSeed()); int CompoGenCacheSize = a_IniFile.GetValueSetI("Generator", "CompositionGenCacheSize", 64); if (CompoGenCacheSize > 1) { - m_UnderlyingCompositionGen = m_CompositionGen; - m_CompositionGen = new cCompoGenCache(*m_UnderlyingCompositionGen, 32); + m_CompositionGen = cTerrainCompositionGenPtr(new cCompoGenCache(m_CompositionGen, 32)); } } @@ -319,7 +286,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) { int DefaultBottomLavaLevel = (Dimension == dimNether) ? 30 : 10; int BottomLavaLevel = a_IniFile.GetValueSetI("Generator", "BottomLavaLevel", DefaultBottomLavaLevel); - m_FinishGens.push_back(new cFinishGenBottomLava(BottomLavaLevel)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenBottomLava(BottomLavaLevel))); } else if (NoCaseCompare(*itr, "DeadBushes") == 0) { @@ -341,20 +308,20 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AllowedBlocks.push_back(E_BLOCK_HARDENED_CLAY); AllowedBlocks.push_back(E_BLOCK_STAINED_CLAY); - m_FinishGens.push_back(new cFinishGenSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, AllowedBiomes, 2, AllowedBlocks)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_DEAD_BUSH, AllowedBiomes, 2, AllowedBlocks))); } else if (NoCaseCompare(*itr, "DirectOverhangs") == 0) { - m_FinishGens.push_back(new cStructGenDirectOverhangs(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDirectOverhangs(Seed))); } else if (NoCaseCompare(*itr, "DistortedMembraneOverhangs") == 0) { - m_FinishGens.push_back(new cStructGenDistortedMembraneOverhangs(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDistortedMembraneOverhangs(Seed))); } else if (NoCaseCompare(*itr, "DualRidgeCaves") == 0) { float Threshold = (float)a_IniFile.GetValueSetF("Generator", "DualRidgeCavesThreshold", 0.3); - m_FinishGens.push_back(new cStructGenDualRidgeCaves(Seed, Threshold)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenDualRidgeCaves(Seed, Threshold))); } else if (NoCaseCompare(*itr, "DungeonRooms") == 0) { @@ -362,24 +329,24 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxSize = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMaxSize", 7); int MinSize = a_IniFile.GetValueSetI("Generator", "DungeonRoomsMinSize", 5); AString HeightDistrib = a_IniFile.GetValueSet ("Generator", "DungeonRoomsHeightDistrib", "0, 0; 10, 10; 11, 500; 40, 500; 60, 40; 90, 1"); - m_FinishGens.push_back(new cDungeonRoomsFinisher(*m_HeightGen, Seed, GridSize, MaxSize, MinSize, HeightDistrib)); + m_FinishGens.push_back(cFinishGenPtr(new cDungeonRoomsFinisher(m_HeightGen, Seed, GridSize, MaxSize, MinSize, HeightDistrib))); } else if (NoCaseCompare(*itr, "Ice") == 0) { - m_FinishGens.push_back(new cFinishGenIce); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenIce)); } else if (NoCaseCompare(*itr, "LavaLakes") == 0) { int Probability = a_IniFile.GetValueSetI("Generator", "LavaLakesProbability", 10); - m_FinishGens.push_back(new cStructGenLakes(Seed * 5 + 16873, E_BLOCK_STATIONARY_LAVA, *m_HeightGen, Probability)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 5 + 16873, E_BLOCK_STATIONARY_LAVA, m_HeightGen, Probability))); } else if (NoCaseCompare(*itr, "LavaSprings") == 0) { - m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_LAVA, a_IniFile, Dimension))); } else if (NoCaseCompare(*itr, "MarbleCaves") == 0) { - m_FinishGens.push_back(new cStructGenMarbleCaves(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenMarbleCaves(Seed))); } else if (NoCaseCompare(*itr, "MineShafts") == 0) { @@ -389,10 +356,10 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int ChanceCorridor = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCorridor", 600); int ChanceCrossing = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceCrossing", 200); int ChanceStaircase = a_IniFile.GetValueSetI("Generator", "MineShaftsChanceStaircase", 200); - m_FinishGens.push_back(new cStructGenMineShafts( + m_FinishGens.push_back(cFinishGenPtr(new cStructGenMineShafts( Seed, GridSize, MaxOffset, MaxSystemSize, ChanceCorridor, ChanceCrossing, ChanceStaircase - )); + ))); } else if (NoCaseCompare(*itr, "Lilypads") == 0) { @@ -406,7 +373,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AllowedBlocks.push_back(E_BLOCK_WATER); AllowedBlocks.push_back(E_BLOCK_STATIONARY_WATER); - m_FinishGens.push_back(new cFinishGenSingleTopBlock(Seed, E_BLOCK_LILY_PAD, AllowedBiomes, 4, AllowedBlocks)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSingleTopBlock(Seed, E_BLOCK_LILY_PAD, AllowedBiomes, 4, AllowedBlocks))); } else if (NoCaseCompare(*itr, "NaturalPatches") == 0) { @@ -455,18 +422,18 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) AndesiteVein.NestSize = 32; Ores.push_back(AndesiteVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE))); } else if (NoCaseCompare(*itr, "NetherClumpFoliage") == 0) { - m_FinishGens.push_back(new cFinishGenNetherClumpFoliage(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenNetherClumpFoliage(Seed))); } else if (NoCaseCompare(*itr, "NetherForts") == 0) { int GridSize = a_IniFile.GetValueSetI("Generator", "NetherFortsGridSize", 512); int MaxOffset = a_IniFile.GetValueSetI("Generator", "NetherFortMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "NetherFortsMaxDepth", 12); - m_FinishGens.push_back(new cNetherFortGen(Seed, GridSize, MaxOffset, MaxDepth)); + m_FinishGens.push_back(cFinishGenPtr(new cNetherFortGen(Seed, GridSize, MaxOffset, MaxDepth))); } else if (NoCaseCompare(*itr, "NetherOreNests") == 0) { @@ -480,7 +447,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) QuartzVein.NestSize = 8; Ores.push_back(QuartzVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_NETHERRACK)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_NETHERRACK))); } else if (NoCaseCompare(*itr, "OreNests") == 0) @@ -535,11 +502,11 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) DiamondVein.NestSize = 4; Ores.push_back(DiamondVein); - m_FinishGens.push_back(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenOreNests(Seed, Ores, E_BLOCK_STONE))); } else if (NoCaseCompare(*itr, "POCPieces") == 0) { - m_FinishGens.push_back(new cPOCPieceGenerator(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cPOCPieceGenerator(Seed))); } else if (NoCaseCompare(*itr, "PreSimulator") == 0) { @@ -548,7 +515,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) bool PreSimulateWater = a_IniFile.GetValueSetB("Generator", "PreSimulatorWater", true); bool PreSimulateLava = a_IniFile.GetValueSetB("Generator", "PreSimulatorLava", true); - m_FinishGens.push_back(new cFinishGenPreSimulator(PreSimulateFallingBlocks, PreSimulateWater, PreSimulateLava)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenPreSimulator(PreSimulateFallingBlocks, PreSimulateWater, PreSimulateLava))); } else if (NoCaseCompare(*itr, "RainbowRoads") == 0) { @@ -556,11 +523,11 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxOffset = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxDepth", 30); int MaxSize = a_IniFile.GetValueSetI("Generator", "RainbowRoadsMaxSize", 260); - m_FinishGens.push_back(new cRainbowRoadsGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize)); + m_FinishGens.push_back(cFinishGenPtr(new cRainbowRoadsGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize))); } else if (NoCaseCompare(*itr, "Ravines") == 0) { - m_FinishGens.push_back(new cStructGenRavines(Seed, 128)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenRavines(Seed, 128))); } else if (NoCaseCompare(*itr, "RoughRavines") == 0) { @@ -580,7 +547,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) double MinCeilingHeightEdge = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightEdge", 38); double MaxCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMaxCeilingHeightCenter", 58); double MinCeilingHeightCenter = a_IniFile.GetValueSetF("Generator", "RoughRavinesMinCeilingHeightCenter", 36); - m_FinishGens.push_back(new cRoughRavines( + m_FinishGens.push_back(cFinishGenPtr(new cRoughRavines( Seed, MaxSize, MinSize, (float)MaxCenterWidth, (float)MinCenterWidth, (float)MaxRoughness, (float)MinRoughness, @@ -589,27 +556,27 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) (float)MaxCeilingHeightEdge, (float)MinCeilingHeightEdge, (float)MaxCeilingHeightCenter, (float)MinCeilingHeightCenter, GridSize, MaxOffset - )); + ))); } else if (NoCaseCompare(*itr, "Snow") == 0) { - m_FinishGens.push_back(new cFinishGenSnow); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSnow)); } else if (NoCaseCompare(*itr, "SprinkleFoliage") == 0) { - m_FinishGens.push_back(new cFinishGenSprinkleFoliage(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenSprinkleFoliage(Seed))); } else if (NoCaseCompare(*itr, "TallGrass") == 0) { - m_FinishGens.push_back(new cFinishGenTallGrass(Seed)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenTallGrass(Seed))); } else if (NoCaseCompare(*itr, "TestRails") == 0) { - m_FinishGens.push_back(new cTestRailsGen(Seed, 100, 1, 7, 50)); + m_FinishGens.push_back(cFinishGenPtr(new cTestRailsGen(Seed, 100, 1, 7, 50))); } else if (NoCaseCompare(*itr, "Trees") == 0) { - m_FinishGens.push_back(new cStructGenTrees(Seed, m_BiomeGen, m_HeightGen, m_CompositionGen)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenTrees(Seed, m_BiomeGen, m_HeightGen, m_CompositionGen))); } else if (NoCaseCompare(*itr, "UnderwaterBases") == 0) { @@ -617,7 +584,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxOffset = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxOffset", 128); int MaxDepth = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxDepth", 7); int MaxSize = a_IniFile.GetValueSetI("Generator", "UnderwaterBaseMaxSize", 128); - m_FinishGens.push_back(new cUnderwaterBaseGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, *m_BiomeGen)); + m_FinishGens.push_back(cFinishGenPtr(new cUnderwaterBaseGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, m_BiomeGen))); } else if (NoCaseCompare(*itr, "Villages") == 0) { @@ -627,23 +594,23 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) int MaxSize = a_IniFile.GetValueSetI("Generator", "VillageMaxSize", 128); int MinDensity = a_IniFile.GetValueSetI("Generator", "VillageMinDensity", 50); int MaxDensity = a_IniFile.GetValueSetI("Generator", "VillageMaxDensity", 80); - m_FinishGens.push_back(new cVillageGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, MinDensity, MaxDensity, *m_BiomeGen, *m_HeightGen)); + m_FinishGens.push_back(cFinishGenPtr(new cVillageGen(Seed, GridSize, MaxOffset, MaxDepth, MaxSize, MinDensity, MaxDensity, m_BiomeGen, m_HeightGen))); } else if (NoCaseCompare(*itr, "WaterLakes") == 0) { int Probability = a_IniFile.GetValueSetI("Generator", "WaterLakesProbability", 25); - m_FinishGens.push_back(new cStructGenLakes(Seed * 3 + 652, E_BLOCK_STATIONARY_WATER, *m_HeightGen, Probability)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenLakes(Seed * 3 + 652, E_BLOCK_STATIONARY_WATER, m_HeightGen, Probability))); } else if (NoCaseCompare(*itr, "WaterSprings") == 0) { - m_FinishGens.push_back(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension)); + m_FinishGens.push_back(cFinishGenPtr(new cFinishGenFluidSprings(Seed, E_BLOCK_WATER, a_IniFile, Dimension))); } else if (NoCaseCompare(*itr, "WormNestCaves") == 0) { int Size = a_IniFile.GetValueSetI("Generator", "WormNestCavesSize", 64); int Grid = a_IniFile.GetValueSetI("Generator", "WormNestCavesGrid", 96); int MaxOffset = a_IniFile.GetValueSetI("Generator", "WormNestMaxOffset", 32); - m_FinishGens.push_back(new cStructGenWormNestCaves(Seed, Size, Grid, MaxOffset)); + m_FinishGens.push_back(cFinishGenPtr(new cStructGenWormNestCaves(Seed, Size, Grid, MaxOffset))); } else { diff --git a/src/Generating/ComposableGenerator.h b/src/Generating/ComposableGenerator.h index 6b7627d2e..a091f8d53 100644 --- a/src/Generating/ComposableGenerator.h +++ b/src/Generating/ComposableGenerator.h @@ -24,6 +24,16 @@ See http://forum.mc-server.org/showthread.php?tid=409 for details. +// Forward-declare the shared pointers to subgenerator classes: +class cBiomeGen; +class cTerrainHeightGen; +class cTerrainCompositionGen; +class cFinishGen; +typedef SharedPtr<cBiomeGen> cBiomeGenPtr; +typedef SharedPtr<cTerrainHeightGen> cTerrainHeightGenPtr; +typedef SharedPtr<cTerrainCompositionGen> cTerrainCompositionGenPtr; +typedef SharedPtr<cFinishGen> cFinishGenPtr; + // fwd: Noise3DGenerator.h class cNoise3DComposable; @@ -53,8 +63,7 @@ public: a_CacheOffByDefault gets set to whether the cache should be disabled by default. Used in BiomeVisualiser, too. Implemented in BioGen.cpp! */ - static cBiomeGen * CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault); - + static cBiomeGenPtr CreateBiomeGen(cIniFile & a_IniFile, int a_Seed, bool & a_CacheOffByDefault); } ; @@ -83,7 +92,7 @@ public: a_CacheOffByDefault gets set to whether the cache should be disabled by default Implemented in HeiGen.cpp! */ - static cTerrainHeightGen * CreateHeightGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault); + static cTerrainHeightGenPtr CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault); } ; @@ -109,7 +118,7 @@ public: a_BiomeGen is the underlying biome generator, some composition generators may depend on it to generate more biomes a_HeightGen is the underlying height generator, some composition generators may depend on it providing additional values */ - static cTerrainCompositionGen * CreateCompositionGen(cIniFile & a_IniFile, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed); + static cTerrainCompositionGenPtr CreateCompositionGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, cTerrainHeightGen & a_HeightGen, int a_Seed); } ; @@ -131,7 +140,7 @@ public: virtual void GenFinish(cChunkDesc & a_ChunkDesc) = 0; } ; -typedef std::list<cFinishGen *> cFinishGenList; +typedef std::list<cFinishGenPtr> cFinishGenList; @@ -144,7 +153,6 @@ class cComposableGenerator : public: cComposableGenerator(cChunkGenerator & a_ChunkGenerator); - virtual ~cComposableGenerator(); virtual void Initialize(cIniFile & a_IniFile) override; virtual void GenerateBiomes(int a_ChunkX, int a_ChunkZ, cChunkDef::BiomeMap & a_BiomeMap) override; @@ -152,15 +160,10 @@ public: protected: // The generation composition: - cBiomeGen * m_BiomeGen; - cTerrainHeightGen * m_HeightGen; - cTerrainCompositionGen * m_CompositionGen; - cFinishGenList m_FinishGens; - - // Generators underlying the caches: - cBiomeGen * m_UnderlyingBiomeGen; - cTerrainHeightGen * m_UnderlyingHeightGen; - cTerrainCompositionGen * m_UnderlyingCompositionGen; + cBiomeGenPtr m_BiomeGen; + cTerrainHeightGenPtr m_HeightGen; + cTerrainCompositionGenPtr m_CompositionGen; + cFinishGenList m_FinishGens; /** Reads the biome gen settings from the ini and initializes m_BiomeGen accordingly */ diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index bf8995dcb..d5bc6ab55 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -7,7 +7,7 @@ #include "DistortedHeightmap.h" #include "../OSSupport/File.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearUpscale.h" @@ -227,15 +227,15 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biMesaPlateau */ { 2.0f, 2.0f}, // 39 // biomes 40 .. 128 are unused, 89 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 40 .. 49 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 50 .. 59 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 60 .. 69 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 70 .. 79 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 80 .. 89 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 90 .. 99 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 100 .. 109 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 110 .. 119 - {}, {}, {}, {}, {}, {}, {}, {}, {}, // 120 .. 128 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 40 .. 49 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 50 .. 59 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 60 .. 69 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 70 .. 79 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 80 .. 89 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 90 .. 99 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 100 .. 109 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 110 .. 119 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 120 .. 128 // Release 1.7 /* biome variants: /* biSunflowerPlains */ { 1.0f, 1.0f}, // 129 @@ -246,22 +246,22 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = /* biSwamplandM */ { 0.0f, 0.0f}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {}, {}, {}, {}, {}, // 135 .. 139 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 135 .. 139 /* biIcePlainsSpikes */ { 1.0f, 1.0f}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, // 141 .. 148 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 141 .. 148 /* biJungleM */ { 4.0f, 4.0f}, // 149 - {}, // 150 + {0.0f, 0.0f}, // 150 /* biJungleEdgeM */ { 3.0f, 3.0f}, // 151 - {}, {}, {}, // 152 .. 154 + {0.0f, 0.0f}, {0.0f, 0.0f}, {0.0f, 0.0f}, // 152 .. 154 /* biBirchForestM */ { 3.0f, 3.0f}, // 155 /* biBirchForestHillsM */ { 5.0f, 5.0f}, // 156 /* biRoofedForestM */ { 2.0f, 2.0f}, // 157 /* biColdTaigaM */ { 1.0f, 1.0f}, // 158 - {}, // 159 + {0.0f, 0.0f}, // 159 /* biMegaSpruceTaiga */ { 3.0f, 3.0f}, // 160 /* biMegaSpruceTaigaHills */ { 3.0f, 3.0f}, // 161 /* biExtremeHillsPlusM */ {32.0f, 32.0f}, // 162 @@ -276,13 +276,13 @@ const cDistortedHeightmap::sGenParam cDistortedHeightmap::m_GenParam[256] = -cDistortedHeightmap::cDistortedHeightmap(int a_Seed, cBiomeGen & a_BiomeGen) : +cDistortedHeightmap::cDistortedHeightmap(int a_Seed, cBiomeGenPtr a_BiomeGen) : m_NoiseDistortX(a_Seed + 1000), m_NoiseDistortZ(a_Seed + 2000), m_OceanFloorSelect(a_Seed + 3000), m_MesaFloor(a_Seed + 4000), m_BiomeGen(a_BiomeGen), - m_UnderlyingHeiGen(a_Seed, a_BiomeGen), + m_UnderlyingHeiGen(new cHeiGenBiomal(a_Seed, a_BiomeGen)), m_HeightGen(m_UnderlyingHeiGen, 64), m_IsInitialized(false) { @@ -577,7 +577,7 @@ void cDistortedHeightmap::UpdateDistortAmps(void) { for (int x = -1; x <= 1; x++) { - m_BiomeGen.GenBiomes(m_CurChunkX + x, m_CurChunkZ + z, Biomes[x + 1][z + 1]); + m_BiomeGen->GenBiomes(m_CurChunkX + x, m_CurChunkZ + z, Biomes[x + 1][z + 1]); } // for x } // for z diff --git a/src/Generating/DistortedHeightmap.h b/src/Generating/DistortedHeightmap.h index e6b3c9d3f..d073f29e4 100644 --- a/src/Generating/DistortedHeightmap.h +++ b/src/Generating/DistortedHeightmap.h @@ -35,7 +35,7 @@ public: NIBBLETYPE BlockMeta; } ; - cDistortedHeightmap(int a_Seed, cBiomeGen & a_BiomeGen); + cDistortedHeightmap(int a_Seed, cBiomeGenPtr a_BiomeGen); protected: typedef cChunkDef::BiomeMap BiomeNeighbors[3][3]; @@ -64,9 +64,14 @@ protected: int m_CurChunkZ; NOISE_DATATYPE m_DistortedHeightmap[17 * 257 * 17]; - cBiomeGen & m_BiomeGen; - cHeiGenBiomal m_UnderlyingHeiGen; // This generator provides us with base heightmap (before distortion) - cHeiGenCache m_HeightGen; // Cache above m_UnderlyingHeiGen + /** The bime generator to query for biomes. */ + cBiomeGenPtr m_BiomeGen; + + /** The generator that provides the base heightmap (before distortion). */ + cTerrainHeightGenPtr m_UnderlyingHeiGen; + + /** Cache for m_UnderlyingHeiGen. */ + cHeiGenCache m_HeightGen; /// Heightmap for the current chunk, before distortion (from m_HeightGen). Used for optimization. cChunkDef::HeightMap m_CurChunkHeights; diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index f213455d6..3f328868d 100644 --- a/src/Generating/DungeonRoomsFinisher.cpp +++ b/src/Generating/DungeonRoomsFinisher.cpp @@ -6,6 +6,7 @@ #include "Globals.h" #include "DungeonRoomsFinisher.h" #include "../FastRandom.h" +#include "../BlockEntities/ChestEntity.h" @@ -175,7 +176,33 @@ protected: } a_ChunkDesc.SetBlockTypeMeta(RelX, m_FloorHeight + 1, RelZ, E_BLOCK_CHEST, (NIBBLETYPE)a_Chest.y); - // TODO: Fill the chest with random loot + // Fill the chest with random loot + static const cLootProbab LootProbab[] = + { + // Item, MinAmount, MaxAmount, Weight + { cItem(E_ITEM_GOLDEN_APPLE), 1, 1, 1 }, + { cItem(E_ITEM_DIAMOND_HORSE_ARMOR), 1, 1, 1 }, + { cItem(E_ITEM_GOLD_HORSE_ARMOR), 1, 1, 2 }, + { cItem(E_ITEM_13_DISC), 1, 1, 4 }, + { cItem(E_ITEM_CAT_DISC), 1, 1, 4 }, + { cItem(E_ITEM_IRON_HORSE_ARMOR), 1, 1, 5 }, + { cItem(E_ITEM_IRON), 1, 4, 10 }, + { cItem(E_ITEM_WHEAT), 1, 4, 10 }, + { cItem(E_ITEM_GUNPOWDER), 1, 4, 10 }, + { cItem(E_ITEM_STRING), 1, 4, 10 }, + { cItem(E_ITEM_REDSTONE_DUST), 1, 4, 10 }, + { cItem(E_ITEM_SADDLE), 1, 1, 10 }, + { cItem(E_ITEM_BUCKET), 1, 1, 10 }, + { cItem(E_ITEM_BREAD), 1, 1, 10 }, + { cItem(E_ITEM_NAME_TAG), 1, 1, 10 }, + } ; + + cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(RelX, m_FloorHeight + 1, RelZ); + ASSERT((ChestEntity != nullptr) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); + cNoise Noise(a_ChunkDesc.GetChunkX() ^ a_ChunkDesc.GetChunkZ()); + int NumSlots = 3 + ((Noise.IntNoise3DInt(a_Chest.x, a_Chest.y, a_Chest.z) / 11) % 4); + int Seed = Noise.IntNoise2DInt(RelX, RelZ); + ChestEntity->GetContents().GenerateRandomLootWithBooks(LootProbab, ARRAYCOUNT(LootProbab), NumSlots, Seed); } @@ -193,6 +220,7 @@ protected: // The chunk is not intersecting the room at all, bail out return; } + int b = m_FloorHeight + 1; // Bottom int t = m_FloorHeight + 1 + ROOM_HEIGHT; // Top ReplaceCuboidRandom(a_ChunkDesc, m_StartX, m_FloorHeight, m_StartZ, m_EndX + 1, b, m_EndZ + 1, E_BLOCK_MOSSY_COBBLESTONE, E_BLOCK_COBBLESTONE); // Floor @@ -230,7 +258,7 @@ protected: //////////////////////////////////////////////////////////////////////////////// // cDungeonRoomsFinisher: -cDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) : +cDungeonRoomsFinisher::cDungeonRoomsFinisher(cTerrainHeightGenPtr a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib) : super(a_Seed + 100, a_GridSize, a_GridSize, a_GridSize, a_GridSize, a_MaxSize, a_MaxSize, 1024), m_HeightGen(a_HeightGen), m_MaxHalfSize((a_MaxSize + 1) / 2), @@ -266,7 +294,7 @@ cDungeonRoomsFinisher::cStructurePtr cDungeonRoomsFinisher::CreateStructure(int int RelX = a_OriginX, RelY = 0, RelZ = a_OriginZ; cChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ); cChunkDef::HeightMap HeightMap; - m_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap); + m_HeightGen->GenHeightMap(ChunkX, ChunkZ, HeightMap); int Height = cChunkDef::GetHeight(HeightMap, RelX, RelZ); // Max room height at {a_OriginX, a_OriginZ} Height = Clamp(m_HeightProbability.MapValue(rnd % m_HeightProbability.GetSum()), 10, Height - 5); diff --git a/src/Generating/DungeonRoomsFinisher.h b/src/Generating/DungeonRoomsFinisher.h index 2b52c9de6..09dd0448a 100644 --- a/src/Generating/DungeonRoomsFinisher.h +++ b/src/Generating/DungeonRoomsFinisher.h @@ -26,12 +26,12 @@ public: a_HeightGen is the underlying height generator, so that the rooms can always be placed under the terrain. a_MaxSize and a_MinSize are the maximum and minimum sizes of the room's internal (air) area, in blocks across. a_HeightDistrib is the string defining the height distribution for the rooms (cProbabDistrib format). */ - cDungeonRoomsFinisher(cTerrainHeightGen & a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib); + cDungeonRoomsFinisher(cTerrainHeightGenPtr a_HeightGen, int a_Seed, int a_GridSize, int a_MaxSize, int a_MinSize, const AString & a_HeightDistrib); protected: /** The height gen that is used for limiting the rooms' Y coords */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; /** Maximum half-size (from center to wall) of the dungeon room's inner (air) area. Default is 3 (vanilla). */ int m_MaxHalfSize; diff --git a/src/Generating/EndGen.cpp b/src/Generating/EndGen.cpp index c94cd1eff..0111d2fa3 100644 --- a/src/Generating/EndGen.cpp +++ b/src/Generating/EndGen.cpp @@ -5,7 +5,7 @@ #include "Globals.h" #include "EndGen.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearUpscale.h" diff --git a/src/Generating/FinishGen.cpp b/src/Generating/FinishGen.cpp index 96e3dc26b..18f8ee2bc 100644 --- a/src/Generating/FinishGen.cpp +++ b/src/Generating/FinishGen.cpp @@ -15,7 +15,7 @@ #include "../Simulator/FluidSimulator.h" // for cFluidSimulator::CanWashAway() #include "../Simulator/FireSimulator.h" #include "../World.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" @@ -414,6 +414,11 @@ void cFinishGenSnow::GenFinish(cChunkDesc & a_ChunkDesc) } break; } + default: + { + // There's no snow in the other biomes. + break; + } } } } // for z @@ -454,6 +459,11 @@ void cFinishGenIce::GenFinish(cChunkDesc & a_ChunkDesc) } break; } + default: + { + // No icy water in other biomes. + break; + } } } } // for z diff --git a/src/Generating/GridStructGen.cpp b/src/Generating/GridStructGen.cpp index 7090f14b1..3c08c1a39 100644 --- a/src/Generating/GridStructGen.cpp +++ b/src/Generating/GridStructGen.cpp @@ -135,7 +135,7 @@ void cGridStructGen::GetStructuresForChunk(int a_ChunkX, int a_ChunkZ, cStructur int OriginX = GridX + ((m_Noise.IntNoise2DInt(GridX + 3, GridZ + 5) / 7) % (m_MaxOffsetX * 2)) - m_MaxOffsetX; int OriginZ = GridZ + ((m_Noise.IntNoise2DInt(GridX + 5, GridZ + 3) / 7) % (m_MaxOffsetZ * 2)) - m_MaxOffsetZ; cStructurePtr Structure = CreateStructure(GridX, GridZ, OriginX, OriginZ); - if (Structure.get() == NULL) + if (Structure.get() == nullptr) { Structure.reset(new cEmptyStructure(GridX, GridZ, OriginX, OriginZ)); } diff --git a/src/Generating/HeiGen.cpp b/src/Generating/HeiGen.cpp index 79d529a6a..28a5698e4 100644 --- a/src/Generating/HeiGen.cpp +++ b/src/Generating/HeiGen.cpp @@ -6,7 +6,7 @@ #include "Globals.h" #include "HeiGen.h" #include "../LinearUpscale.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "DistortedHeightmap.h" #include "EndGen.h" #include "Noise3DGenerator.h" @@ -17,81 +17,6 @@ //////////////////////////////////////////////////////////////////////////////// -// cTerrainHeightGen: - -cTerrainHeightGen * cTerrainHeightGen::CreateHeightGen(cIniFile &a_IniFile, cBiomeGen & a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) -{ - AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", ""); - if (HeightGenName.empty()) - { - LOGWARN("[Generator] HeightGen value not set in world.ini, using \"Biomal\"."); - HeightGenName = "Biomal"; - } - - a_CacheOffByDefault = false; - cTerrainHeightGen * res = NULL; - if (NoCaseCompare(HeightGenName, "flat") == 0) - { - res = new cHeiGenFlat; - a_CacheOffByDefault = true; // We're generating faster than a cache would retrieve data - } - else if (NoCaseCompare(HeightGenName, "classic") == 0) - { - res = new cHeiGenClassic(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "DistortedHeightmap") == 0) - { - res = new cDistortedHeightmap(a_Seed, a_BiomeGen); - } - else if (NoCaseCompare(HeightGenName, "End") == 0) - { - res = new cEndGen(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "Mountains") == 0) - { - res = new cHeiGenMountains(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "Noise3D") == 0) - { - res = new cNoise3DComposable(a_Seed); - } - else if (NoCaseCompare(HeightGenName, "biomal") == 0) - { - res = new cHeiGenBiomal(a_Seed, a_BiomeGen); - - /* - // Performance-testing: - LOGINFO("Measuring performance of cHeiGenBiomal..."); - clock_t BeginTick = clock(); - for (int x = 0; x < 500; x++) - { - cChunkDef::HeightMap Heights; - res->GenHeightMap(x * 5, x * 5, Heights); - } - clock_t Duration = clock() - BeginTick; - LOGINFO("HeightGen for 500 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC); - //*/ - } - else - { - // No match found, force-set the default and retry - LOGWARN("Unknown HeightGen \"%s\", using \"Biomal\" instead.", HeightGenName.c_str()); - a_IniFile.DeleteValue("Generator", "HeightGen"); - a_IniFile.SetValue("Generator", "HeightGen", "Biomal"); - return CreateHeightGen(a_IniFile, a_BiomeGen, a_Seed, a_CacheOffByDefault); - } - - // Read the settings: - res->InitializeHeightGen(a_IniFile); - - return res; -} - - - - - -//////////////////////////////////////////////////////////////////////////////// // cHeiGenFlat: void cHeiGenFlat::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) @@ -118,7 +43,7 @@ void cHeiGenFlat::InitializeHeightGen(cIniFile & a_IniFile) //////////////////////////////////////////////////////////////////////////////// // cHeiGenCache: -cHeiGenCache::cHeiGenCache(cTerrainHeightGen & a_HeiGenToCache, int a_CacheSize) : +cHeiGenCache::cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize) : m_HeiGenToCache(a_HeiGenToCache), m_CacheSize(a_CacheSize), m_CacheOrder(new int[a_CacheSize]), @@ -142,9 +67,9 @@ cHeiGenCache::cHeiGenCache(cTerrainHeightGen & a_HeiGenToCache, int a_CacheSize) cHeiGenCache::~cHeiGenCache() { delete[] m_CacheData; - m_CacheData = NULL; + m_CacheData = nullptr; delete[] m_CacheOrder; - m_CacheOrder = NULL; + m_CacheOrder = nullptr; } @@ -190,7 +115,7 @@ void cHeiGenCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap // Not in the cache: m_NumMisses++; - m_HeiGenToCache.GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap); + m_HeiGenToCache->GenHeightMap(a_ChunkX, a_ChunkZ, a_HeightMap); // Insert it as the first item in the MRU order: int Idx = m_CacheOrder[m_CacheSize - 1]; @@ -210,7 +135,7 @@ void cHeiGenCache::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap void cHeiGenCache::InitializeHeightGen(cIniFile & a_IniFile) { - m_HeiGenToCache.InitializeHeightGen(a_IniFile); + m_HeiGenToCache->InitializeHeightGen(a_IniFile); } @@ -317,7 +242,9 @@ void cHeiGenClassic::InitializeHeightGen(cIniFile & a_IniFile) cHeiGenMountains::cHeiGenMountains(int a_Seed) : m_Seed(a_Seed), - m_Noise(a_Seed) + m_MountainNoise(a_Seed + 100), + m_DitchNoise(a_Seed + 200), + m_Perlin(a_Seed + 300) { } @@ -332,9 +259,11 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh NOISE_DATATYPE StartZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width); NOISE_DATATYPE EndZ = (NOISE_DATATYPE)(a_ChunkZ * cChunkDef::Width + cChunkDef::Width - 1); NOISE_DATATYPE Workspace[16 * 16]; - NOISE_DATATYPE Noise[16 * 16]; + NOISE_DATATYPE MountainNoise[16 * 16]; + NOISE_DATATYPE DitchNoise[16 * 16]; NOISE_DATATYPE PerlinNoise[16 * 16]; - m_Noise.Generate2D(Noise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); + m_MountainNoise.Generate2D(MountainNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); + m_DitchNoise.Generate2D(DitchNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); m_Perlin.Generate2D(PerlinNoise, 16, 16, StartX, EndX, StartZ, EndZ, Workspace); for (int z = 0; z < cChunkDef::Width; z++) { @@ -342,7 +271,7 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh for (int x = 0; x < cChunkDef::Width; x++) { int idx = IdxZ + x; - int hei = 100 - (int)((Noise[idx] + PerlinNoise[idx]) * 15); + int hei = 100 - (int)((MountainNoise[idx] - DitchNoise[idx] + PerlinNoise[idx]) * 15); if (hei < 10) { hei = 10; @@ -363,9 +292,12 @@ void cHeiGenMountains::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::Heigh void cHeiGenMountains::InitializeHeightGen(cIniFile & a_IniFile) { // TODO: Read the params from an INI file - m_Noise.AddOctave(0.1f, 0.1f); - m_Noise.AddOctave(0.05f, 0.5f); - m_Noise.AddOctave(0.02f, 1.5f); + m_MountainNoise.AddOctave(0.1f, 0.2f); + m_MountainNoise.AddOctave(0.05f, 0.4f); + m_MountainNoise.AddOctave(0.02f, 1.0f); + m_DitchNoise.AddOctave(0.1f, 0.2f); + m_DitchNoise.AddOctave(0.05f, 0.4f); + m_DitchNoise.AddOctave(0.02f, 1.0f); m_Perlin.AddOctave(0.01f, 1.5f); } @@ -423,15 +355,15 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biMesaPlateau */ { 0.1f, 1.0f, 0.05f, 1.5f, 0.01f, 4.0f, 80}, // biomes 40 .. 128 are unused, 89 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 40 .. 49 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 50 .. 59 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 60 .. 69 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 70 .. 79 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 80 .. 89 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 90 .. 99 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 100 .. 109 - {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, // 110 .. 119 - {}, {}, {}, {}, {}, {}, {}, {}, {}, // 120 .. 128 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 40 .. 49 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 50 .. 59 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 60 .. 69 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 70 .. 79 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 80 .. 89 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 90 .. 99 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 100 .. 109 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 110 .. 119 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 120 .. 128 /* biSunflowerPlains */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 129 /* biDesertM */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 130 @@ -441,22 +373,22 @@ const cHeiGenBiomal::sGenParam cHeiGenBiomal::m_GenParam[256] = /* biSwamplandM */ { 1.0f, 3.0f, 1.10f, 7.0f, 0.01f, 0.01f, 60}, // 134 // Biomes 135 .. 139 unused, 5 empty placeholders here: - {}, {}, {}, {}, {}, // 135 .. 139 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 135 .. 139 /* biIcePlainsSpikes */ { 0.1f, 2.0f, 0.05f, 12.0f, 0.01f, 10.0f, 40}, // 140 // Biomes 141 .. 148 unused, 8 empty placeholders here: - {}, {}, {}, {}, {}, {}, {}, {}, // 141 .. 148 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 141 .. 148 /* biJungleM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 149 - {}, // 150 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 150 /* biJungleEdgeM */ { 0.1f, 3.0f, 0.05f, 6.0f, 0.01f, 6.0f, 70}, // 151 - {}, {}, {}, // 152 .. 154 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 152 .. 154 /* biBirchForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 155 /* biBirchForestHillsM */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 156 /* biRoofedForestM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 157 /* biColdTaigaM */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 158 - {}, // 159 + {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0}, // 159 /* biMegaSpruceTaiga */ { 0.1f, 1.0f, 0.05f, 2.0f, 0.01f, 4.0f, 70}, // 160 /* biMegaSpruceTaigaHills */ { 0.2f, 2.0f, 0.05f, 10.0f, 0.01f, 8.0f, 80}, // 161 /* biExtremeHillsPlusM */ { 0.2f, 4.0f, 0.05f, 20.0f, 0.01f, 16.0f, 120}, // 162 @@ -479,7 +411,7 @@ void cHeiGenBiomal::GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMa { for (int x = -1; x <= 1; x++) { - m_BiomeGen.GenBiomes(a_ChunkX + x, a_ChunkZ + z, Biomes[x + 1][z + 1]); + m_BiomeGen->GenBiomes(a_ChunkX + x, a_ChunkZ + z, Biomes[x + 1][z + 1]); } // for x } // for z @@ -604,3 +536,283 @@ NOISE_DATATYPE cHeiGenBiomal::GetHeightAt(int a_RelX, int a_RelZ, int a_ChunkX, +//////////////////////////////////////////////////////////////////////////////// +// cHeiGenMinMax: + +class cHeiGenMinMax: + public cTerrainHeightGen +{ + typedef cTerrainHeightGen super; + + /** Size of the averaging process, in columns (for each direction). Must be less than 16. */ + static const int AVERAGING_SIZE = 4; + +public: + cHeiGenMinMax(int a_Seed, cBiomeGenPtr a_BiomeGen): + m_Noise(a_Seed), + m_BiomeGen(a_BiomeGen), + m_TotalWeight(0) + { + // Initialize the weights: + for (int z = 0; z <= AVERAGING_SIZE * 2; z++) + { + for (int x = 0; x <= AVERAGING_SIZE * 2; x++) + { + m_Weights[z][x] = 1 + 2 * AVERAGING_SIZE - std::abs(x - AVERAGING_SIZE) - std::abs(z - AVERAGING_SIZE); + m_TotalWeight += m_Weights[z][x]; + } + } + + // Initialize the Perlin generator: + m_Perlin.AddOctave(0.04f, 0.2f); + m_Perlin.AddOctave(0.02f, 0.1f); + m_Perlin.AddOctave(0.01f, 0.05f); + } + + + virtual void GenHeightMap(int a_ChunkX, int a_ChunkZ, cChunkDef::HeightMap & a_HeightMap) + { + // Generate the biomes for the 3*3 neighbors: + cChunkDef::BiomeMap neighborBiomes[3][3]; + for (int z = 0; z < 3; z++) for (int x = 0; x < 3; x++) + { + m_BiomeGen->GenBiomes(a_ChunkX + x - 1, a_ChunkZ + z - 1, neighborBiomes[z][x]); + } + + // Get the min and max heights based on the biomes: + double minHeight[cChunkDef::Width * cChunkDef::Width]; + double maxHeight[cChunkDef::Width * cChunkDef::Width]; + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + // For each column, sum the min and max values of the neighborhood around it: + double min = 0, max = 0; + for (int relz = 0; relz <= AVERAGING_SIZE * 2; relz++) + { + int bz = z + 16 + relz - AVERAGING_SIZE; // Biome Z coord relative to the neighborBiomes start + int cz = bz / 16; // Chunk Z coord relative to the neighborBiomes start + bz = bz % 16; // Biome Z coord relative to cz in neighborBiomes + for (int relx = 0; relx <= AVERAGING_SIZE * 2; relx++) + { + int bx = x + 16 + relx - AVERAGING_SIZE; // Biome X coord relative to the neighborBiomes start + int cx = bx / 16; // Chunk X coord relative to the neighborBiomes start + bx = bx % 16; // Biome X coord relative to cz in neighborBiomes + + // Get the biome's min and max heights: + double bmin, bmax; + getBiomeMinMax(cChunkDef::GetBiome(neighborBiomes[cz][cx], bx, bz), bmin, bmax); + + // Add them to the total, with the weight depending on their relative position to the column: + min += bmin * m_Weights[relz][relx]; + max += bmax * m_Weights[relz][relx]; + } // for relx + } // for relz + minHeight[x + z * cChunkDef::Width] = min / m_TotalWeight; + maxHeight[x + z * cChunkDef::Width] = max / m_TotalWeight; + } // for x + } // for z + + // Generate the base noise: + NOISE_DATATYPE noise[cChunkDef::Width * cChunkDef::Width]; + NOISE_DATATYPE workspace[cChunkDef::Width * cChunkDef::Width]; + NOISE_DATATYPE startX = static_cast<float>(a_ChunkX * cChunkDef::Width); + NOISE_DATATYPE endX = startX + cChunkDef::Width - 1; + NOISE_DATATYPE startZ = static_cast<float>(a_ChunkZ * cChunkDef::Width); + NOISE_DATATYPE endZ = startZ + cChunkDef::Width - 1; + m_Perlin.Generate2D(noise, 16, 16, startX, endX, startZ, endZ, workspace); + + // Make the height by ranging the noise between min and max: + for (int z = 0; z < cChunkDef::Width; z++) + { + for (int x = 0; x < cChunkDef::Width; x++) + { + double min = minHeight[x + z * cChunkDef::Width]; + double max = maxHeight[x + z * cChunkDef::Width]; + double h = (max + min) / 2 + noise[x + z * cChunkDef::Width] * (max - min); + cChunkDef::SetHeight(a_HeightMap, x, z, static_cast<HEIGHTTYPE>(h)); + } + } + } + + + virtual void InitializeHeightGen(cIniFile & a_IniFile) + { + // No settings available + } + +protected: + cNoise m_Noise; + + cPerlinNoise m_Perlin; + + /** The biome generator to query for the underlying biomes. */ + cBiomeGenPtr m_BiomeGen; + + /** Weights applied to each of the min / max values in the neighborhood of the currently evaluated column. */ + double m_Weights[AVERAGING_SIZE * 2 + 1][AVERAGING_SIZE * 2 + 1]; + + /** Sum of all the m_Weights items. */ + double m_TotalWeight; + + + /** Returns the minimum and maximum heights for the given biome. */ + void getBiomeMinMax(EMCSBiome a_Biome, double & a_Min, double & a_Max) + { + switch (a_Biome) + { + case biBeach: a_Min = 61; a_Max = 64; break; + case biBirchForest: a_Min = 63; a_Max = 75; break; + case biBirchForestHills: a_Min = 63; a_Max = 90; break; + case biBirchForestHillsM: a_Min = 63; a_Max = 90; break; + case biBirchForestM: a_Min = 63; a_Max = 75; break; + case biColdBeach: a_Min = 61; a_Max = 64; break; + case biColdTaiga: a_Min = 63; a_Max = 75; break; + case biColdTaigaHills: a_Min = 63; a_Max = 90; break; + case biColdTaigaM: a_Min = 63; a_Max = 75; break; + case biDeepOcean: a_Min = 30; a_Max = 60; break; + case biDesert: a_Min = 63; a_Max = 70; break; + case biDesertHills: a_Min = 63; a_Max = 85; break; + case biDesertM: a_Min = 63; a_Max = 70; break; + case biEnd: a_Min = 10; a_Max = 100; break; + case biExtremeHills: a_Min = 60; a_Max = 120; break; + case biExtremeHillsEdge: a_Min = 63; a_Max = 100; break; + case biExtremeHillsM: a_Min = 60; a_Max = 120; break; + case biExtremeHillsPlus: a_Min = 60; a_Max = 140; break; + case biExtremeHillsPlusM: a_Min = 60; a_Max = 140; break; + case biFlowerForest: a_Min = 63; a_Max = 75; break; + case biForest: a_Min = 63; a_Max = 75; break; + case biForestHills: a_Min = 63; a_Max = 90; break; + case biFrozenOcean: a_Min = 45; a_Max = 64; break; + case biFrozenRiver: a_Min = 60; a_Max = 62; break; + case biIceMountains: a_Min = 63; a_Max = 90; break; + case biIcePlains: a_Min = 63; a_Max = 70; break; + case biIcePlainsSpikes: a_Min = 60; a_Max = 70; break; + case biJungle: a_Min = 60; a_Max = 80; break; + case biJungleEdge: a_Min = 62; a_Max = 75; break; + case biJungleEdgeM: a_Min = 62; a_Max = 75; break; + case biJungleHills: a_Min = 60; a_Max = 90; break; + case biJungleM: a_Min = 60; a_Max = 75; break; + case biMegaSpruceTaiga: a_Min = 63; a_Max = 75; break; + case biMegaSpruceTaigaHills: a_Min = 63; a_Max = 90; break; + case biMegaTaiga: a_Min = 63; a_Max = 75; break; + case biMegaTaigaHills: a_Min = 63; a_Max = 90; break; + case biMesa: a_Min = 63; a_Max = 90; break; + case biMesaBryce: a_Min = 60; a_Max = 67; break; + case biMesaPlateau: a_Min = 75; a_Max = 85; break; + case biMesaPlateauF: a_Min = 80; a_Max = 90; break; + case biMesaPlateauFM: a_Min = 80; a_Max = 90; break; + case biMesaPlateauM: a_Min = 75; a_Max = 85; break; + case biMushroomIsland: a_Min = 63; a_Max = 90; break; + case biMushroomShore: a_Min = 60; a_Max = 75; break; + case biNether: a_Min = 10; a_Max = 100; break; + case biOcean: a_Min = 45; a_Max = 64; break; + case biPlains: a_Min = 63; a_Max = 70; break; + case biRiver: a_Min = 60; a_Max = 62; break; + case biRoofedForest: a_Min = 63; a_Max = 75; break; + case biRoofedForestM: a_Min = 63; a_Max = 75; break; + case biSavanna: a_Min = 63; a_Max = 75; break; + case biSavannaM: a_Min = 63; a_Max = 80; break; + case biSavannaPlateau: a_Min = 75; a_Max = 100; break; + case biSavannaPlateauM: a_Min = 80; a_Max = 160; break; + case biStoneBeach: a_Min = 60; a_Max = 64; break; + case biSunflowerPlains: a_Min = 63; a_Max = 70; break; + case biSwampland: a_Min = 60; a_Max = 67; break; + case biSwamplandM: a_Min = 61; a_Max = 67; break; + case biTaiga: a_Min = 63; a_Max = 75; break; + case biTaigaHills: a_Min = 63; a_Max = 90; break; + case biTaigaM: a_Min = 63; a_Max = 80; break; + default: + { + ASSERT(!"Unknown biome"); + a_Min = 10; + a_Max = 10; + break; + } + } + } +}; + + + + + +//////////////////////////////////////////////////////////////////////////////// +// cTerrainHeightGen: + +cTerrainHeightGenPtr cTerrainHeightGen::CreateHeightGen(cIniFile & a_IniFile, cBiomeGenPtr a_BiomeGen, int a_Seed, bool & a_CacheOffByDefault) +{ + AString HeightGenName = a_IniFile.GetValueSet("Generator", "HeightGen", ""); + if (HeightGenName.empty()) + { + LOGWARN("[Generator] HeightGen value not set in world.ini, using \"Biomal\"."); + HeightGenName = "Biomal"; + } + + a_CacheOffByDefault = false; + cTerrainHeightGen * res = nullptr; + if (NoCaseCompare(HeightGenName, "flat") == 0) + { + res = new cHeiGenFlat; + a_CacheOffByDefault = true; // We're generating faster than a cache would retrieve data + } + else if (NoCaseCompare(HeightGenName, "classic") == 0) + { + res = new cHeiGenClassic(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "DistortedHeightmap") == 0) + { + res = new cDistortedHeightmap(a_Seed, a_BiomeGen); + } + else if (NoCaseCompare(HeightGenName, "End") == 0) + { + res = new cEndGen(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "MinMax") == 0) + { + res = new cHeiGenMinMax(a_Seed, a_BiomeGen); + } + else if (NoCaseCompare(HeightGenName, "Mountains") == 0) + { + res = new cHeiGenMountains(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "Noise3D") == 0) + { + res = new cNoise3DComposable(a_Seed); + } + else if (NoCaseCompare(HeightGenName, "biomal") == 0) + { + res = new cHeiGenBiomal(a_Seed, a_BiomeGen); + + /* + // Performance-testing: + LOGINFO("Measuring performance of cHeiGenBiomal..."); + clock_t BeginTick = clock(); + for (int x = 0; x < 500; x++) + { + cChunkDef::HeightMap Heights; + res->GenHeightMap(x * 5, x * 5, Heights); + } + clock_t Duration = clock() - BeginTick; + LOGINFO("HeightGen for 500 chunks took %d ticks (%.02f sec)", Duration, (double)Duration / CLOCKS_PER_SEC); + //*/ + } + else + { + // No match found, force-set the default and retry + LOGWARN("Unknown HeightGen \"%s\", using \"Biomal\" instead.", HeightGenName.c_str()); + a_IniFile.DeleteValue("Generator", "HeightGen"); + a_IniFile.SetValue("Generator", "HeightGen", "Biomal"); + return CreateHeightGen(a_IniFile, a_BiomeGen, a_Seed, a_CacheOffByDefault); + } + + // Read the settings: + res->InitializeHeightGen(a_IniFile); + + return cTerrainHeightGenPtr(res); +} + + + + + diff --git a/src/Generating/HeiGen.h b/src/Generating/HeiGen.h index 5c106c7d9..6ae5ba362 100644 --- a/src/Generating/HeiGen.h +++ b/src/Generating/HeiGen.h @@ -45,7 +45,7 @@ class cHeiGenCache : public cTerrainHeightGen { public: - cHeiGenCache(cTerrainHeightGen & a_HeiGenToCache, int a_CacheSize); // Doesn't take ownership of a_HeiGenToCache + cHeiGenCache(cTerrainHeightGenPtr a_HeiGenToCache, int a_CacheSize); ~cHeiGenCache(); // cTerrainHeightGen overrides: @@ -57,7 +57,7 @@ public: protected: - cTerrainHeightGen & m_HeiGenToCache; + cTerrainHeightGenPtr m_HeiGenToCache; struct sCacheData { @@ -115,7 +115,8 @@ public: protected: int m_Seed; - cRidgedMultiNoise m_Noise; + cRidgedMultiNoise m_MountainNoise; + cRidgedMultiNoise m_DitchNoise; cPerlinNoise m_Perlin; // cTerrainHeightGen overrides: @@ -131,7 +132,7 @@ class cHeiGenBiomal : public cTerrainHeightGen { public: - cHeiGenBiomal(int a_Seed, cBiomeGen & a_BiomeGen) : + cHeiGenBiomal(int a_Seed, cBiomeGenPtr a_BiomeGen) : m_Noise(a_Seed), m_BiomeGen(a_BiomeGen) { @@ -141,8 +142,8 @@ protected: typedef cChunkDef::BiomeMap BiomeNeighbors[3][3]; - cNoise m_Noise; - cBiomeGen & m_BiomeGen; + cNoise m_Noise; + cBiomeGenPtr m_BiomeGen; // Per-biome terrain generator parameters: struct sGenParam diff --git a/src/Generating/IntGen.h b/src/Generating/IntGen.h new file mode 100644 index 000000000..b25e378c0 --- /dev/null +++ b/src/Generating/IntGen.h @@ -0,0 +1,1406 @@ + +// IntGen.h + +// Declares the cIntGen class and descendants for generating and filtering various 2D arrays of ints + +/* +The integers generated may be interpreted in several ways: +- land/see designators + - 0 = ocean + - >0 = land +- biome group + - 0 = ocean + - 1 = desert biomes + - 2 = temperate biomes + - 3 = mountains (hills and forests) + - 4 = ice biomes +- biome group with "bgfRare" flag (for generating rare biomes for the group) +- biome IDs +The interpretation depends on the generator used and on the position in the chain. + +The generators can be chained together - one produces data that another one consumes. +Some of such chain connections require changing the data dimensions between the two, which is handled automatically +by using templates. +*/ + + + + + +#pragma once + +#include "../BiomeDef.h" + + + + + +/** Constants representing the biome group designators. */ +const int bgOcean = 0; +const int bgDesert = 1; +const int bgTemperate = 2; +const int bgMountains = 3; +const int bgIce = 4; +const int bgLandOceanMax = 4; // Maximum biome group value generated in the landOcean generator +const int bgfRare = 1024; // Flag added to values to generate rare biomes for the group + + + + + +/** Interface that all the generator classes provide. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGen +{ +public: + /** Force a virtual destructor in all descendants. + Descendants contain virtual functions and are referred to via pointer-to-base, so they need a virtual destructor. */ + virtual ~cIntGen() {} + + /** Holds the array of values generated by this class (descendant). */ + typedef int Values[SizeX * SizeZ]; + + /** Generates the array of templated size into a_Values, based on given min coords. */ + virtual void GetInts(int a_MinX, int a_MinZ, Values & a_Values) = 0; +}; + + + + + +/** Provides additional cNoise member and its helper functions. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenWithNoise : + public cIntGen<SizeX, SizeZ> +{ + typedef cIntGen<SizeX, SizeZ> super; + +public: + cIntGenWithNoise(int a_Seed) : + m_Noise(a_Seed) + { + } + +protected: + cNoise m_Noise; + + /** Chooses one of a_Val1 or a_Val2, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + return ((rnd & 1) == 0) ? a_Val1 : a_Val2; + } + + /** Chooses one of a_ValN, based on m_Noise and the coordinates for querying the noise. */ + int ChooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + switch (rnd % 4) + { + case 0: return a_Val1; + case 1: return a_Val2; + case 2: return a_Val3; + default: return a_Val4; + } + } +}; + + + + + + +/** Generates a 2D array of random integers in the specified range [0 .. Range). */ +template <int Range, int SizeX, int SizeZ = SizeX> +class cIntGenChoice : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + cIntGenChoice(int a_Seed) : + super(a_Seed) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + for (int z = 0; z < SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + a_Values[x + SizeX * z] = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % Range; + } + } // for z + } +}; + + + + + + +/** Decides between the ocean and landmass biomes. +Has a threshold (in percent) of how much land, the larger the threshold, the more land. +Generates 0 for ocean, biome group ID for landmass. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenLandOcean : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + cIntGenLandOcean(int a_Seed, int a_Threshold) : + super(a_Seed), + m_Threshold(a_Threshold) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + for (int z = 0; z < SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); + a_Values[x + SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 101) % bgLandOceanMax + 1) : 0; + } + } + + // If the centerpoint of the world is within the area, set it to bgTemperate, always: + if ((a_MinX <= 0) && (a_MinZ <= 0) && (a_MinX + SizeX > 0) && (a_MinZ + SizeZ > 0)) + { + a_Values[-a_MinX - a_MinZ * SizeX] = bgTemperate; + } + } + +protected: + int m_Threshold; +}; + + + + + +/** Zooms the underlying value array to twice the size. Uses random-neighbor for the pixels in-between. +This means that the zoome out image is randomly distorted. Applying zoom several times provides all +the distortion that the generators need. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenZoom : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +protected: + static const int m_LowerSizeX = (SizeX / 2) + 2; + static const int m_LowerSizeZ = (SizeZ / 2) + 2; + +public: + typedef std::shared_ptr<cIntGen<m_LowerSizeX, m_LowerSizeZ>> Underlying; + + + cIntGenZoom(int a_Seed, Underlying a_UnderlyingGen) : + super(a_Seed), + m_UnderlyingGen(a_UnderlyingGen) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data with half the resolution: + int lowerMinX = a_MinX >> 1; + int lowerMinZ = a_MinZ >> 1; + int lowerData[m_LowerSizeX * m_LowerSizeZ]; + m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, lowerData); + const int lowStepX = (m_LowerSizeX - 1) * 2; + const int lowStepZ = (m_LowerSizeZ - 1) * 2; + int cache[lowStepX * lowStepZ]; + + // Discreet-interpolate the values into twice the size: + for (int z = 0; z < m_LowerSizeZ - 1; ++z) + { + int idx = (z * 2) * lowStepX; + int PrevZ0 = lowerData[z * m_LowerSizeX]; + int PrevZ1 = lowerData[(z + 1) * m_LowerSizeX]; + + for (int x = 0; x < m_LowerSizeX - 1; ++x) + { + int ValX1Z0 = lowerData[x + 1 + z * m_LowerSizeX]; + int ValX1Z1 = lowerData[x + 1 + (z + 1) * m_LowerSizeX]; + int RndX = (x + lowerMinX) * 2; + int RndZ = (z + lowerMinZ) * 2; + cache[idx] = PrevZ0; + cache[idx + lowStepX] = super::ChooseRandomOne(RndX, RndZ + 1, PrevZ0, PrevZ1); + cache[idx + 1] = super::ChooseRandomOne(RndX, RndZ - 1, PrevZ0, ValX1Z0); + cache[idx + 1 + lowStepX] = super::ChooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx += 2; + PrevZ0 = ValX1Z0; + PrevZ1 = ValX1Z1; + } + } + + // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: + for (int z = 0; z < SizeZ; ++z) + { + memcpy(a_Values + z * SizeX, cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), SizeX * sizeof(int)); + } + } + +protected: + Underlying m_UnderlyingGen; +}; + + + + + +/** Smoothes out some artifacts generated by the zooming - mostly single-pixel values. +Compares each pixel to its neighbors and if the neighbors are equal, changes the pixel to their value. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenSmooth : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + static const int m_LowerSizeX = SizeX + 2; + static const int m_LowerSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr<cIntGen<m_LowerSizeX, m_LowerSizeZ>> Underlying; + + + cIntGenSmooth(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying values: + int lowerData[m_LowerSizeX * m_LowerSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerData); + + // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. + // Also get rid of single-pixel irregularities (A-B-A): + for (int z = 0; z < SizeZ; z++) + { + int NoiseZ = a_MinZ + z; + for (int x = 0; x < SizeX; x++) + { + int val = lowerData[x + 1 + (z + 1) * m_LowerSizeX]; + int above = lowerData[x + 1 + z * m_LowerSizeX]; + int below = lowerData[x + 1 + (z + 2) * m_LowerSizeX]; + int left = lowerData[x + (z + 1) * m_LowerSizeX]; + int right = lowerData[x + 2 + (z + 1) * m_LowerSizeX]; + + if ((left == right) && (above == below)) + { + if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) + { + val = left; + } + else + { + val = above; + } + } + else + { + if (left == right) + { + val = left; + } + + if (above == below) + { + val = above; + } + } + + a_Values[x + z * SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Converts land biomes at the edge of an ocean into the respective beach biome. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenBeaches : + public cIntGen<SizeX, SizeZ> +{ + typedef cIntGen<SizeX, SizeZ> super; + static const int m_UnderlyingSizeX = SizeX + 2; + static const int m_UnderlyingSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr<cIntGen<m_UnderlyingSizeX, m_UnderlyingSizeZ>> Underlying; + + + cIntGenBeaches(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Map for biome -> its beach: + static const int ToBeach[] = + { + /* biOcean */ biOcean, + /* biPlains */ biBeach, + /* biDesert */ biBeach, + /* biExtremeHills */ biStoneBeach, + /* biForest */ biBeach, + /* biTaiga */ biColdBeach, + /* biSwampland */ biSwampland, + /* biRiver */ biRiver, + /* biNether */ biNether, + /* biEnd */ biEnd, + /* biFrozenOcean */ biColdBeach, + /* biFrozenRiver */ biColdBeach, + /* biIcePlains */ biColdBeach, + /* biIceMountains */ biColdBeach, + /* biMushroomIsland */ biMushroomShore, + /* biMushroomShore */ biMushroomShore, + /* biBeach */ biBeach, + /* biDesertHills */ biBeach, + /* biForestHills */ biBeach, + /* biTaigaHills */ biColdBeach, + /* biExtremeHillsEdge */ biStoneBeach, + /* biJungle */ biBeach, + /* biJungleHills */ biBeach, + /* biJungleEdge */ biBeach, + /* biDeepOcean */ biOcean, + /* biStoneBeach */ biStoneBeach, + /* biColdBeach */ biColdBeach, + /* biBirchForest */ biBeach, + /* biBirchForestHills */ biBeach, + /* biRoofedForest */ biBeach, + /* biColdTaiga */ biColdBeach, + /* biColdTaigaHills */ biColdBeach, + /* biMegaTaiga */ biStoneBeach, + /* biMegaTaigaHills */ biStoneBeach, + /* biExtremeHillsPlus */ biStoneBeach, + /* biSavanna */ biBeach, + /* biSavannaPlateau */ biBeach, + /* biMesa */ biMesa, + /* biMesaPlateauF */ biMesa, + /* biMesaPlateau */ biMesa, + }; + + // Generate the underlying values: + int lowerValues[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerValues); + + // Add beaches between ocean and biomes: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int above = lowerValues[x + 1 + z * m_UnderlyingSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int left = lowerValues[x + (z + 1) * m_UnderlyingSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_UnderlyingSizeX]; + if (!IsBiomeOcean(val)) + { + if (IsBiomeOcean(above) || IsBiomeOcean(below) || IsBiomeOcean(left) || IsBiomeOcean(right)) + { + // First convert the value to a regular biome (drop the M flag), then modulo by our biome count: + val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; + } + } + a_Values[x + z * SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Generates the underlying numbers and then randomly changes some ocean group pixels into random land +biome group pixels, based on the predefined chance. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenAddIslands : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenAddIslands(int a_Seed, int a_Chance, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + if (a_Values[x + z * SizeX] == bgOcean) + { + int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * SizeX] = (rnd / 1003) % bgLandOceanMax; + } + } + } // for x + } // for z + } + +protected: + /** Chance, in permille, of an island being generated in ocean. */ + int m_Chance; + + Underlying m_Underlying; +}; + + + + + +/** A filter that adds an edge biome group between two biome groups that need an edge between them. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenBiomeGroupEdges : + public cIntGen<SizeX, SizeZ> +{ + typedef cIntGen<SizeX, SizeZ> super; + + static const int m_UnderlyingSizeX = SizeX + 2; + static const int m_UnderlyingSizeZ = SizeZ + 2; + +public: + + typedef std::shared_ptr<cIntGen<m_UnderlyingSizeX, m_UnderlyingSizeZ>> Underlying; + + cIntGenBiomeGroupEdges(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) + { + // Generate the underlying biome groups: + int lowerValues[m_UnderlyingSizeX * m_UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX, a_MinZ, lowerValues); + + // Change the biomes on incompatible edges into an edge biome: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * m_UnderlyingSizeX]; + int above = lowerValues[x + 1 + z * m_UnderlyingSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_UnderlyingSizeX]; + int left = lowerValues[x + (z + 1) * m_UnderlyingSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_UnderlyingSizeX]; + switch (val) + { + // Desert should neighbor only oceans, desert and temperates; change to temperate when another: + case bgDesert: + { + if ( + !isDesertCompatible(above) || + !isDesertCompatible(below) || + !isDesertCompatible(left) || + !isDesertCompatible(right) + ) + { + val = bgTemperate; + } + break; + } // case bgDesert + + // Ice should not neighbor deserts; change to temperate: + case bgIce: + { + if ( + (above == bgDesert) || + (below == bgDesert) || + (left == bgDesert) || + (right == bgDesert) + ) + { + val = bgTemperate; + } + break; + } // case bgIce + } + a_Values[x + z * SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; + + + inline bool isDesertCompatible(int a_BiomeGroup) + { + switch (a_BiomeGroup) + { + case bgOcean: + case bgDesert: + case bgTemperate: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + + +/** Turns biome group indices into real biomes. +For each pixel, takes its biome group and chooses a random biome from that group; replaces the value with +that biome. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenBiomes : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenBiomes(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Define the per-biome-group biomes: + static const int oceanBiomes[] = + { + biOcean, // biDeepOcean, + }; + + // Same as oceanBiomes, there are no rare oceanic biomes (mushroom islands are handled separately) + static const int rareOceanBiomes[] = + { + biOcean, + }; + + static const int desertBiomes[] = + { + biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, + }; + + static const int rareDesertBiomes[] = + { + biMesaPlateau, biMesaPlateauF, + }; + + static const int temperateBiomes[] = + { + biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, + }; + + static const int rareTemperateBiomes[] = + { + biJungle, // Jungle is not strictly temperate, but let's piggyback it here + }; + + static const int mountainBiomes[] = + { + biExtremeHills, biForest, biTaiga, biPlains, + }; + + static const int rareMountainBiomes[] = + { + biMegaTaiga, + }; + + static const int iceBiomes[] = + { + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, + }; + + // Same as iceBiomes, there's no rare ice biome + static const int rareIceBiomes[] = + { + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, + }; + + static const cBiomesInGroups biomesInGroups[] = + { + /* bgOcean */ { static_cast<int>(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, + /* bgDesert */ { static_cast<int>(ARRAYCOUNT(desertBiomes)), desertBiomes}, + /* bgTemperate */ { static_cast<int>(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, + /* bgMountains */ { static_cast<int>(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, + /* bgIce */ { static_cast<int>(ARRAYCOUNT(iceBiomes)), iceBiomes}, + }; + + static const cBiomesInGroups rareBiomesInGroups[] = + { + /* bgOcean */ { static_cast<int>(ARRAYCOUNT(rareOceanBiomes)), rareOceanBiomes}, + /* bgDesert */ { static_cast<int>(ARRAYCOUNT(rareDesertBiomes)), rareDesertBiomes}, + /* bgTemperate */ { static_cast<int>(ARRAYCOUNT(rareTemperateBiomes)), rareTemperateBiomes}, + /* bgMountains */ { static_cast<int>(ARRAYCOUNT(rareMountainBiomes)), rareMountainBiomes}, + /* bgIce */ { static_cast<int>(ARRAYCOUNT(rareIceBiomes)), rareIceBiomes}, + }; + + // Generate the underlying values, representing biome groups: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Overwrite each biome group with a random biome from that group: + for (int z = 0; z < SizeZ; z++) + { + int IdxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int val = a_Values[x + IdxZ]; + const cBiomesInGroups & Biomes = (val > bgfRare) ? + rareBiomesInGroups[(val & (bgfRare - 1)) % ARRAYCOUNT(rareBiomesInGroups)] : + biomesInGroups[val % ARRAYCOUNT(biomesInGroups)]; + int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); + a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; + } + } + } + +protected: + + struct cBiomesInGroups + { + const int Count; + const int * Biomes; + }; + + + /** The underlying int generator */ + Underlying m_Underlying; +}; + + + + + +/** Randomly replaces pixels of one value to another value, using the given chance. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenReplaceRandomly : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenReplaceRandomly(int a_From, int a_To, int a_Chance, int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_From(a_From), + m_To(a_To), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying values: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Replace some of the values: + for (int z = 0; z < SizeZ; z++) + { + int idxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int idx = x + idxZ; + if (a_Values[idx] == m_From) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[idx] = m_To; + } + } + } + } // for z + } + + +protected: + /** The original value to be replaced. */ + int m_From; + + /** The destination value to which to replace. */ + int m_To; + + /** Chance, in permille, of replacing the value. */ + int m_Chance; + + Underlying m_Underlying; +}; + + + + + +/** Mixer that joins together finalized biomes and rivers. +It first checks for oceans, if there is an ocean in the Biomes, it keeps the ocean. +If there's no ocean, it checks Rivers for a river, if there is a river, it uses the Biomes to select either +regular river or frozen river, based on the biome. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenMixRivers: + public cIntGen<SizeX, SizeZ> +{ + typedef cIntGen<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenMixRivers(Underlying a_Biomes, Underlying a_Rivers): + m_Biomes(a_Biomes), + m_Rivers(a_Rivers) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + m_Biomes->GetInts(a_MinX, a_MinZ, a_Values); + typename super::Values riverData; + m_Rivers->GetInts(a_MinX, a_MinZ, riverData); + + // Mix the values: + for (int z = 0; z < SizeZ; z++) + { + int idxZ = z * SizeX; + for (int x = 0; x < SizeX; x++) + { + int idx = x + idxZ; + if (IsBiomeOcean(a_Values[idx])) + { + // Oceans are kept without any changes + continue; + } + if (riverData[idx] != biRiver) + { + // There's no river, keep the current value + continue; + } + + // There's a river, change the output to a river or a frozen river, based on the original biome: + if (IsBiomeVeryCold((EMCSBiome)a_Values[idx])) + { + a_Values[idx] = biFrozenRiver; + } + else + { + a_Values[idx] = biRiver; + } + } // for x + } // for z + } + +protected: + Underlying m_Biomes; + Underlying m_Rivers; +}; + + + + + +/** Generates a river based on the underlying data. +This is basically an edge detector over the underlying data. The rivers are the edges where the underlying data +changes from one pixel to its neighbor. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenRiver: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + static const int UnderlyingSizeX = SizeX + 2; + static const int UnderlyingSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr<cIntGen<UnderlyingSizeX, UnderlyingSizeZ>> Underlying; + + + cIntGenRiver(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + int Cache[UnderlyingSizeX * UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Detect the edges: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int Above = Cache[x + 1 + z * UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; + int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; + + if ((val == Above) && (val == Below) && (val == Left) && (val == Right)) + { + val = 0; + } + else + { + val = biRiver; + } + a_Values[x + z * SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Turns some of the oceans into the specified biome. Used for mushroom and deep ocean. +The biome is only placed if at least 3 of its neighbors are ocean and only with the specified chance. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenAddToOcean: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + static const int UnderlyingSizeX = SizeX + 2; + static const int UnderlyingSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr<cIntGen<UnderlyingSizeX, UnderlyingSizeZ>> Underlying; + + + cIntGenAddToOcean(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + int Cache[UnderlyingSizeX * UnderlyingSizeZ]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, Cache); + + // Add the mushroom islands: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int val = Cache[x + 1 + (z + 1) * UnderlyingSizeX]; + if (!IsBiomeOcean(val)) + { + a_Values[x + z * SizeX] = val; + continue; + } + + // Count the ocean neighbors: + int Above = Cache[x + 1 + z * UnderlyingSizeX]; + int Below = Cache[x + 1 + (z + 2) * UnderlyingSizeX]; + int Left = Cache[x + (z + 1) * UnderlyingSizeX]; + int Right = Cache[x + 2 + (z + 1) * UnderlyingSizeX]; + int NumOceanNeighbors = 0; + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Below)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Left)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Right)) + { + NumOceanNeighbors += 1; + } + + // If at least 3 ocean neighbors and the chance is right, change: + if ( + (NumOceanNeighbors >= 3) && + ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance) + ) + { + a_Values[x + z * SizeX] = m_ToValue; + } + else + { + a_Values[x + z * SizeX] = val; + } + } // for x + } // for z + } + +protected: + /** Chance, in permille, of changing the biome. */ + int m_Chance; + + /** The value to change the ocean into. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + +/** Changes random pixels of the underlying data to the specified value. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenSetRandomly : + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + cIntGenSetRandomly(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Change random pixels to bgOcean: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * SizeX] = m_ToValue; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel. */ + int m_Chance; + + /** The value to which to set the pixel. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + + +/** Adds a "rare" flag to random biome groups, based on the given chance. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenRareBiomeGroups: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenRareBiomeGroups(int a_Seed, int a_Chance, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + + // Change some of the biome groups into rare biome groups: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + int idx = x + SizeX * z; + a_Values[idx] = a_Values[idx] | bgfRare; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel into the rare biome group. */ + int m_Chance; + + /** The underlying generator. */ + Underlying m_Underlying; +}; + + + + + +/** Changes biomes in the parent data into an alternate versions (usually "hill" variants), in such places +that have their alterations set. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenAlternateBiomes: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenAlternateBiomes(int a_Seed, Underlying a_Alterations, Underlying a_BaseBiomes): + super(a_Seed), + m_Alterations(a_Alterations), + m_BaseBiomes(a_BaseBiomes) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the base biomes and the alterations: + m_BaseBiomes->GetInts(a_MinX, a_MinZ, a_Values); + typename super::Values alterations; + m_Alterations->GetInts(a_MinX, a_MinZ, alterations); + + // Change the biomes into their alternate versions: + for (int idx = 0; idx < SizeX * SizeZ; ++idx) + { + if (alterations[idx] == 0) + { + // No change + continue; + } + + // Change to alternate biomes: + int val = a_Values[idx]; + switch (val) + { + case biBirchForest: val = biBirchForestHills; break; + case biDesert: val = biDesertHills; break; + case biExtremeHills: val = biExtremeHillsPlus; break; + case biForest: val = biForestHills; break; + case biIcePlains: val = biIceMountains; break; + case biJungle: val = biJungleHills; break; + case biMegaTaiga: val = biMegaTaigaHills; break; + case biMesaPlateau: val = biMesa; break; + case biMesaPlateauF: val = biMesa; break; + case biMesaPlateauM: val = biMesa; break; + case biMesaPlateauFM: val = biMesa; break; + case biPlains: val = biForest; break; + case biRoofedForest: val = biPlains; break; + case biSavanna: val = biSavannaPlateau; break; + case biTaiga: val = biTaigaHills; break; + } + a_Values[idx] = val; + } // for idx - a_Values[] + } + +protected: + Underlying m_Alterations; + Underlying m_BaseBiomes; +}; + + + + + +/** Adds an edge between two specifically incompatible biomes, such as mesa and forest. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenBiomeEdges: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + static const int m_LowerSizeX = SizeX + 2; + static const int m_LowerSizeZ = SizeZ + 2; + +public: + typedef std::shared_ptr<cIntGen<m_LowerSizeX, m_LowerSizeZ>> Underlying; + + + cIntGenBiomeEdges(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying biomes: + typename Underlying::element_type::Values lowerValues; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerValues); + + // Convert incompatible edges into neutral biomes: + for (int z = 0; z < SizeZ; z++) + { + for (int x = 0; x < SizeX; x++) + { + int biome = lowerValues[x + 1 + (z + 1) * m_LowerSizeX]; + int above = lowerValues[x + 1 + z * m_LowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * m_LowerSizeX]; + int left = lowerValues[x + (z + 1) * m_LowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * m_LowerSizeX]; + + switch (biome) + { + case biDesert: + case biDesertM: + case biDesertHills: + { + if ( + IsBiomeVeryCold(static_cast<EMCSBiome>(above)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(below)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(left)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(right)) + ) + { + biome = biPlains; + } + break; + } // case biDesert + + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + { + if ( + !isMesaCompatible(above) || + !isMesaCompatible(below) || + !isMesaCompatible(left) || + !isMesaCompatible(right) + ) + { + biome = biDesert; + } + break; + } // Mesa biomes + + case biJungle: + case biJungleM: + { + if ( + !isJungleCompatible(above) || + !isJungleCompatible(below) || + !isJungleCompatible(left) || + !isJungleCompatible(right) + ) + { + biome = (biome == biJungle) ? biJungleEdge : biJungleEdgeM; + } + break; + } // Jungle biomes + + case biSwampland: + case biSwamplandM: + { + if ( + IsBiomeNoDownfall(static_cast<EMCSBiome>(above)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(below)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(left)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(right)) + ) + { + biome = biPlains; + } + break; + } // Swampland biomes + } // switch (biome) + + a_Values[x + z * SizeX] = biome; + } // for x + } // for z + } + + +protected: + Underlying m_Underlying; + + + bool isMesaCompatible(int a_Biome) + { + switch (a_Biome) + { + case biDesert: + case biMesa: + case biMesaBryce: + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + case biOcean: + case biDeepOcean: + { + return true; + } + default: + { + return false; + } + } + } + + + bool isJungleCompatible(int a_Biome) + { + switch (a_Biome) + { + case biJungle: + case biJungleM: + case biJungleEdge: + case biJungleEdgeM: + case biJungleHills: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + + +/** Changes biomes in the parent data into their alternate versions ("M" variants), in such places that +have their alterations set. */ +template <int SizeX, int SizeZ = SizeX> +class cIntGenMBiomes: + public cIntGenWithNoise<SizeX, SizeZ> +{ + typedef cIntGenWithNoise<SizeX, SizeZ> super; + +public: + typedef std::shared_ptr<cIntGen<SizeX, SizeZ>> Underlying; + + + cIntGenMBiomes(int a_Seed, Underlying a_Alteration, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying), + m_Alteration(a_Alteration) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, typename super::Values & a_Values) override + { + // Generate the underlying biomes and the alterations: + m_Underlying->GetInts(a_MinX, a_MinZ, a_Values); + typename super::Values alterations; + m_Alteration->GetInts(a_MinX, a_MinZ, alterations); + + // Wherever alterations are nonzero, change into alternate biome, if available: + for (int idx = 0; idx < SizeX * SizeZ; ++idx) + { + if (alterations[idx] == 0) + { + continue; + } + + // Ice spikes biome was removed from here, because it was generated way too often + switch (a_Values[idx]) + { + case biPlains: a_Values[idx] = biSunflowerPlains; break; + case biDesert: a_Values[idx] = biDesertM; break; + case biExtremeHills: a_Values[idx] = biExtremeHillsM; break; + case biForest: a_Values[idx] = biFlowerForest; break; + case biTaiga: a_Values[idx] = biTaigaM; break; + case biSwampland: a_Values[idx] = biSwamplandM; break; + case biJungle: a_Values[idx] = biJungleM; break; + case biJungleEdge: a_Values[idx] = biJungleEdgeM; break; + case biBirchForest: a_Values[idx] = biBirchForestM; break; + case biBirchForestHills: a_Values[idx] = biBirchForestHillsM; break; + case biRoofedForest: a_Values[idx] = biRoofedForestM; break; + case biColdTaiga: a_Values[idx] = biColdTaigaM; break; + case biMegaSpruceTaiga: a_Values[idx] = biMegaSpruceTaiga; break; + case biMegaSpruceTaigaHills: a_Values[idx] = biMegaSpruceTaigaHills; break; + case biExtremeHillsPlus: a_Values[idx] = biExtremeHillsPlusM; break; + case biSavanna: a_Values[idx] = biSavannaM; break; + case biSavannaPlateau: a_Values[idx] = biSavannaPlateauM; break; + case biMesa: a_Values[idx] = biMesaBryce; break; + case biMesaPlateauF: a_Values[idx] = biMesaPlateauFM; break; + case biMesaPlateau: a_Values[idx] = biMesaBryce; break; + } + } // for idx - a_Values[] / alterations[] + } + +protected: + Underlying m_Underlying; + Underlying m_Alteration; +}; + + + + diff --git a/src/Generating/MineShafts.cpp b/src/Generating/MineShafts.cpp index 0532aff39..55b3b64dd 100644 --- a/src/Generating/MineShafts.cpp +++ b/src/Generating/MineShafts.cpp @@ -112,7 +112,7 @@ class cMineShaftCorridor : public: /** Creates a new Corridor attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -165,7 +165,7 @@ class cMineShaftCrossing : public: /** Creates a new Crossing attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -199,7 +199,7 @@ public: /** Creates a new Staircase attached to the specified pivot point and direction. Checks all ParentSystem's objects and disallows intersecting. Initializes the new object to fit. - May return NULL if cannot fit. + May return nullptr if cannot fit. */ static cMineShaft * CreateAndFit( cStructGenMineShafts::cMineShaftSystem & a_ParentSystem, @@ -351,7 +351,7 @@ void cStructGenMineShafts::cMineShaftSystem::AppendBranch( return; } - cMineShaft * Next = NULL; + cMineShaft * Next = nullptr; int rnd = (a_Noise.IntNoise3DInt(a_PivotX, a_PivotY + a_RecursionLevel * 16, a_PivotZ) / 13) % m_ProbLevelStaircase; if (rnd < m_ProbLevelCorridor) { @@ -365,7 +365,7 @@ void cStructGenMineShafts::cMineShaftSystem::AppendBranch( { Next = cMineShaftStaircase::CreateAndFit(*this, a_PivotX, a_PivotY, a_PivotZ, a_Direction, a_Noise); } - if (Next == NULL) + if (Next == nullptr) { return; } @@ -552,7 +552,7 @@ cMineShaft * cMineShaftCorridor::CreateAndFit( } if (!a_ParentSystem.CanAppend(BoundingBox)) { - return NULL; + return nullptr; } return new cMineShaftCorridor(a_ParentSystem, BoundingBox, NumSegments, a_Direction, a_Noise); } @@ -796,7 +796,7 @@ void cMineShaftCorridor::PlaceChest(cChunkDesc & a_ChunkDesc) { a_ChunkDesc.SetBlockTypeMeta(x, m_BoundingBox.p1.y + 1, z, E_BLOCK_CHEST, Meta); cChestEntity * ChestEntity = (cChestEntity *)a_ChunkDesc.GetBlockEntity(x, m_BoundingBox.p1.y + 1, z); - ASSERT((ChestEntity != NULL) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); + ASSERT((ChestEntity != nullptr) && (ChestEntity->GetBlockType() == E_BLOCK_CHEST)); cNoise Noise(a_ChunkDesc.GetChunkX() ^ a_ChunkDesc.GetChunkZ()); int NumSlots = 3 + ((Noise.IntNoise3DInt(x, m_BoundingBox.p1.y, z) / 11) % 4); int Seed = Noise.IntNoise2DInt(x, z); @@ -1006,7 +1006,7 @@ cMineShaft * cMineShaftCrossing::CreateAndFit( } if (!a_ParentSystem.CanAppend(BoundingBox)) { - return NULL; + return nullptr; } return new cMineShaftCrossing(a_ParentSystem, BoundingBox); } @@ -1157,7 +1157,7 @@ cMineShaft * cMineShaftStaircase::CreateAndFit( } if (!a_ParentSystem.CanAppend(Box)) { - return NULL; + return nullptr; } return new cMineShaftStaircase(a_ParentSystem, Box, a_Direction, Slope); } diff --git a/src/Generating/Noise3DGenerator.cpp b/src/Generating/Noise3DGenerator.cpp index c3ca30384..5a4cb44cf 100644 --- a/src/Generating/Noise3DGenerator.cpp +++ b/src/Generating/Noise3DGenerator.cpp @@ -6,7 +6,7 @@ #include "Globals.h" #include "Noise3DGenerator.h" #include "../OSSupport/File.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "../LinearInterpolation.h" #include "../LinearUpscale.h" diff --git a/src/Generating/PieceGenerator.cpp b/src/Generating/PieceGenerator.cpp index ae4b6e36c..97aa646fc 100644 --- a/src/Generating/PieceGenerator.cpp +++ b/src/Generating/PieceGenerator.cpp @@ -289,7 +289,7 @@ cPlacedPiece::cPlacedPiece(const cPlacedPiece * a_Parent, const cPiece & a_Piece m_NumCCWRotations(a_NumCCWRotations), m_HasBeenMovedToGround(false) { - m_Depth = (m_Parent == NULL) ? 0 : (m_Parent->GetDepth() + 1); + m_Depth = (m_Parent == nullptr) ? 0 : (m_Parent->GetDepth() + 1); m_HitBox = a_Piece.RotateMoveHitBox(a_NumCCWRotations, a_Coords.x, a_Coords.y, a_Coords.z); m_HitBox.Sort(); } @@ -402,7 +402,7 @@ cPlacedPiece * cPieceGenerator::PlaceStartingPiece(int a_BlockX, int a_BlockY, i } int Rotation = Rotations[rnd % NumRotations]; - cPlacedPiece * res = new cPlacedPiece(NULL, *StartingPiece, Vector3i(a_BlockX, a_BlockY, a_BlockZ), Rotation); + cPlacedPiece * res = new cPlacedPiece(nullptr, *StartingPiece, Vector3i(a_BlockX, a_BlockY, a_BlockZ), Rotation); // Place the piece's connectors into a_OutConnectors: const cPiece::cConnectors & Conn = StartingPiece->GetConnectors(); diff --git a/src/Generating/Prefab.cpp b/src/Generating/Prefab.cpp index 6da3c3d10..761986690 100644 --- a/src/Generating/Prefab.cpp +++ b/src/Generating/Prefab.cpp @@ -328,7 +328,7 @@ void cPrefab::AddConnector(int a_RelX, int a_RelY, int a_RelZ, eBlockFace a_Dire void cPrefab::ParseCharMap(CharMap & a_CharMapOut, const char * a_CharMapDef) { - ASSERT(a_CharMapDef != NULL); + ASSERT(a_CharMapDef != nullptr); // Initialize the charmap to all-invalid values: for (size_t i = 0; i < ARRAYCOUNT(a_CharMapOut); i++) @@ -389,7 +389,7 @@ void cPrefab::ParseBlockImage(const CharMap & a_CharMap, const char * a_BlockIma void cPrefab::ParseConnectors(const char * a_ConnectorsDef) { - ASSERT(a_ConnectorsDef != NULL); + ASSERT(a_ConnectorsDef != nullptr); AStringVector Lines = StringSplitAndTrim(a_ConnectorsDef, "\n"); for (AStringVector::const_iterator itr = Lines.begin(), end = Lines.end(); itr != end; ++itr) @@ -436,7 +436,7 @@ void cPrefab::ParseConnectors(const char * a_ConnectorsDef) void cPrefab::ParseDepthWeight(const char * a_DepthWeightDef) { // The member needn't be defined at all, if so, skip: - if (a_DepthWeightDef == NULL) + if (a_DepthWeightDef == nullptr) { return; } diff --git a/src/Generating/PrefabPiecePool.cpp b/src/Generating/PrefabPiecePool.cpp index 122b9d2af..895555ef8 100644 --- a/src/Generating/PrefabPiecePool.cpp +++ b/src/Generating/PrefabPiecePool.cpp @@ -16,7 +16,7 @@ cPrefabPiecePool::cPrefabPiecePool( ) { AddPieceDefs(a_PieceDefs, a_NumPieceDefs); - if (a_StartingPieceDefs != NULL) + if (a_StartingPieceDefs != nullptr) { AddStartingPieceDefs(a_StartingPieceDefs, a_NumStartingPieceDefs); } @@ -56,7 +56,7 @@ void cPrefabPiecePool::Clear(void) void cPrefabPiecePool::AddPieceDefs(const cPrefab::sDef * a_PieceDefs, size_t a_NumPieceDefs) { - ASSERT(a_PieceDefs != NULL); + ASSERT(a_PieceDefs != nullptr); for (size_t i = 0; i < a_NumPieceDefs; i++) { cPrefab * Prefab = new cPrefab(a_PieceDefs[i]); @@ -71,7 +71,7 @@ void cPrefabPiecePool::AddPieceDefs(const cPrefab::sDef * a_PieceDefs, size_t a_ void cPrefabPiecePool::AddStartingPieceDefs(const cPrefab::sDef * a_StartingPieceDefs, size_t a_NumStartingPieceDefs) { - ASSERT(a_StartingPieceDefs != NULL); + ASSERT(a_StartingPieceDefs != nullptr); for (size_t i = 0; i < a_NumStartingPieceDefs; i++) { cPrefab * Prefab = new cPrefab(a_StartingPieceDefs[i]); diff --git a/src/Generating/Prefabs/CMakeLists.txt b/src/Generating/Prefabs/CMakeLists.txt index 2c62aa73d..68f6491c4 100644 --- a/src/Generating/Prefabs/CMakeLists.txt +++ b/src/Generating/Prefabs/CMakeLists.txt @@ -29,5 +29,5 @@ SET (HDRS if(NOT MSVC) add_library(Generating_Prefabs ${SRCS} ${HDRS}) - target_link_libraries(Generating_Prefabs OSSupport iniFile Blocks) + target_link_libraries(Generating_Prefabs OSSupport Blocks) endif() diff --git a/src/Generating/ProtIntGen.h b/src/Generating/ProtIntGen.h new file mode 100644 index 000000000..73ed27096 --- /dev/null +++ b/src/Generating/ProtIntGen.h @@ -0,0 +1,1351 @@ + +// ProtIntGen.h + +// Declares the prototyping integer generators - cProtIntGen class and its descendants + +/* +These classes generate 2D arrays of integers that have various interpretations. The main purpose of these +classes is to provide fast prototyping for cIntGen classes - unlike cIntGen classes, these are not +template-based and so they take care of the underlying sizes automatically. This makes them easier to chain +and re-chain, since the size parameters don't need to be adjusted after each such case. Their performance is, +however, slightly worse, which is why we use cIntGen classes in the final generator. + +Because there is no SizeX / SizeZ template param, the generators would have to either alloc memory for each +underlying generator's values, or use a maximum-size buffer. We chose the latter, to avoid memory allocation +overhead; this however means that there's (an arbitrary) limit to the size of the generated data. +*/ + + + + + +#pragma once + +// We need the biome group constants defined there: +#include "IntGen.h" + + + + + +/** Interface that all the generator classes provide. */ +class cProtIntGen +{ +protected: + /** Maximum size of the generated area. + Adjust the constant if you need larger areas, these are just so that we can use fixed-size buffers. */ + static const int m_BufferSize = 900; + +public: + + /** Type of the generic interface used for storing links to the underlying generators. */ + typedef std::shared_ptr<cProtIntGen> Underlying; + + + /** Force a virtual destructor in all descendants. + Descendants contain virtual functions and are referred to via pointer-to-base, so they need a virtual destructor. */ + virtual ~cProtIntGen() {} + + /** Generates the array of specified size into a_Values, based on given min coords. */ + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) = 0; +}; + + + + + +/** Provides additional cNoise member and its helper functions. */ +class cProtIntGenWithNoise : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenWithNoise(int a_Seed) : + m_Noise(a_Seed) + { + } + +protected: + cNoise m_Noise; + + /** Chooses one of a_Val1 or a_Val2, based on m_Noise and the coordinates for querying the noise. */ + int chooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + return ((rnd & 1) == 0) ? a_Val1 : a_Val2; + } + + /** Chooses one of a_ValN, based on m_Noise and the coordinates for querying the noise. */ + int chooseRandomOne(int a_RndX, int a_RndZ, int a_Val1, int a_Val2, int a_Val3, int a_Val4) + { + int rnd = m_Noise.IntNoise2DInt(a_RndX, a_RndZ) / 7; + switch (rnd % 4) + { + case 0: return a_Val1; + case 1: return a_Val2; + case 2: return a_Val3; + default: return a_Val4; + } + } +}; + + + + + + +/** Generates a 2D array of random integers in the specified range [0 .. Range). */ +class cProtIntGenChoice : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenChoice(int a_Seed, int a_Range) : + super(a_Seed), + m_Range(a_Range) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + for (int z = 0; z < a_SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + a_Values[x + a_SizeX * z] = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7) % m_Range; + } + } // for z + } + +protected: + int m_Range; +}; + + + + + + +/** Decides between the ocean and landmass biomes. +Has a threshold (in percent) of how much land, the larger the threshold, the more land. +Generates 0 for ocean, biome group ID for landmass. */ +class cProtIntGenLandOcean : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenLandOcean(int a_Seed, int a_Threshold) : + super(a_Seed), + m_Threshold(a_Threshold) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + for (int z = 0; z < a_SizeZ; z++) + { + int BaseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + int rnd = (super::m_Noise.IntNoise2DInt(a_MinX + x, BaseZ) / 7); + a_Values[x + a_SizeX * z] = ((rnd % 100) < m_Threshold) ? ((rnd / 101) % bgLandOceanMax + 1) : 0; + } + } + + // If the centerpoint of the world is within the area, set it to bgTemperate, always: + if ((a_MinX <= 0) && (a_MinZ <= 0) && (a_MinX + a_SizeX > 0) && (a_MinZ + a_SizeZ > 0)) + { + a_Values[-a_MinX - a_MinZ * a_SizeX] = bgTemperate; + } + } + +protected: + int m_Threshold; +}; + + + + + +/** Zooms the underlying value array to twice the size. Uses random-neighbor for the pixels in-between. +This means that the zoome out image is randomly distorted. Applying zoom several times provides all +the distortion that the generators need. */ +class cProtIntGenZoom : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenZoom(int a_Seed, Underlying a_UnderlyingGen) : + super(a_Seed), + m_UnderlyingGen(a_UnderlyingGen) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Get the coords for the lower generator: + int lowerMinX = a_MinX >> 1; + int lowerMinZ = a_MinZ >> 1; + int lowerSizeX = a_SizeX / 2 + 2; + int lowerSizeZ = a_SizeZ / 2 + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + ASSERT(lowerSizeX > 0); + ASSERT(lowerSizeZ > 0); + + // Generate the underlying data with half the resolution: + int lowerData[m_BufferSize]; + m_UnderlyingGen->GetInts(lowerMinX, lowerMinZ, lowerSizeX, lowerSizeZ, lowerData); + const int lowStepX = (lowerSizeX - 1) * 2; + int cache[m_BufferSize]; + + // Discreet-interpolate the values into twice the size: + for (int z = 0; z < lowerSizeZ - 1; ++z) + { + int idx = (z * 2) * lowStepX; + int PrevZ0 = lowerData[z * lowerSizeX]; + int PrevZ1 = lowerData[(z + 1) * lowerSizeX]; + + for (int x = 0; x < lowerSizeX - 1; ++x) + { + int ValX1Z0 = lowerData[x + 1 + z * lowerSizeX]; + int ValX1Z1 = lowerData[x + 1 + (z + 1) * lowerSizeX]; + int RndX = (x + lowerMinX) * 2; + int RndZ = (z + lowerMinZ) * 2; + cache[idx] = PrevZ0; + cache[idx + lowStepX] = super::chooseRandomOne(RndX, RndZ + 1, PrevZ0, PrevZ1); + cache[idx + 1] = super::chooseRandomOne(RndX, RndZ - 1, PrevZ0, ValX1Z0); + cache[idx + 1 + lowStepX] = super::chooseRandomOne(RndX, RndZ, PrevZ0, ValX1Z0, PrevZ1, ValX1Z1); + idx += 2; + PrevZ0 = ValX1Z0; + PrevZ1 = ValX1Z1; + } + } + + // Copy from Cache into a_Values; take into account the even/odd offsets in a_Min: + for (int z = 0; z < a_SizeZ; ++z) + { + memcpy(a_Values + z * a_SizeX, cache + (z + (a_MinZ & 1)) * lowStepX + (a_MinX & 1), a_SizeX * sizeof(int)); + } + } + +protected: + Underlying m_UnderlyingGen; +}; + + + + + +/** Smoothes out some artifacts generated by the zooming - mostly single-pixel values. +Compares each pixel to its neighbors and if the neighbors are equal, changes the pixel to their value. */ +class cProtIntGenSmooth : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenSmooth(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying values: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerData[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerData); + + // Smooth - for each square check if the surroundings are the same, if so, expand them diagonally. + // Also get rid of single-pixel irregularities (A-B-A): + for (int z = 0; z < a_SizeZ; z++) + { + int NoiseZ = a_MinZ + z; + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerData[x + 1 + (z + 1) * lowerSizeX]; + int above = lowerData[x + 1 + z * lowerSizeX]; + int below = lowerData[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerData[x + (z + 1) * lowerSizeX]; + int right = lowerData[x + 2 + (z + 1) * lowerSizeX]; + + if ((left == right) && (above == below)) + { + if (((super::m_Noise.IntNoise2DInt(a_MinX + x, NoiseZ) / 7) % 2) == 0) + { + val = left; + } + else + { + val = above; + } + } + else + { + if (left == right) + { + val = left; + } + + if (above == below) + { + val = above; + } + } + + a_Values[x + z * a_SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Converts land biomes at the edge of an ocean into the respective beach biome. */ +class cProtIntGenBeaches : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenBeaches(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Map for biome -> its beach: + static const int ToBeach[] = + { + /* biOcean */ biOcean, + /* biPlains */ biBeach, + /* biDesert */ biBeach, + /* biExtremeHills */ biStoneBeach, + /* biForest */ biBeach, + /* biTaiga */ biColdBeach, + /* biSwampland */ biSwampland, + /* biRiver */ biRiver, + /* biNether */ biNether, + /* biEnd */ biEnd, + /* biFrozenOcean */ biColdBeach, + /* biFrozenRiver */ biColdBeach, + /* biIcePlains */ biColdBeach, + /* biIceMountains */ biColdBeach, + /* biMushroomIsland */ biMushroomShore, + /* biMushroomShore */ biMushroomShore, + /* biBeach */ biBeach, + /* biDesertHills */ biBeach, + /* biForestHills */ biBeach, + /* biTaigaHills */ biColdBeach, + /* biExtremeHillsEdge */ biStoneBeach, + /* biJungle */ biBeach, + /* biJungleHills */ biBeach, + /* biJungleEdge */ biBeach, + /* biDeepOcean */ biOcean, + /* biStoneBeach */ biStoneBeach, + /* biColdBeach */ biColdBeach, + /* biBirchForest */ biBeach, + /* biBirchForestHills */ biBeach, + /* biRoofedForest */ biBeach, + /* biColdTaiga */ biColdBeach, + /* biColdTaigaHills */ biColdBeach, + /* biMegaTaiga */ biStoneBeach, + /* biMegaTaigaHills */ biStoneBeach, + /* biExtremeHillsPlus */ biStoneBeach, + /* biSavanna */ biBeach, + /* biSavannaPlateau */ biBeach, + /* biMesa */ biMesa, + /* biMesaPlateauF */ biMesa, + /* biMesaPlateau */ biMesa, + }; + + // Generate the underlying values: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Add beaches between ocean and biomes: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int above = lowerValues[x + 1 + z * lowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerValues[x + (z + 1) * lowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + if (!IsBiomeOcean(val)) + { + if (IsBiomeOcean(above) || IsBiomeOcean(below) || IsBiomeOcean(left) || IsBiomeOcean(right)) + { + // First convert the value to a regular biome (drop the M flag), then modulo by our biome count: + val = ToBeach[(val % 128) % ARRAYCOUNT(ToBeach)]; + } + } + a_Values[x + z * a_SizeX] = val; + } + } + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Generates the underlying numbers and then randomly changes some ocean group pixels into random land +biome group pixels, based on the predefined chance. */ +class cProtIntGenAddIslands : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + typedef std::shared_ptr<cProtIntGen> Underlying; + + + cProtIntGenAddIslands(int a_Seed, int a_Chance, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + if (a_Values[x + z * a_SizeX] == bgOcean) + { + int rnd = super::m_Noise.IntNoise2DInt(a_MinX + x, a_MinZ + z) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * a_SizeX] = (rnd / 1003) % bgLandOceanMax; + } + } + } + } + } + +protected: + /** Chance of each ocean pixel being converted, in permille. */ + int m_Chance; + + Underlying m_Underlying; +}; + + + + + +/** A filter that adds an edge biome group between two biome groups that need an edge between them. */ +class cProtIntGenBiomeGroupEdges : + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenBiomeGroupEdges(Underlying a_Underlying) : + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) + { + // Generate the underlying biome groups: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX, a_MinZ, lowerSizeX, lowerSizeZ, lowerValues); + + // Change the biomes on incompatible edges into an edge biome: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + switch (val) + { + // Desert should neighbor only oceans, desert and temperates; change to temperate when another: + case bgDesert: + { + if ( + !isDesertCompatible(Above) || + !isDesertCompatible(Below) || + !isDesertCompatible(Left) || + !isDesertCompatible(Right) + ) + { + val = bgTemperate; + } + break; + } // case bgDesert + + // Ice should not neighbor deserts; change to temperate: + case bgIce: + { + if ( + (Above == bgDesert) || + (Below == bgDesert) || + (Left == bgDesert) || + (Right == bgDesert) + ) + { + val = bgTemperate; + } + break; + } // case bgIce + } + a_Values[x + z * a_SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; + + + inline bool isDesertCompatible(int a_BiomeGroup) + { + switch (a_BiomeGroup) + { + case bgOcean: + case bgDesert: + case bgTemperate: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + + +/** Turns biome group indices into real biomes. +For each pixel, takes its biome group and chooses a random biome from that group; replaces the value with +that biome. */ +class cProtIntGenBiomes : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenBiomes(int a_Seed, Underlying a_Underlying) : + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Define the per-biome-group biomes: + static const int oceanBiomes[] = + { + biOcean, // biDeepOcean, + }; + + // Same as oceanBiomes, there are no rare oceanic biomes (mushroom islands are handled separately) + static const int rareOceanBiomes[] = + { + biOcean, + }; + + static const int desertBiomes[] = + { + biDesert, biDesert, biDesert, biDesert, biDesert, biDesert, biSavanna, biSavanna, biPlains, + }; + + static const int rareDesertBiomes[] = + { + biMesaPlateau, biMesaPlateauF, + }; + + static const int temperateBiomes[] = + { + biForest, biForest, biRoofedForest, biExtremeHills, biPlains, biBirchForest, biSwampland, + }; + + static const int rareTemperateBiomes[] = + { + biJungle, // Jungle is not strictly temperate, but let's piggyback it here + }; + + static const int mountainBiomes[] = + { + biExtremeHills, biForest, biTaiga, biPlains, + }; + + static const int rareMountainBiomes[] = + { + biMegaTaiga, + }; + + static const int iceBiomes[] = + { + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, + }; + + // Same as iceBiomes, there's no rare ice biome + static const int rareIceBiomes[] = + { + biIcePlains, biIcePlains, biIcePlains, biIcePlains, biColdTaiga, + }; + + static const cBiomesInGroups biomesInGroups[] = + { + /* bgOcean */ { static_cast<int>(ARRAYCOUNT(oceanBiomes)), oceanBiomes}, + /* bgDesert */ { static_cast<int>(ARRAYCOUNT(desertBiomes)), desertBiomes}, + /* bgTemperate */ { static_cast<int>(ARRAYCOUNT(temperateBiomes)), temperateBiomes}, + /* bgMountains */ { static_cast<int>(ARRAYCOUNT(mountainBiomes)), mountainBiomes}, + /* bgIce */ { static_cast<int>(ARRAYCOUNT(iceBiomes)), iceBiomes}, + }; + + static const cBiomesInGroups rareBiomesInGroups[] = + { + /* bgOcean */ { static_cast<int>(ARRAYCOUNT(rareOceanBiomes)), rareOceanBiomes}, + /* bgDesert */ { static_cast<int>(ARRAYCOUNT(rareDesertBiomes)), rareDesertBiomes}, + /* bgTemperate */ { static_cast<int>(ARRAYCOUNT(rareTemperateBiomes)), rareTemperateBiomes}, + /* bgMountains */ { static_cast<int>(ARRAYCOUNT(rareMountainBiomes)), rareMountainBiomes}, + /* bgIce */ { static_cast<int>(ARRAYCOUNT(rareIceBiomes)), rareIceBiomes}, + }; + + // Generate the underlying values, representing biome groups: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Overwrite each biome group with a random biome from that group: + // Take care of the bgfRare flag + for (int z = 0; z < a_SizeZ; z++) + { + int IdxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int val = a_Values[x + IdxZ]; + const cBiomesInGroups & Biomes = (val > bgfRare) ? + rareBiomesInGroups[(val & (bgfRare - 1)) % ARRAYCOUNT(rareBiomesInGroups)] : + biomesInGroups[val % ARRAYCOUNT(biomesInGroups)]; + int rnd = (super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7); + a_Values[x + IdxZ] = Biomes.Biomes[rnd % Biomes.Count]; + } + } + } + +protected: + + struct cBiomesInGroups + { + const int Count; + const int * Biomes; + }; + + + /** The underlying int generator */ + Underlying m_Underlying; +}; + + + + + +/** Randomly replaces pixels of one value to another value, using the given chance. */ +class cProtIntGenReplaceRandomly : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + typedef std::shared_ptr<cProtIntGen> Underlying; + + + cProtIntGenReplaceRandomly(int a_Seed, int a_From, int a_To, int a_Chance, Underlying a_Underlying) : + super(a_Seed), + m_From(a_From), + m_To(a_To), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying values: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Replace some of the values: + for (int z = 0; z < a_SizeZ; z++) + { + int idxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int idx = x + idxZ; + if (a_Values[idx] == m_From) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[idx] = m_To; + } + } + } + } // for z + } + + +protected: + /** The original value to be replaced. */ + int m_From; + + /** The destination value to which to replace. */ + int m_To; + + /** Chance, in permille, of replacing the value. */ + int m_Chance; + + Underlying m_Underlying; +}; + + + + + +/** Mixer that joins together finalized biomes and rivers. +It first checks for oceans, if there is an ocean in the Biomes, it keeps the ocean. +If there's no ocean, it checks Rivers for a river, if there is a river, it uses the Biomes to select either +regular river or frozen river, based on the biome. */ +class cProtIntGenMixRivers: + public cProtIntGen +{ + typedef cProtIntGen super; + +public: + cProtIntGenMixRivers(Underlying a_Biomes, Underlying a_Rivers): + m_Biomes(a_Biomes), + m_Rivers(a_Rivers) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + ASSERT(a_SizeX * a_SizeZ <= m_BufferSize); + m_Biomes->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int riverData[m_BufferSize]; + m_Rivers->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, riverData); + + // Mix the values: + for (int z = 0; z < a_SizeZ; z++) + { + int idxZ = z * a_SizeX; + for (int x = 0; x < a_SizeX; x++) + { + int idx = x + idxZ; + if (IsBiomeOcean(a_Values[idx])) + { + // Oceans are kept without any changes + continue; + } + if (riverData[idx] != biRiver) + { + // There's no river, keep the current value + continue; + } + + // There's a river, change the output to a river or a frozen river, based on the original biome: + if (IsBiomeVeryCold((EMCSBiome)a_Values[idx])) + { + a_Values[idx] = biFrozenRiver; + } + else + { + a_Values[idx] = biRiver; + } + } // for x + } // for z + } + +protected: + Underlying m_Biomes; + Underlying m_Rivers; +}; + + + + + +/** Generates a river based on the underlying data. +This is basically an edge detector over the underlying data. The rivers are the edges where the underlying +data changes from one pixel to its neighbor. */ +class cProtIntGenRiver: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenRiver(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Detect the edges: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + + if ((val == Above) && (val == Below) && (val == Left) && (val == Right)) + { + val = 0; + } + else + { + val = biRiver; + } + a_Values[x + z * a_SizeX] = val; + } // for x + } // for z + } + +protected: + Underlying m_Underlying; +}; + + + + + +/** Turns some of the oceans into the specified biome. Used for mushroom and deep ocean. +The biome is only placed if at least 3 of its neighbors are ocean and only with the specified chance. */ +class cProtIntGenAddToOcean: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenAddToOcean(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Add the mushroom islands: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int val = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + if (!IsBiomeOcean(val)) + { + a_Values[x + z * a_SizeX] = val; + continue; + } + + // Count the ocean neighbors: + int Above = lowerValues[x + 1 + z * lowerSizeX]; + int Below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int Left = lowerValues[x + (z + 1) * lowerSizeX]; + int Right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + int NumOceanNeighbors = 0; + if (IsBiomeOcean(Above)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Below)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Left)) + { + NumOceanNeighbors += 1; + } + if (IsBiomeOcean(Right)) + { + NumOceanNeighbors += 1; + } + + // If at least 3 ocean neighbors and the chance is right, change: + if ( + (NumOceanNeighbors >= 3) && + ((super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7) % 1000 < m_Chance) + ) + { + a_Values[x + z * a_SizeX] = m_ToValue; + } + else + { + a_Values[x + z * a_SizeX] = val; + } + } // for x + } // for z + } + +protected: + /** Chance, in permille, of changing the biome. */ + int m_Chance; + + /** The value to change the ocean into. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + +/** Changes random pixels of the underlying data to the specified value. */ +class cProtIntGenSetRandomly : + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenSetRandomly(int a_Seed, int a_Chance, int a_ToValue, Underlying a_Underlying) : + super(a_Seed), + m_Chance(a_Chance), + m_ToValue(a_ToValue), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Change random pixels to bgOcean: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + a_Values[x + z * a_SizeX] = m_ToValue; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel. */ + int m_Chance; + + /** The value to which to set the pixel. */ + int m_ToValue; + + Underlying m_Underlying; +}; + + + + + + +/** Adds a "rare" flag to random biome groups, based on the given chance. */ +class cProtIntGenRareBiomeGroups: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenRareBiomeGroups(int a_Seed, int a_Chance, Underlying a_Underlying): + super(a_Seed), + m_Chance(a_Chance), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying data: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + + // Change some of the biome groups into rare biome groups: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int rnd = super::m_Noise.IntNoise2DInt(x + a_MinX, z + a_MinZ) / 7; + if (rnd % 1000 < m_Chance) + { + int idx = x + a_SizeX * z; + a_Values[idx] = a_Values[idx] | bgfRare; + } + } + } + } + +protected: + /** Chance, in permille, of changing each pixel into the rare biome group. */ + int m_Chance; + + /** The underlying generator. */ + Underlying m_Underlying; +}; + + + + + +/** Changes biomes in the parent data into an alternate versions (usually "hill" variants), in such places +that have their alterations set. */ +class cProtIntGenAlternateBiomes: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenAlternateBiomes(int a_Seed, Underlying a_Alterations, Underlying a_BaseBiomes): + super(a_Seed), + m_Alterations(a_Alterations), + m_BaseBiomes(a_BaseBiomes) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the base biomes and the alterations: + m_BaseBiomes->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int alterations[m_BufferSize]; + m_Alterations->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, alterations); + + // Change the biomes into their alternate versions: + int len = a_SizeX * a_SizeZ; + for (int idx = 0; idx < len; ++idx) + { + if (alterations[idx] == 0) + { + // No change + continue; + } + + // Change to alternate biomes: + int val = a_Values[idx]; + switch (val) + { + case biBirchForest: val = biBirchForestHills; break; + case biDesert: val = biDesertHills; break; + case biExtremeHills: val = biExtremeHillsPlus; break; + case biForest: val = biForestHills; break; + case biIcePlains: val = biIceMountains; break; + case biJungle: val = biJungleHills; break; + case biMegaTaiga: val = biMegaTaigaHills; break; + case biMesaPlateau: val = biMesa; break; + case biMesaPlateauF: val = biMesa; break; + case biMesaPlateauM: val = biMesa; break; + case biMesaPlateauFM: val = biMesa; break; + case biPlains: val = biForest; break; + case biRoofedForest: val = biPlains; break; + case biSavanna: val = biSavannaPlateau; break; + case biTaiga: val = biTaigaHills; break; + } + a_Values[idx] = val; + } // for idx - a_Values[] + } + +protected: + Underlying m_Alterations; + Underlying m_BaseBiomes; +}; + + + + + +/** Adds an edge between two specifically incompatible biomes, such as mesa and forest. */ +class cProtIntGenBiomeEdges: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenBiomeEdges(int a_Seed, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying biomes: + int lowerSizeX = a_SizeX + 2; + int lowerSizeZ = a_SizeZ + 2; + ASSERT(lowerSizeX * lowerSizeZ <= m_BufferSize); + int lowerValues[m_BufferSize]; + m_Underlying->GetInts(a_MinX - 1, a_MinZ - 1, lowerSizeX, lowerSizeZ, lowerValues); + + // Convert incompatible edges into neutral biomes: + for (int z = 0; z < a_SizeZ; z++) + { + for (int x = 0; x < a_SizeX; x++) + { + int biome = lowerValues[x + 1 + (z + 1) * lowerSizeX]; + int above = lowerValues[x + 1 + z * lowerSizeX]; + int below = lowerValues[x + 1 + (z + 2) * lowerSizeX]; + int left = lowerValues[x + (z + 1) * lowerSizeX]; + int right = lowerValues[x + 2 + (z + 1) * lowerSizeX]; + + switch (biome) + { + case biDesert: + case biDesertM: + case biDesertHills: + { + if ( + IsBiomeVeryCold(static_cast<EMCSBiome>(above)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(below)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(left)) || + IsBiomeVeryCold(static_cast<EMCSBiome>(right)) + ) + { + biome = biPlains; + } + break; + } // case biDesert + + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + { + if ( + !isMesaCompatible(above) || + !isMesaCompatible(below) || + !isMesaCompatible(left) || + !isMesaCompatible(right) + ) + { + biome = biDesert; + } + break; + } // Mesa biomes + + case biJungle: + case biJungleM: + { + if ( + !isJungleCompatible(above) || + !isJungleCompatible(below) || + !isJungleCompatible(left) || + !isJungleCompatible(right) + ) + { + biome = (biome == biJungle) ? biJungleEdge : biJungleEdgeM; + } + break; + } // Jungle biomes + + case biSwampland: + case biSwamplandM: + { + if ( + IsBiomeNoDownfall(static_cast<EMCSBiome>(above)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(below)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(left)) || + IsBiomeNoDownfall(static_cast<EMCSBiome>(right)) + ) + { + biome = biPlains; + } + break; + } // Swampland biomes + } // switch (biome) + + a_Values[x + z * a_SizeX] = biome; + } // for x + } // for z + } + + +protected: + Underlying m_Underlying; + + + bool isMesaCompatible(int a_Biome) + { + switch (a_Biome) + { + case biDesert: + case biMesa: + case biMesaBryce: + case biMesaPlateau: + case biMesaPlateauF: + case biMesaPlateauFM: + case biMesaPlateauM: + case biOcean: + case biDeepOcean: + { + return true; + } + default: + { + return false; + } + } + } + + + bool isJungleCompatible(int a_Biome) + { + switch (a_Biome) + { + case biJungle: + case biJungleM: + case biJungleEdge: + case biJungleEdgeM: + case biJungleHills: + { + return true; + } + default: + { + return false; + } + } + } +}; + + + + + +/** Changes biomes in the parent data into their alternate versions ("M" variants), in such places that +have their alterations set. */ +class cProtIntGenMBiomes: + public cProtIntGenWithNoise +{ + typedef cProtIntGenWithNoise super; + +public: + cProtIntGenMBiomes(int a_Seed, Underlying a_Alteration, Underlying a_Underlying): + super(a_Seed), + m_Underlying(a_Underlying), + m_Alteration(a_Alteration) + { + } + + + virtual void GetInts(int a_MinX, int a_MinZ, int a_SizeX, int a_SizeZ, int * a_Values) override + { + // Generate the underlying biomes and the alterations: + m_Underlying->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, a_Values); + int alterations[m_BufferSize]; + m_Alteration->GetInts(a_MinX, a_MinZ, a_SizeX, a_SizeZ, alterations); + + // Wherever alterations are nonzero, change into alternate biome, if available: + int len = a_SizeX * a_SizeZ; + for (int idx = 0; idx < len; ++idx) + { + if (alterations[idx] == 0) + { + continue; + } + + // Ice spikes biome was removed from here, because it was generated way too often + switch (a_Values[idx]) + { + case biPlains: a_Values[idx] = biSunflowerPlains; break; + case biDesert: a_Values[idx] = biDesertM; break; + case biExtremeHills: a_Values[idx] = biExtremeHillsM; break; + case biForest: a_Values[idx] = biFlowerForest; break; + case biTaiga: a_Values[idx] = biTaigaM; break; + case biSwampland: a_Values[idx] = biSwamplandM; break; + case biJungle: a_Values[idx] = biJungleM; break; + case biJungleEdge: a_Values[idx] = biJungleEdgeM; break; + case biBirchForest: a_Values[idx] = biBirchForestM; break; + case biBirchForestHills: a_Values[idx] = biBirchForestHillsM; break; + case biRoofedForest: a_Values[idx] = biRoofedForestM; break; + case biColdTaiga: a_Values[idx] = biColdTaigaM; break; + case biMegaSpruceTaiga: a_Values[idx] = biMegaSpruceTaiga; break; + case biMegaSpruceTaigaHills: a_Values[idx] = biMegaSpruceTaigaHills; break; + case biExtremeHillsPlus: a_Values[idx] = biExtremeHillsPlusM; break; + case biSavanna: a_Values[idx] = biSavannaM; break; + case biSavannaPlateau: a_Values[idx] = biSavannaPlateauM; break; + case biMesa: a_Values[idx] = biMesaBryce; break; + case biMesaPlateauF: a_Values[idx] = biMesaPlateauFM; break; + case biMesaPlateau: a_Values[idx] = biMesaBryce; break; + } + } // for idx - a_Values[] / alterations[] + } + +protected: + Underlying m_Underlying; + Underlying m_Alteration; +}; + + + + diff --git a/src/Generating/StructGen.cpp b/src/Generating/StructGen.cpp index c23a72621..bdefcd8c1 100644 --- a/src/Generating/StructGen.cpp +++ b/src/Generating/StructGen.cpp @@ -411,7 +411,7 @@ void cStructGenLakes::CreateLakeImage(int a_ChunkX, int a_ChunkZ, cBlockArea & a // Find the minimum height in this chunk: cChunkDef::HeightMap HeightMap; - m_HeiGen.GenHeightMap(a_ChunkX, a_ChunkZ, HeightMap); + m_HeiGen->GenHeightMap(a_ChunkX, a_ChunkZ, HeightMap); HEIGHTTYPE MinHeight = HeightMap[0]; for (size_t i = 1; i < ARRAYCOUNT(HeightMap); i++) { diff --git a/src/Generating/StructGen.h b/src/Generating/StructGen.h index 96aa3e437..906fdd722 100644 --- a/src/Generating/StructGen.h +++ b/src/Generating/StructGen.h @@ -24,7 +24,7 @@ class cStructGenTrees : public cFinishGen { public: - cStructGenTrees(int a_Seed, cBiomeGen * a_BiomeGen, cTerrainHeightGen * a_HeightGen, cTerrainCompositionGen * a_CompositionGen) : + cStructGenTrees(int a_Seed, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen, cTerrainCompositionGenPtr a_CompositionGen) : m_Seed(a_Seed), m_Noise(a_Seed), m_BiomeGen(a_BiomeGen), @@ -36,9 +36,9 @@ protected: int m_Seed; cNoise m_Noise; - cBiomeGen * m_BiomeGen; - cTerrainHeightGen * m_HeightGen; - cTerrainCompositionGen * m_CompositionGen; + cBiomeGenPtr m_BiomeGen; + cTerrainHeightGenPtr m_HeightGen; + cTerrainCompositionGenPtr m_CompositionGen; /** Generates and applies an image of a single tree. Parts of the tree inside the chunk are applied to a_BlockX. @@ -124,7 +124,7 @@ class cStructGenLakes : public cFinishGen { public: - cStructGenLakes(int a_Seed, BLOCKTYPE a_Fluid, cTerrainHeightGen & a_HeiGen, int a_Probability) : + cStructGenLakes(int a_Seed, BLOCKTYPE a_Fluid, cTerrainHeightGenPtr a_HeiGen, int a_Probability) : m_Noise(a_Seed), m_Seed(a_Seed), m_Fluid(a_Fluid), @@ -134,11 +134,11 @@ public: } protected: - cNoise m_Noise; - int m_Seed; - BLOCKTYPE m_Fluid; - cTerrainHeightGen & m_HeiGen; - int m_Probability; ///< Chance, 0 .. 100, of a chunk having the lake + cNoise m_Noise; + int m_Seed; + BLOCKTYPE m_Fluid; + cTerrainHeightGenPtr m_HeiGen; + int m_Probability; ///< Chance, 0 .. 100, of a chunk having the lake // cFinishGen override: virtual void GenFinish(cChunkDesc & a_ChunkDesc) override; diff --git a/src/Generating/UnderwaterBaseGen.cpp b/src/Generating/UnderwaterBaseGen.cpp index 9278ea546..8916f4b5f 100644 --- a/src/Generating/UnderwaterBaseGen.cpp +++ b/src/Generating/UnderwaterBaseGen.cpp @@ -93,7 +93,7 @@ protected: -cUnderwaterBaseGen::cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGen & a_BiomeGen) : +cUnderwaterBaseGen::cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGenPtr a_BiomeGen) : super(a_Seed, a_GridSize, a_GridSize, a_MaxOffset, a_MaxOffset, a_MaxSize, a_MaxSize, 100), m_Noise(a_Seed + 1000), m_MaxDepth(a_MaxDepth), @@ -112,7 +112,7 @@ cGridStructGen::cStructurePtr cUnderwaterBaseGen::CreateStructure(int a_GridX, i int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_OriginX, a_OriginZ, ChunkX, ChunkZ); cChunkDef::BiomeMap Biomes; - m_BiomeGen.GenBiomes(ChunkX, ChunkZ, Biomes); + m_BiomeGen->GenBiomes(ChunkX, ChunkZ, Biomes); // Check if all the biomes are ocean: // If just one is not, no base is created, because it's likely that an unfriendly biome is too close diff --git a/src/Generating/UnderwaterBaseGen.h b/src/Generating/UnderwaterBaseGen.h index d6267b602..b24eb1075 100644 --- a/src/Generating/UnderwaterBaseGen.h +++ b/src/Generating/UnderwaterBaseGen.h @@ -22,7 +22,7 @@ class cUnderwaterBaseGen : typedef cGridStructGen super; public: - cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGen & a_BiomeGen); + cUnderwaterBaseGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, cBiomeGenPtr a_BiomeGen); protected: class cUnderwaterBase; // fwd: UnderwaterBaseGen.cpp @@ -38,7 +38,7 @@ protected: int m_MaxSize; /** The underlying biome generator that defines whether the base is created or not */ - cBiomeGen & m_BiomeGen; + cBiomeGenPtr m_BiomeGen; // cGridStructGen overrides: diff --git a/src/Generating/VillageGen.cpp b/src/Generating/VillageGen.cpp index a7f66b75e..a9b359b6a 100644 --- a/src/Generating/VillageGen.cpp +++ b/src/Generating/VillageGen.cpp @@ -116,7 +116,7 @@ public: int a_MaxSize, int a_Density, cPiecePool & a_Prefabs, - cTerrainHeightGen & a_HeightGen, + cTerrainHeightGenPtr a_HeightGen, BLOCKTYPE a_RoadBlock, BLOCKTYPE a_WaterRoadBlock ) : @@ -175,7 +175,7 @@ protected: cPiecePool & m_Prefabs; /** The underlying height generator, used for placing the structures on top of the terrain. */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; /** The village pieces, placed by the generator. */ cPlacedPieces m_Pieces; @@ -194,7 +194,7 @@ protected: // Each intersecting prefab is placed on ground, then drawn // Each intersecting road is drawn by replacing top soil blocks with gravel / sandstone blocks cChunkDef::HeightMap HeightMap; // Heightmap for this chunk, used by roads - m_HeightGen.GenHeightMap(a_Chunk.GetChunkX(), a_Chunk.GetChunkZ(), HeightMap); + m_HeightGen->GenHeightMap(a_Chunk.GetChunkX(), a_Chunk.GetChunkZ(), HeightMap); for (cPlacedPieces::iterator itr = m_Pieces.begin(), end = m_Pieces.end(); itr != end; ++itr) { cPrefab & Prefab = (cPrefab &)((*itr)->GetPiece()); @@ -224,7 +224,7 @@ protected: int BlockY; cChunkDef::AbsoluteToRelative(BlockX, BlockY, BlockZ, ChunkX, ChunkZ); cChunkDef::HeightMap HeightMap; - m_HeightGen.GenHeightMap(ChunkX, ChunkZ, HeightMap); + m_HeightGen->GenHeightMap(ChunkX, ChunkZ, HeightMap); int TerrainHeight = cChunkDef::GetHeight(HeightMap, BlockX, BlockZ); a_Piece.MoveToGroundBy(TerrainHeight - FirstConnector.m_Pos.y + 1); } @@ -359,7 +359,7 @@ static cVillagePiecePool * g_PlainsVillagePools[] = -cVillageGen::cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen) : +cVillageGen::cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen) : super(a_Seed, a_GridSize, a_GridSize, a_MaxOffset, a_MaxOffset, a_MaxSize, a_MaxSize, 100), m_Noise(a_Seed + 1000), m_MaxDepth(a_MaxDepth), @@ -381,11 +381,11 @@ cGridStructGen::cStructurePtr cVillageGen::CreateStructure(int a_GridX, int a_Gr int ChunkX, ChunkZ; cChunkDef::BlockToChunk(a_OriginX, a_OriginZ, ChunkX, ChunkZ); cChunkDef::BiomeMap Biomes; - m_BiomeGen.GenBiomes(ChunkX, ChunkZ, Biomes); + m_BiomeGen->GenBiomes(ChunkX, ChunkZ, Biomes); // Check if all the biomes are village-friendly: // If just one is not, no village is created, because it's likely that an unfriendly biome is too close - cVillagePiecePool * VillagePrefabs = NULL; + cVillagePiecePool * VillagePrefabs = nullptr; BLOCKTYPE RoadBlock = E_BLOCK_GRAVEL; BLOCKTYPE WaterRoadBlock = E_BLOCK_PLANKS; int rnd = m_Noise.IntNoise2DInt(a_OriginX, a_OriginZ) / 11; @@ -432,7 +432,7 @@ cGridStructGen::cStructurePtr cVillageGen::CreateStructure(int a_GridX, int a_Gr } // Create a village based on the chosen prefabs: - if (VillagePrefabs == NULL) + if (VillagePrefabs == nullptr) { return cStructurePtr(); } diff --git a/src/Generating/VillageGen.h b/src/Generating/VillageGen.h index 694ea2358..ed8d739df 100644 --- a/src/Generating/VillageGen.h +++ b/src/Generating/VillageGen.h @@ -21,7 +21,7 @@ class cVillageGen : { typedef cGridStructGen super; public: - cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGen & a_BiomeGen, cTerrainHeightGen & a_HeightGen); + cVillageGen(int a_Seed, int a_GridSize, int a_MaxOffset, int a_MaxDepth, int a_MaxSize, int a_MinDensity, int a_MaxDensity, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen); protected: class cVillage; // fwd: VillageGen.cpp @@ -42,10 +42,10 @@ protected: int m_MaxDensity; /** The underlying biome generator that defines whether the village is created or not */ - cBiomeGen & m_BiomeGen; + cBiomeGenPtr m_BiomeGen; /** The underlying height generator, used to position the prefabs crossing chunk borders */ - cTerrainHeightGen & m_HeightGen; + cTerrainHeightGenPtr m_HeightGen; // cGridStructGen overrides: diff --git a/src/Globals.h b/src/Globals.h index 4ee1352eb..582f5fdaa 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -17,7 +17,6 @@ #pragma warning(disable:4100) // Unreferenced formal parameter // Useful warnings from warning level 4: - #pragma warning(3 : 4127) // Conditional expression is constant #pragma warning(3 : 4189) // Local variable is initialized but not referenced #pragma warning(3 : 4245) // Conversion from 'type1' to 'type2', signed/unsigned mismatch #pragma warning(3 : 4310) // Cast truncates constant value @@ -26,7 +25,10 @@ #pragma warning(3 : 4701) // Potentially unitialized local variable used #pragma warning(3 : 4702) // Unreachable code #pragma warning(3 : 4706) // Assignment within conditional expression - + + // 2014-10-23 xoft: Disabled this because the new C++11 headers in MSVC produce tons of these warnings uselessly + // #pragma warning(3 : 4127) // Conditional expression is constant + // Disabling this warning, because we know what we're doing when we're doing this: #pragma warning(disable: 4355) // 'this' used in initializer list @@ -361,19 +363,8 @@ void inline LOGD(const char* a_Format, ...) #define assert_test(x) ( !!(x) || (assert(!#x), exit(1), 0)) #endif -// Allow both Older versions of MSVC and newer versions of everything use a shared_ptr: -// Note that we cannot typedef, because C++ doesn't allow (partial) templates to be typedeffed. -#if (defined(_MSC_VER) && (_MSC_VER < 1600)) - // MSVC before 2010 doesn't have std::shared_ptr, but has std::tr1::shared_ptr, defined in <memory> included earlier - #define SharedPtr std::tr1::shared_ptr -#elif (defined(_MSC_VER) || (__cplusplus >= 201103L)) - // C++11 has std::shared_ptr in <memory>, included earlier - #define SharedPtr std::shared_ptr -#else - // C++03 has std::tr1::shared_ptr in <tr1/memory> - #include <tr1/memory> - #define SharedPtr std::tr1::shared_ptr -#endif +// Unified shared ptr from before C++11. Also no silly undercores. +#define SharedPtr std::shared_ptr @@ -419,6 +410,12 @@ typename std::enable_if<std::is_arithmetic<T>::value, C>::type CeilC(T a_Value) +//temporary replacement for std::make_unique until we get c++14 +template <class T, class... Args> +std::unique_ptr<T> make_unique(Args&&... args) +{ + return std::unique_ptr<T>(new T(args...)); +} #ifndef TOLUA_TEMPLATE_BIND @@ -436,3 +433,4 @@ typename std::enable_if<std::is_arithmetic<T>::value, C>::type CeilC(T a_Value) #include "BlockInfo.h" + diff --git a/src/HTTPServer/HTTPConnection.cpp b/src/HTTPServer/HTTPConnection.cpp index bf46bb241..d5dbf0199 100644 --- a/src/HTTPServer/HTTPConnection.cpp +++ b/src/HTTPServer/HTTPConnection.cpp @@ -15,7 +15,7 @@ cHTTPConnection::cHTTPConnection(cHTTPServer & a_HTTPServer) : m_HTTPServer(a_HTTPServer), m_State(wcsRecvHeaders), - m_CurrentRequest(NULL), + m_CurrentRequest(nullptr), m_CurrentRequestBodyRemaining(0) { // LOGD("HTTP: New connection at %p", this); @@ -29,7 +29,7 @@ cHTTPConnection::~cHTTPConnection() { // LOGD("HTTP: Connection deleting: %p", this); delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; } @@ -136,7 +136,7 @@ void cHTTPConnection::AwaitNextRequest(void) void cHTTPConnection::Terminate(void) { - if (m_CurrentRequest != NULL) + if (m_CurrentRequest != nullptr) { m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); } @@ -153,7 +153,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) { case wcsRecvHeaders: { - if (m_CurrentRequest == NULL) + if (m_CurrentRequest == nullptr) { m_CurrentRequest = new cHTTPRequest; } @@ -162,7 +162,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) if (BytesConsumed == AString::npos) { delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; m_State = wcsInvalid; m_HTTPServer.CloseConnection(*this); return true; @@ -196,7 +196,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) case wcsRecvBody: { - ASSERT(m_CurrentRequest != NULL); + ASSERT(m_CurrentRequest != nullptr); if (m_CurrentRequestBodyRemaining > 0) { size_t BytesToConsume = std::min(m_CurrentRequestBodyRemaining, (size_t)a_Size); @@ -214,7 +214,7 @@ bool cHTTPConnection::DataReceived(const char * a_Data, size_t a_Size) return true; } delete m_CurrentRequest; - m_CurrentRequest = NULL; + m_CurrentRequest = nullptr; } break; } @@ -243,7 +243,7 @@ void cHTTPConnection::GetOutgoingData(AString & a_Data) void cHTTPConnection::SocketClosed(void) { - if (m_CurrentRequest != NULL) + if (m_CurrentRequest != nullptr) { m_HTTPServer.RequestFinished(*this, *m_CurrentRequest); } diff --git a/src/HTTPServer/HTTPConnection.h b/src/HTTPServer/HTTPConnection.h index 6ea8a1ae8..ccbf26466 100644 --- a/src/HTTPServer/HTTPConnection.h +++ b/src/HTTPServer/HTTPConnection.h @@ -31,10 +31,10 @@ public: enum eState { - wcsRecvHeaders, ///< Receiving request headers (m_CurrentRequest is created if NULL) + wcsRecvHeaders, ///< Receiving request headers (m_CurrentRequest is created if nullptr) wcsRecvBody, ///< Receiving request body (m_CurrentRequest is valid) - wcsRecvIdle, ///< Has received the entire body, waiting to send the response (m_CurrentRequest == NULL) - wcsSendingResp, ///< Sending response body (m_CurrentRequest == NULL) + wcsRecvIdle, ///< Has received the entire body, waiting to send the response (m_CurrentRequest == nullptr) + wcsSendingResp, ///< Sending response body (m_CurrentRequest == nullptr) wcsInvalid, ///< The request was malformed, the connection is closing } ; diff --git a/src/HTTPServer/HTTPFormParser.cpp b/src/HTTPServer/HTTPFormParser.cpp index c50c6dcf2..72872078b 100644 --- a/src/HTTPServer/HTTPFormParser.cpp +++ b/src/HTTPServer/HTTPFormParser.cpp @@ -86,7 +86,7 @@ void cHTTPFormParser::Parse(const char * a_Data, size_t a_Size) } case fpkMultipart: { - ASSERT(m_MultipartParser.get() != NULL); + ASSERT(m_MultipartParser.get() != nullptr); m_MultipartParser->Parse(a_Data, a_Size); break; } @@ -145,7 +145,7 @@ bool cHTTPFormParser::HasFormData(const cHTTPRequest & a_Request) void cHTTPFormParser::BeginMultipart(const cHTTPRequest & a_Request) { - ASSERT(m_MultipartParser.get() == NULL); + ASSERT(m_MultipartParser.get() == nullptr); m_MultipartParser.reset(new cMultipartParser(a_Request.GetContentType(), *this)); } diff --git a/src/HTTPServer/HTTPMessage.cpp b/src/HTTPServer/HTTPMessage.cpp index 65d73fd87..f6c0204ae 100644 --- a/src/HTTPServer/HTTPMessage.cpp +++ b/src/HTTPServer/HTTPMessage.cpp @@ -70,7 +70,7 @@ cHTTPRequest::cHTTPRequest(void) : super(mkRequest), m_EnvelopeParser(*this), m_IsValid(true), - m_UserData(NULL), + m_UserData(nullptr), m_HasAuth(false), m_AllowKeepAlive(false) { diff --git a/src/HTTPServer/HTTPServer.cpp b/src/HTTPServer/HTTPServer.cpp index 0c41b54b2..9ab030a1f 100644 --- a/src/HTTPServer/HTTPServer.cpp +++ b/src/HTTPServer/HTTPServer.cpp @@ -44,7 +44,7 @@ class cDebugCallbacks : UNUSED(a_Connection); cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData()); - if (FormParser != NULL) + if (FormParser != nullptr) { FormParser->Parse(a_Data, a_Size); } @@ -54,7 +54,7 @@ class cDebugCallbacks : virtual void OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & a_Request) override { cHTTPFormParser * FormParser = (cHTTPFormParser *)(a_Request.GetUserData()); - if (FormParser != NULL) + if (FormParser != nullptr) { if (FormParser->Finish()) { @@ -124,7 +124,7 @@ class cDebugCallbacks : cHTTPServer::cHTTPServer(void) : m_ListenThreadIPv4(*this, cSocket::IPv4, "WebServer"), m_ListenThreadIPv6(*this, cSocket::IPv6, "WebServer"), - m_Callbacks(NULL) + m_Callbacks(nullptr) { } @@ -168,7 +168,7 @@ bool cHTTPServer::Initialize(const AString & a_PortsIPv4, const AString & a_Port } // Notify the admin about the HTTPS / HTTP status - if (m_Cert.get() == NULL) + if (m_Cert.get() == nullptr) { LOGWARNING("WebServer: The server is running in unsecured HTTP mode."); LOGINFO("Put a valid HTTPS certificate in file 'webadmin/httpscert.crt' and its corresponding private key to 'webadmin/httpskey.pem' (without any password) to enable HTTPS support"); @@ -235,7 +235,7 @@ void cHTTPServer::Stop(void) void cHTTPServer::OnConnectionAccepted(cSocket & a_Socket) { cHTTPConnection * Connection; - if (m_Cert.get() != NULL) + if (m_Cert.get() != nullptr) { Connection = new cSslHTTPConnection(*this, m_Cert, m_CertPrivKey); } diff --git a/src/HTTPServer/HTTPServer.h b/src/HTTPServer/HTTPServer.h index 522b7da62..73d4cbdd0 100644 --- a/src/HTTPServer/HTTPServer.h +++ b/src/HTTPServer/HTTPServer.h @@ -11,7 +11,7 @@ #include "../OSSupport/ListenThread.h" #include "../OSSupport/SocketThreads.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "PolarSSL++/RsaPrivateKey.h" #include "PolarSSL++/CryptoKey.h" #include "PolarSSL++/X509Cert.h" diff --git a/src/IniFile.cpp b/src/IniFile.cpp new file mode 100644 index 000000000..ded7e4199 --- /dev/null +++ b/src/IniFile.cpp @@ -0,0 +1,890 @@ +// IniFile.cpp: Implementation of the CIniFile class. +// Written by: Adam Clauss +// Email: cabadam@houston.rr.com +// You may use this class/code as you wish in your programs. Feel free to distribute it, and +// email suggested changes to me. +// +// Rewritten by: Shane Hill +// Date: 21/08/2001 +// Email: Shane.Hill@dsto.defence.gov.au +// Reason: Remove dependancy on MFC. Code should compile on any +// platform. +//////////////////////////////////////////////////////////////////////////////// + +/* +!! MODIFIED BY FAKETRUTH and xoft !! +*/ + +#include "Globals.h" // NOTE: MSVC stupidness requires this to be the same across all modules + +// C++ Includes +#include <fstream> + +// C Includes +#include <ctype.h> + +// Local Includes +#include "IniFile.h" + +#if defined(WIN32) + #define iniEOL endl +#else + #define iniEOL '\r' << endl +#endif + +using namespace std; + + + + + +cIniFile::cIniFile(void) : + m_IsCaseInsensitive(true) +{ +} + + + + + +bool cIniFile::ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect) +{ + // Normally you would use ifstream, but the SGI CC compiler has + // a few bugs with ifstream. So ... fstream used. + fstream f; + AString line; + AString keyname, valuename, value; + AString::size_type pLeft, pRight; + bool IsFromExampleRedirect = false; + + f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::in); + if (f.fail()) + { + f.clear(); + if (a_AllowExampleRedirect) + { + // Retry with the .example.ini file instead of .ini: + AString ExPath(a_FileName.substr(0, a_FileName.length() - 4)); + ExPath.append(".example.ini"); + f.open((FILE_IO_PREFIX + ExPath).c_str(), ios::in); + if (f.fail()) + { + return false; + } + IsFromExampleRedirect = true; + } + else + { + return false; + } + } + + bool IsFirstLine = true; + + while (getline(f, line)) + { + // To be compatible with Win32, check for existence of '\r'. + // Win32 files have the '\r' and Unix files don't at the end of a line. + // Note that the '\r' will be written to INI files from + // Unix so that the created INI file can be read under Win32 + // without change. + + // Removes UTF-8 Byte Order Markers (BOM) if, present. + if (IsFirstLine) + { + RemoveBom(line); + IsFirstLine = false; + } + + size_t lineLength = line.length(); + if (lineLength == 0) + { + continue; + } + if (line[lineLength - 1] == '\r') + { + line = line.substr(0, lineLength - 1); + } + + if (line.length() == 0) + { + continue; + } + + // Check that the user hasn't opened a binary file by checking the first + // character of each line! + if (!isprint(line[0])) + { + printf("%s: Binary-check failed on char %d\n", __FUNCTION__, line[0]); + f.close(); + return false; + } + if ((pLeft = line.find_first_of(";#[=")) == AString::npos) + { + continue; + } + + switch (line[pLeft]) + { + case '[': + { + if ( + ((pRight = line.find_last_of("]")) != AString::npos) && + (pRight > pLeft) + ) + { + keyname = line.substr(pLeft + 1, pRight - pLeft - 1); + AddKeyName(keyname); + } + break; + } + + case '=': + { + valuename = line.substr(0, pLeft); + value = line.substr(pLeft + 1); + AddValue(keyname, valuename, value); + break; + } + + case ';': + case '#': + { + if (names.empty()) + { + AddHeaderComment(line.substr(pLeft + 1)); + } + else + { + AddKeyComment(keyname, line.substr(pLeft + 1)); + } + break; + } + } // switch (line[pLeft]) + } // while (getline()) + + f.close(); + if (keys.empty() && names.empty() && comments.empty()) + { + // File be empty or unreadable, equivalent to nonexistant + return false; + } + + if (IsFromExampleRedirect) + { + WriteFile(FILE_IO_PREFIX + a_FileName); + } + + return true; +} + + + + + +bool cIniFile::WriteFile(const AString & a_FileName) const +{ + // Normally you would use ofstream, but the SGI CC compiler has + // a few bugs with ofstream. So ... fstream used. + fstream f; + + f.open((FILE_IO_PREFIX + a_FileName).c_str(), ios::out); + if (f.fail()) + { + return false; + } + + // Write header comments. + size_t NumComments = comments.size(); + for (size_t commentID = 0; commentID < NumComments; ++commentID) + { + f << ';' << comments[commentID] << iniEOL; + } + if (NumComments > 0) + { + f << iniEOL; + } + + // Write keys and values. + for (size_t keyID = 0; keyID < keys.size(); ++keyID) + { + f << '[' << names[keyID] << ']' << iniEOL; + + // Comments. + for (size_t commentID = 0; commentID < keys[keyID].comments.size(); ++commentID) + { + f << ';' << keys[keyID].comments[commentID] << iniEOL; + } + + // Values. + for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID) + { + f << keys[keyID].names[valueID] << '=' << keys[keyID].values[valueID] << iniEOL; + } + f << iniEOL; + } + f.close(); + + return true; +} + + + + + +int cIniFile::FindKey(const AString & a_KeyName) const +{ + AString CaseKeyName = CheckCase(a_KeyName); + for (size_t keyID = 0; keyID < names.size(); ++keyID) + { + if (CheckCase(names[keyID]) == CaseKeyName) + { + return (int)keyID; + } + } + return noID; +} + + + + + +int cIniFile::FindValue(const int keyID, const AString & a_ValueName) const +{ + if (!keys.size() || (keyID >= (int)keys.size())) + { + return noID; + } + + AString CaseValueName = CheckCase(a_ValueName); + for (size_t valueID = 0; valueID < keys[keyID].names.size(); ++valueID) + { + if (CheckCase(keys[keyID].names[valueID]) == CaseValueName) + { + return int(valueID); + } + } + return noID; +} + + + + + +int cIniFile::AddKeyName(const AString & keyname) +{ + names.resize(names.size() + 1, keyname); + keys.resize(keys.size() + 1); + return (int)names.size() - 1; +} + + + + + +AString cIniFile::GetKeyName(const int keyID) const +{ + if (keyID < (int)names.size()) + { + return names[keyID]; + } + else + { + return ""; + } +} + + + + + +int cIniFile::GetNumValues(const int keyID) const +{ + if (keyID < (int)keys.size()) + { + return (int)keys[keyID].names.size(); + } + return 0; +} + + + + + +int cIniFile::GetNumValues(const AString & keyname) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return 0; + } + return (int)keys[keyID].names.size(); +} + + + + + +AString cIniFile::GetValueName(const int keyID, const int valueID) const +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + return keys[keyID].names[valueID]; + } + return ""; +} + + + + + +AString cIniFile::GetValueName(const AString & keyname, const int valueID) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return ""; + } + return GetValueName(keyID, valueID); +} + + + + + +void cIniFile::AddValue(const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value) +{ + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + keyID = int(AddKeyName(a_KeyName)); + } + + keys[keyID].names.push_back(a_ValueName); + keys[keyID].values.push_back(a_Value); +} + + + + + +void cIniFile::AddValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value) +{ + AddValue(a_KeyName, a_ValueName, Printf("%d", a_Value)); +} + + + + + +void cIniFile::AddValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value) +{ + AddValue(a_KeyName, a_ValueName, Printf("%f", a_Value)); +} + + + + + +bool cIniFile::SetValue(const int keyID, const int valueID, const AString & value) +{ + if (((size_t)keyID >= keys.size()) || ((size_t)valueID >= keys[keyID].names.size())) + { + return false; + } + keys[keyID].values[valueID] = value; + return true; +} + + + + + +bool cIniFile::SetValue(const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists) +{ + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + if (!a_CreateIfNotExists) + { + return false; + } + keyID = AddKeyName(a_KeyName); + } + + int valueID = FindValue(keyID, a_ValueName); + if (valueID == noID) + { + if (!a_CreateIfNotExists) + { + return false; + } + keys[keyID].names.push_back(a_ValueName); + keys[keyID].values.push_back(a_Value); + } + else + { + keys[keyID].values[valueID] = a_Value; + } + + return true; +} + + + + + +bool cIniFile::SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_KeyName, a_ValueName, Printf("%d", a_Value), a_CreateIfNotExists); +} + + + + + +bool cIniFile::SetValueI(const AString & a_Keyname, const AString & a_ValueName, const Int64 a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_Keyname, a_ValueName, Printf("%lld", a_Value), a_CreateIfNotExists); +} + + + + + +bool cIniFile::SetValueF(const AString & a_KeyName, const AString & a_ValueName, double const a_Value, const bool a_CreateIfNotExists) +{ + return SetValue(a_KeyName, a_ValueName, Printf("%f", a_Value), a_CreateIfNotExists); +} + + + + + +AString cIniFile::GetValue(const int keyID, const int valueID, const AString & defValue) const +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + return keys[keyID].values[valueID]; + } + return defValue; +} + + + + + +AString cIniFile::GetValue(const AString & keyname, const AString & valuename, const AString & defValue) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return defValue; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + return defValue; + } + + return keys[keyID].values[valueID]; +} + + + + + +int cIniFile::GetValueI(const AString & keyname, const AString & valuename, const int defValue) const +{ + AString Data; + Printf(Data, "%d", defValue); + return atoi(GetValue(keyname, valuename, Data).c_str()); +} + + + + + +double cIniFile::GetValueF(const AString & keyname, const AString & valuename, double const defValue) const +{ + AString Data; + Printf(Data, "%f", defValue); + return atof(GetValue(keyname, valuename, Data).c_str()); +} + + + + + +AString cIniFile::GetValueSet(const AString & keyname, const AString & valuename, const AString & defValue) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + SetValue(keyname, valuename, defValue); + return defValue; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + SetValue(keyname, valuename, defValue); + return defValue; + } + + return keys[keyID].values[valueID]; +} + + + + + +double cIniFile::GetValueSetF(const AString & keyname, const AString & valuename, const double defValue) +{ + AString Data; + Printf(Data, "%f", defValue); + return atof(GetValueSet(keyname, valuename, Data).c_str()); +} + + + + + +int cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const int defValue) +{ + AString Data; + Printf(Data, "%d", defValue); + return atoi(GetValueSet(keyname, valuename, Data).c_str()); +} + + + + + +Int64 cIniFile::GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue) +{ + AString Data; + Printf(Data, "%lld", defValue); + AString resultstring = GetValueSet(keyname, valuename, Data); + Int64 result = defValue; +#ifdef _WIN32 + sscanf_s(resultstring.c_str(), "%lld", &result); +#else + sscanf(resultstring.c_str(), "%lld", &result); +#endif + return result; +} + + + + + +bool cIniFile::DeleteValueByID(const int keyID, const int valueID) +{ + if ((keyID < (int)keys.size()) && (valueID < (int)keys[keyID].names.size())) + { + // This looks strange, but is neccessary. + vector<AString>::iterator npos = keys[keyID].names.begin() + valueID; + vector<AString>::iterator vpos = keys[keyID].values.begin() + valueID; + keys[keyID].names.erase(npos, npos + 1); + keys[keyID].values.erase(vpos, vpos + 1); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteValue(const AString & keyname, const AString & valuename) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + + int valueID = FindValue(int(keyID), valuename); + if (valueID == noID) + { + return false; + } + + return DeleteValueByID(keyID, valueID); +} + + + + + +bool cIniFile::DeleteKey(const AString & keyname) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + + vector<AString>::iterator npos = names.begin() + keyID; + vector<key>::iterator kpos = keys.begin() + keyID; + names.erase(npos, npos + 1); + keys.erase(kpos, kpos + 1); + + return true; +} + + + + + +void cIniFile::Clear(void) +{ + names.clear(); + keys.clear(); + comments.clear(); +} + + + + + +bool cIniFile::HasValue(const AString & a_KeyName, const AString & a_ValueName) +{ + // Find the key: + int keyID = FindKey(a_KeyName); + if (keyID == noID) + { + return false; + } + + // Find the value: + int valueID = FindValue(keyID, a_ValueName); + return (valueID != noID); +} + + + + + +void cIniFile::AddHeaderComment(const AString & comment) +{ + comments.push_back(comment); + // comments.resize(comments.size() + 1, comment); +} + + + + + +AString cIniFile::GetHeaderComment(const int commentID) const +{ + if (commentID < (int)comments.size()) + { + return comments[commentID]; + } + return ""; +} + + + + + +bool cIniFile::DeleteHeaderComment(int commentID) +{ + if (commentID < (int)comments.size()) + { + vector<AString>::iterator cpos = comments.begin() + commentID; + comments.erase(cpos, cpos + 1); + return true; + } + return false; +} + + + + + +int cIniFile::GetNumKeyComments(const int keyID) const +{ + if (keyID < (int)keys.size()) + { + return (int)keys[keyID].comments.size(); + } + return 0; +} + + + + + +int cIniFile::GetNumKeyComments(const AString & keyname) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return 0; + } + return (int)keys[keyID].comments.size(); +} + + + + + +bool cIniFile::AddKeyComment(const int keyID, const AString & comment) +{ + if (keyID < (int)keys.size()) + { + keys[keyID].comments.resize(keys[keyID].comments.size() + 1, comment); + return true; + } + return false; +} + + + + + +bool cIniFile::AddKeyComment(const AString & keyname, const AString & comment) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return AddKeyComment(keyID, comment); +} + + + + + +AString cIniFile::GetKeyComment(const int keyID, const int commentID) const +{ + if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size())) + { + return keys[keyID].comments[commentID]; + } + return ""; +} + + + + + +AString cIniFile::GetKeyComment(const AString & keyname, const int commentID) const +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return ""; + } + return GetKeyComment(int(keyID), commentID); +} + + + + + +bool cIniFile::DeleteKeyComment(const int keyID, const int commentID) +{ + if ((keyID < (int)keys.size()) && (commentID < (int)keys[keyID].comments.size())) + { + vector<AString>::iterator cpos = keys[keyID].comments.begin() + commentID; + keys[keyID].comments.erase(cpos, cpos + 1); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteKeyComment(const AString & keyname, const int commentID) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return DeleteKeyComment(int(keyID), commentID); +} + + + + + +bool cIniFile::DeleteKeyComments(const int keyID) +{ + if (keyID < (int)keys.size()) + { + keys[keyID].comments.clear(); + return true; + } + return false; +} + + + + + +bool cIniFile::DeleteKeyComments(const AString & keyname) +{ + int keyID = FindKey(keyname); + if (keyID == noID) + { + return false; + } + return DeleteKeyComments(int(keyID)); +} + + + + + +AString cIniFile::CheckCase(const AString & s) const +{ + if (!m_IsCaseInsensitive) + { + return s; + } + AString res(s); + size_t len = res.length(); + for (size_t i = 0; i < len; i++) + { + res[i] = tolower(res[i]); + } + return res; +} + + + + + +void cIniFile::RemoveBom(AString & a_line) const +{ + // The BOM sequence for UTF-8 is 0xEF, 0xBB, 0xBF + static unsigned const char BOM[] = { 0xEF, 0xBB, 0xBF }; + + // The BOM sequence, if present, is always th e first three characters of the input. + const AString ref = a_line.substr(0, 3); + + // If any of the first three chars do not match, return and do nothing. + for (int i = 0; i < 3; ++i) + { + if (static_cast<unsigned char>(ref[i]) != BOM[i]) + { + return; + } + } + + // First three characters match; erase them. + a_line.erase(0, 3); +} + + + + diff --git a/src/IniFile.h b/src/IniFile.h new file mode 100644 index 000000000..e5879f46c --- /dev/null +++ b/src/IniFile.h @@ -0,0 +1,218 @@ +// IniFile.cpp: Implementation of the CIniFile class. +// Written by: Adam Clauss +// Email: cabadam@tamu.edu +// You may use this class/code as you wish in your programs. Feel free to distribute it, and +// email suggested changes to me. +// +// Rewritten by: Shane Hill +// Date: 21/08/2001 +// Email: Shane.Hill@dsto.defence.gov.au +// Reason: Remove dependancy on MFC. Code should compile on any +// platform. Tested on Windows/Linux/Irix +//////////////////////////////////////////////////////////////////////////////// + +/* +!! MODIFIED BY FAKETRUTH and madmaxoft!! +*/ + +#ifndef CIniFile_H +#define CIniFile_H + + + + + +#define MAX_KEYNAME 128 +#define MAX_VALUENAME 128 +#define MAX_VALUEDATA 2048 + + + + + +// tolua_begin + +class cIniFile +{ +private: + bool m_IsCaseInsensitive; + + struct key + { + std::vector<AString> names; + std::vector<AString> values; + std::vector<AString> comments; + } ; + + std::vector<key> keys; + std::vector<AString> names; + std::vector<AString> comments; + + /// If the object is case-insensitive, returns s as lowercase; otherwise returns s as-is + AString CheckCase(const AString & s) const; + + /// Removes the UTF-8 BOMs (Byte order makers), if present. + void RemoveBom(AString & a_line) const; + +public: + + enum errors + { + noID = -1, + }; + + /// Creates a new instance with no data + cIniFile(void); + + // Sets whether or not keynames and valuenames should be case sensitive. + // The default is case insensitive. + void CaseSensitive (void) { m_IsCaseInsensitive = false; } + void CaseInsensitive(void) { m_IsCaseInsensitive = true; } + + /** Reads the contents of the specified ini file + If the file doesn't exist and a_AllowExampleRedirect is true, tries to read <basename>.example.ini, and + writes its contents as <basename>.ini, if successful. + Returns true if successful, false otherwise. + */ + bool ReadFile(const AString & a_FileName, bool a_AllowExampleRedirect = true); + + /// Writes data stored in class to the specified ini file + bool WriteFile(const AString & a_FileName) const; + + /// Deletes all stored ini data (but doesn't touch the file) + void Clear(void); + + /** Returns true iff the specified value exists. */ + bool HasValue(const AString & a_KeyName, const AString & a_ValueName); + + /// Returns index of specified key, or noID if not found + int FindKey(const AString & keyname) const; + + /// Returns index of specified value, in the specified key, or noID if not found + int FindValue(const int keyID, const AString & valuename) const; + + /// Returns number of keys currently in the ini + int GetNumKeys(void) const { return (int)keys.size(); } + + /// Add a key name + int AddKeyName(const AString & keyname); + + // Returns key names by index. + AString GetKeyName(const int keyID) const; + + // Returns number of values stored for specified key. + int GetNumValues(const AString & keyname) const; + int GetNumValues(const int keyID) const; + + // Returns value name by index for a given keyname or keyID. + AString GetValueName(const AString & keyname, const int valueID) const; + AString GetValueName(const int keyID, const int valueID) const; + + // Gets value of [keyname] valuename =. + // Overloaded to return string, int, and double. + // Returns defValue if key/value not found. + AString GetValue (const AString & keyname, const AString & valuename, const AString & defValue = "") const; + AString GetValue (const int keyID, const int valueID, const AString & defValue = "") const; + double GetValueF(const AString & keyname, const AString & valuename, const double defValue = 0) const; + int GetValueI(const AString & keyname, const AString & valuename, const int defValue = 0) const; + bool GetValueB(const AString & keyname, const AString & valuename, const bool defValue = false) const + { + return (GetValueI(keyname, valuename, defValue ? 1 : 0) != 0); + } + + // Gets the value; if not found, write the default to the INI file + AString GetValueSet (const AString & keyname, const AString & valuename, const AString & defValue = ""); + double GetValueSetF(const AString & keyname, const AString & valuename, const double defValue = 0.0); + int GetValueSetI(const AString & keyname, const AString & valuename, const int defValue = 0); + Int64 GetValueSetI(const AString & keyname, const AString & valuename, const Int64 defValue = 0); + bool GetValueSetB(const AString & keyname, const AString & valuename, const bool defValue = false) + { + return (GetValueSetI(keyname, valuename, defValue ? 1 : 0) != 0); + } + + // Adds a new value to the specified key. + // If a value of the same name already exists, creates another one (non-standard INI file) + void AddValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value); + void AddValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value); + void AddValueB(const AString & a_KeyName, const AString & a_ValueName, const bool a_Value) + { + return AddValueI(a_KeyName, a_ValueName, a_Value ? 1 : 0); + } + void AddValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value); + + // Overwrites the value of [keyname].valuename + // Specify the optional parameter as false (0) if you do not want the value created if it doesn't exist. + // Returns true if value set, false otherwise. + // Overloaded to accept string, int, and double. + bool SetValue (const int keyID, const int valueID, const AString & value); + bool SetValue (const AString & a_KeyName, const AString & a_ValueName, const AString & a_Value, const bool a_CreateIfNotExists = true); + bool SetValueI(const AString & a_KeyName, const AString & a_ValueName, const int a_Value, const bool a_CreateIfNotExists = true); + bool SetValueI(const AString & a_Keyname, const AString & a_ValueName, const Int64 a_Value, const bool a_CreateIfNotExists = true); + bool SetValueB(const AString & a_KeyName, const AString & a_ValueName, const bool a_Value, const bool a_CreateIfNotExists = true) + { + return SetValueI(a_KeyName, a_ValueName, int(a_Value), a_CreateIfNotExists); + } + bool SetValueF(const AString & a_KeyName, const AString & a_ValueName, const double a_Value, const bool a_CreateIfNotExists = true); + + // Deletes specified value. + // Returns true if value existed and deleted, false otherwise. + bool DeleteValueByID(const int keyID, const int valueID); + bool DeleteValue(const AString & keyname, const AString & valuename); + + // Deletes specified key and all values contained within. + // Returns true if key existed and deleted, false otherwise. + bool DeleteKey(const AString & keyname); + + // Header comment functions. + // Header comments are those comments before the first key. + + /// Returns the number of header comments + int GetNumHeaderComments(void) {return (int)comments.size();} + + /// Adds a header comment + void AddHeaderComment(const AString & comment); + + /// Returns a header comment, or empty string if out of range + AString GetHeaderComment(const int commentID) const; + + /// Deletes a header comment. Returns true if successful + bool DeleteHeaderComment(int commentID); + + /// Deletes all header comments + void DeleteHeaderComments(void) {comments.clear();} + + + // Key comment functions. + // Key comments are those comments within a key. Any comments + // defined within value names will be added to this list. Therefore, + // these comments will be moved to the top of the key definition when + // the CIniFile::WriteFile() is called. + + /// Get number of key comments + int GetNumKeyComments(const int keyID) const; + + /// Get number of key comments + int GetNumKeyComments(const AString & keyname) const; + + /// Add a key comment + bool AddKeyComment(const int keyID, const AString & comment); + + /// Add a key comment + bool AddKeyComment(const AString & keyname, const AString & comment); + + /// Return a key comment + AString GetKeyComment(const int keyID, const int commentID) const; + AString GetKeyComment(const AString & keyname, const int commentID) const; + + // Delete a key comment. + bool DeleteKeyComment(const int keyID, const int commentID); + bool DeleteKeyComment(const AString & keyname, const int commentID); + + // Delete all comments for a key. + bool DeleteKeyComments(const int keyID); + bool DeleteKeyComments(const AString & keyname); +}; + +// tolua_end + +#endif diff --git a/src/Inventory.cpp b/src/Inventory.cpp index 832a079bc..51ac32da9 100644 --- a/src/Inventory.cpp +++ b/src/Inventory.cpp @@ -220,7 +220,7 @@ void cInventory::SetSlot(int a_SlotNum, const cItem & a_Item) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s(%d): requesting an invalid itemgrid. Ignoring.", __FUNCTION__, a_SlotNum); return; @@ -278,7 +278,7 @@ const cItem & cInventory::GetSlot(int a_SlotNum) const } int GridSlotNum = 0; const cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { // Something went wrong, but we don't know what. We must return a value, so return the first inventory slot LOGWARNING("%s(%d): requesting an invalid ItemGrid, returning the first inventory slot instead.", __FUNCTION__, a_SlotNum); @@ -372,7 +372,7 @@ int cInventory::ChangeSlotCount(int a_SlotNum, int a_AddToCount) { int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s: invalid slot number, expected 0 .. %d, got %d; ignoring", __FUNCTION__, invNumSlots, a_SlotNum); return -1; @@ -398,7 +398,7 @@ bool cInventory::DamageItem(int a_SlotNum, short a_Amount) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(a_SlotNum, GridSlotNum); - if (Grid == NULL) + if (Grid == nullptr) { LOGWARNING("%s(%d, %d): requesting an invalid grid, ignoring.", __FUNCTION__, a_SlotNum, a_Amount); return false; @@ -640,7 +640,7 @@ bool cInventory::LoadFromJson(Json::Value & a_Value) int GridSlotNum = 0; cItemGrid * Grid = GetGridForSlotNum(SlotIdx - 5, GridSlotNum); - ASSERT(Grid != NULL); + ASSERT(Grid != nullptr); Grid->SetSlot(GridSlotNum, Item); } // for itr - a_Value[] return true; @@ -708,7 +708,7 @@ void cInventory::OnSlotChanged(cItemGrid * a_ItemGrid, int a_SlotNum) // Armor update needs broadcast to other players: cWorld * World = m_Owner.GetWorld(); - if ((a_ItemGrid == &m_ArmorSlots) && (World != NULL)) + if ((a_ItemGrid == &m_ArmorSlots) && (World != nullptr)) { World->BroadcastEntityEquipment( m_Owner, ArmorSlotNumToEntityEquipmentID(a_SlotNum), diff --git a/src/Inventory.h b/src/Inventory.h index 5628fb0da..4e76bc0d3 100644 --- a/src/Inventory.h +++ b/src/Inventory.h @@ -179,10 +179,10 @@ protected: cPlayer & m_Owner; - /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return NULL for invalid SlotNum */ + /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return nullptr for invalid SlotNum */ const cItemGrid * GetGridForSlotNum(int a_SlotNum, int & a_GridSlotNum) const; - /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return NULL for invalid SlotNum */ + /** Returns the ItemGrid and the (grid-local) slot number for a (global) slot number; return nullptr for invalid SlotNum */ cItemGrid * GetGridForSlotNum(int a_SlotNum, int & a_GridSlotNum); // cItemGrid::cListener override: diff --git a/src/Item.cpp b/src/Item.cpp index ebdf99ca5..36c444328 100644 --- a/src/Item.cpp +++ b/src/Item.cpp @@ -391,7 +391,7 @@ cItem * cItems::Get(int a_Idx) if ((a_Idx < 0) || (a_Idx >= (int)size())) { LOGWARNING("cItems: Attempt to get an out-of-bounds item at index %d; there are currently " SIZE_T_FMT " items. Returning a nil.", a_Idx, size()); - return NULL; + return nullptr; } return &at(a_Idx); } diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 2344dc0a5..55fb36a17 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -28,7 +28,7 @@ cItemGrid::cItemGrid(int a_Width, int a_Height) : cItemGrid::~cItemGrid() { delete[] m_Slots; - m_Slots = NULL; + m_Slots = nullptr; } @@ -637,14 +637,35 @@ void cItemGrid::GenerateRandomLootWithBooks(const cLootProbab * a_LootProbabs, s int Rnd = (Noise.IntNoise1DInt(i) / 7); int LootRnd = Rnd % TotalProbab; Rnd >>= 8; - cItem CurrentLoot = cItem(E_ITEM_BOOK, 1, 0); // TODO: enchantment + cItem CurrentLoot = cItem(E_ITEM_ENCHANTED_BOOK, 1, 0); + + // Choose the enchantments + cWeightedEnchantments Enchantments; + cEnchantments::AddItemEnchantmentWeights(Enchantments, E_ITEM_BOOK, 24 + Noise.IntNoise2DInt(a_Seed, TotalProbab) % 7); + int NumEnchantments = Noise.IntNoise3DInt(TotalProbab, Rnd, a_Seed) % 5; // The number of enchantments this book wil get. + + for (int j = 0; j <= NumEnchantments; j++) + { + cEnchantments Enchantment = cEnchantments::GenerateEnchantmentFromVector(Enchantments, Noise.IntNoise2DInt(NumEnchantments, i)); + CurrentLoot.m_Enchantments.Add(Enchantment); + cEnchantments::RemoveEnchantmentWeightFromVector(Enchantments, Enchantment); + cEnchantments::CheckEnchantmentConflictsFromVector(Enchantments, Enchantment); + } + for (size_t j = 0; j < a_CountLootProbabs; j++) { - LootRnd -= a_LootProbabs[i].m_Weight; + LootRnd -= a_LootProbabs[j].m_Weight; if (LootRnd < 0) { - CurrentLoot = a_LootProbabs[i].m_Item; - CurrentLoot.m_ItemCount = a_LootProbabs[i].m_MinAmount + (Rnd % (a_LootProbabs[i].m_MaxAmount - a_LootProbabs[i].m_MinAmount)); + CurrentLoot = a_LootProbabs[j].m_Item; + if ((a_LootProbabs[j].m_MaxAmount - a_LootProbabs[j].m_MinAmount) > 0) + { + CurrentLoot.m_ItemCount = a_LootProbabs[j].m_MinAmount + (Rnd % (a_LootProbabs[j].m_MaxAmount - a_LootProbabs[j].m_MinAmount)); + } + else + { + CurrentLoot.m_ItemCount = a_LootProbabs[j].m_MinAmount; + } Rnd >>= 8; break; } diff --git a/src/Items/ItemBow.h b/src/Items/ItemBow.h index f29cc5d59..cf2fe9ad2 100644 --- a/src/Items/ItemBow.h +++ b/src/Items/ItemBow.h @@ -29,7 +29,7 @@ public: virtual bool OnItemUse(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Dir) override { - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); // Check if the player has an arrow in the inventory, or is in Creative: if (!(a_Player->IsGameModeCreative() || a_Player->GetInventory().HasItems(cItem(E_ITEM_ARROW)))) @@ -45,7 +45,7 @@ public: virtual void OnItemShoot(cPlayer * a_Player, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace) override { // Actual shot - produce the arrow with speed based on the ticks that the bow was charged - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); int BowCharge = a_Player->FinishChargingBow(); double Force = (double)BowCharge / 20.0; @@ -65,14 +65,14 @@ public: // Create the arrow entity: cArrowEntity * Arrow = new cArrowEntity(*a_Player, Force * 2); - if (Arrow == NULL) + if (Arrow == nullptr) { return; } if (!Arrow->Initialize(*a_Player->GetWorld())) { delete Arrow; - Arrow = NULL; + Arrow = nullptr; return; } a_Player->GetWorld()->BroadcastSoundEffect("random.bow", a_Player->GetPosX(), a_Player->GetPosY(), a_Player->GetPosZ(), 0.5, (float)Force); diff --git a/src/Items/ItemEmptyMap.h b/src/Items/ItemEmptyMap.h index 953673382..9238d771b 100644 --- a/src/Items/ItemEmptyMap.h +++ b/src/Items/ItemEmptyMap.h @@ -50,7 +50,7 @@ public: return true; } - if (NewMap == NULL) + if (NewMap == nullptr) { return true; } diff --git a/src/Items/ItemHandler.cpp b/src/Items/ItemHandler.cpp index 912dde022..9272a723d 100644 --- a/src/Items/ItemHandler.cpp +++ b/src/Items/ItemHandler.cpp @@ -83,7 +83,7 @@ cItemHandler * cItemHandler::GetItemHandler(int a_ItemType) memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); m_HandlerInitialized = true; } - if (m_ItemHandler[a_ItemType] == NULL) + if (m_ItemHandler[a_ItemType] == nullptr) { m_ItemHandler[a_ItemType] = CreateItemHandler(a_ItemType); } @@ -278,7 +278,7 @@ void cItemHandler::Deinit() for (int i = 0; i < 2267; i++) { delete m_ItemHandler[i]; - m_ItemHandler[i] = NULL; + m_ItemHandler[i] = nullptr; } memset(m_ItemHandler, 0, sizeof(m_ItemHandler)); // Don't leave any dangling pointers around, just in case m_HandlerInitialized = false; @@ -572,6 +572,8 @@ bool cItemHandler::CanHarvestBlock(BLOCKTYPE a_BlockType) case E_BLOCK_COBBLESTONE: case E_BLOCK_COBBLESTONE_STAIRS: case E_BLOCK_COBBLESTONE_WALL: + case E_BLOCK_COBWEB: + case E_BLOCK_DEAD_BUSH: case E_BLOCK_DIAMOND_BLOCK: case E_BLOCK_DIAMOND_ORE: case E_BLOCK_DOUBLE_NEW_STONE_SLAB: diff --git a/src/Items/ItemItemFrame.h b/src/Items/ItemItemFrame.h index 87e20ecf0..5d22c1cb8 100644 --- a/src/Items/ItemItemFrame.h +++ b/src/Items/ItemItemFrame.h @@ -37,7 +37,7 @@ public: if (!ItemFrame->Initialize(*a_World)) { delete ItemFrame; - ItemFrame = NULL; + ItemFrame = nullptr; return false; } diff --git a/src/Items/ItemMap.h b/src/Items/ItemMap.h index 056fe0fe7..2dbbb3dc0 100644 --- a/src/Items/ItemMap.h +++ b/src/Items/ItemMap.h @@ -31,7 +31,7 @@ public: { cMap * Map = a_World->GetMapManager().GetMapData((unsigned)a_Item.m_ItemDamage); - if (Map == NULL) + if (Map == nullptr) { return; } diff --git a/src/Items/ItemMinecart.h b/src/Items/ItemMinecart.h index 63038de51..ed0a4711c 100644 --- a/src/Items/ItemMinecart.h +++ b/src/Items/ItemMinecart.h @@ -56,7 +56,7 @@ public: double x = (double)a_BlockX + 0.5; double y = (double)a_BlockY + 0.5; double z = (double)a_BlockZ + 0.5; - cMinecart * Minecart = NULL; + cMinecart * Minecart = nullptr; switch (m_ItemType) { case E_ITEM_MINECART: Minecart = new cRideableMinecart (x, y, z, cItem(), 1); break; diff --git a/src/Items/ItemShears.h b/src/Items/ItemShears.h index fa2794df2..73343f629 100644 --- a/src/Items/ItemShears.h +++ b/src/Items/ItemShears.h @@ -28,21 +28,25 @@ public: virtual bool OnDiggingBlock(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_Dir) override { - BLOCKTYPE Block = a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ); + BLOCKTYPE Block; + NIBBLETYPE BlockMeta; + a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); + if ((Block == E_BLOCK_LEAVES) || (Block == E_BLOCK_NEW_LEAVES)) { - NIBBLETYPE Meta = a_World->GetBlockMeta(a_BlockX, a_BlockY, a_BlockZ); + cItems Drops; cBlockHandler * Handler = cBlockInfo::GetHandler(Block); - cItems Drops; - Handler->ConvertToPickups(Drops, Meta); - Drops.push_back(cItem(Block, 1, Meta & 3)); + Handler->ConvertToPickups(Drops, BlockMeta); + Drops.Add(Block, 1, BlockMeta & 3); a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); a_World->SetBlock(a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_AIR, 0); + a_World->SpawnItemPickups(Drops, a_BlockX, a_BlockY, a_BlockZ); a_Player->UseEquippedItem(); return true; } + return false; } @@ -53,12 +57,10 @@ public: { case E_BLOCK_COBWEB: case E_BLOCK_VINES: - case E_BLOCK_LEAVES: - case E_BLOCK_NEW_LEAVES: { return true; } - } // switch (a_BlockType) + } return super::CanHarvestBlock(a_BlockType); } @@ -71,12 +73,21 @@ public: virtual void OnBlockDestroyed(cWorld * a_World, cPlayer * a_Player, const cItem & a_Item, int a_BlockX, int a_BlockY, int a_BlockZ) override { - super::OnBlockDestroyed(a_World, a_Player, a_Item, a_BlockX, a_BlockY, a_BlockZ); + BLOCKTYPE Block; + NIBBLETYPE BlockMeta; + a_World->GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, BlockMeta); - BLOCKTYPE Block = a_World->GetBlock(a_BlockX, a_BlockY, a_BlockZ); - if ((Block == E_BLOCK_TRIPWIRE) || (Block == E_BLOCK_VINES)) + super::OnBlockDestroyed(a_World, a_Player, a_Item, a_BlockX, a_BlockY, a_BlockZ); + switch (Block) { - a_Player->UseEquippedItem(); + case E_BLOCK_COBWEB: + case E_BLOCK_DEAD_BUSH: + case E_BLOCK_TRIPWIRE: + case E_BLOCK_VINES: + case E_BLOCK_WOOL: + { + a_Player->UseEquippedItem(); + } } } } ; diff --git a/src/LeakFinder.h b/src/LeakFinder.h index e63b9ec5d..ceaa53782 100644 --- a/src/LeakFinder.h +++ b/src/LeakFinder.h @@ -68,7 +68,7 @@ public: LeakFinderShowCompleteCallstack = 0x1000 } LeakFinderOptions; - LeakFinderOutput(int options = OptionsAll, LPCSTR szSymPath = NULL); + LeakFinderOutput(int options = OptionsAll, LPCSTR szSymPath = nullptr); virtual void OnLeakSearchStart(LPCSTR sszLeakFinderName); virtual void OnLeakStartEntry(LPCSTR szKeyName, SIZE_T nDataSize); protected: @@ -110,7 +110,7 @@ class ZZZ_LeakFinder public: ZZZ_LeakFinder() { - m_pXml = NULL; + m_pXml = nullptr; #ifdef XML_LEAK_FINDER m_pXml = new LeakFinderXmlOutput(); #endif @@ -119,7 +119,7 @@ public: ~ZZZ_LeakFinder() { DeinitLeakFinder(m_pXml); - if (m_pXml != NULL) delete m_pXml; + if (m_pXml != nullptr) delete m_pXml; } protected: LeakFinderXmlOutput *m_pXml; @@ -148,7 +148,7 @@ ZZZ_LeakFinder zzz_LeakFinder; -extern void DumpUsedMemory(LeakFinderOutput * output = NULL); +extern void DumpUsedMemory(LeakFinderOutput * output = nullptr); diff --git a/src/LightingThread.cpp b/src/LightingThread.cpp index 652b03e46..ae5e746e7 100644 --- a/src/LightingThread.cpp +++ b/src/LightingThread.cpp @@ -91,7 +91,7 @@ public: cLightingThread::cLightingThread(void) : super("cLightingThread"), - m_World(NULL), + m_World(nullptr), m_MaxHeight(0), m_NumSeeds(0) { @@ -112,7 +112,7 @@ cLightingThread::~cLightingThread() bool cLightingThread::Start(cWorld * a_World) { - ASSERT(m_World == NULL); // Not started yet + ASSERT(m_World == nullptr); // Not started yet m_World = a_World; return super::Start(); @@ -151,7 +151,7 @@ void cLightingThread::Stop(void) void cLightingThread::QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter) { - ASSERT(m_World != NULL); // Did you call Start() properly? + ASSERT(m_World != nullptr); // Did you call Start() properly? cChunkStay * ChunkStay = new cLightingChunkStay(*this, a_ChunkX, a_ChunkZ, a_CallbackAfter); { @@ -310,7 +310,7 @@ void cLightingThread::LightChunk(cLightingChunkStay & a_Item) m_World->ChunkLighted(a_Item.m_ChunkX, a_Item.m_ChunkZ, BlockLight, SkyLight); - if (a_Item.m_CallbackAfter != NULL) + if (a_Item.m_CallbackAfter != nullptr) { a_Item.m_CallbackAfter->Call(a_Item.m_ChunkX, a_Item.m_ChunkZ); } diff --git a/src/LightingThread.h b/src/LightingThread.h index f71d2cf1a..87eb9c6d8 100644 --- a/src/LightingThread.h +++ b/src/LightingThread.h @@ -61,7 +61,7 @@ public: void Stop(void); /** Queues the entire chunk for lighting */ - void QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter = NULL); + void QueueChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_CallbackAfter = nullptr); /** Blocks until the queue is empty or the thread is terminated */ void WaitForQueueEmpty(void); diff --git a/src/LineBlockTracer.cpp b/src/LineBlockTracer.cpp index 1b42081c2..90f97cd23 100644 --- a/src/LineBlockTracer.cpp +++ b/src/LineBlockTracer.cpp @@ -198,7 +198,7 @@ bool cLineBlockTracer::Item(cChunk * a_Chunk) for (;;) { // Report the current block through the callbacks: - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { m_Callbacks->OnNoChunk(); return false; @@ -228,7 +228,7 @@ bool cLineBlockTracer::Item(cChunk * a_Chunk) // Update the current chunk a_Chunk = a_Chunk->GetNeighborChunk(m_CurrentX, m_CurrentZ); - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { m_Callbacks->OnNoChunk(); return false; diff --git a/src/LinearUpscale.h b/src/LinearUpscale.h index a49f4bdf9..1b0fbd89a 100644 --- a/src/LinearUpscale.h +++ b/src/LinearUpscale.h @@ -95,8 +95,8 @@ template <typename TYPE> void LinearUpscale2DArray( const int MAX_UPSCALE_X = 128; const int MAX_UPSCALE_Y = 128; - ASSERT(a_Src != NULL); - ASSERT(a_Dst != NULL); + ASSERT(a_Src != nullptr); + ASSERT(a_Dst != nullptr); ASSERT(a_SrcSizeX > 0); ASSERT(a_SrcSizeY > 0); ASSERT(a_UpscaleX > 0); @@ -166,8 +166,8 @@ template <typename TYPE> void LinearUpscale3DArray( const int MAX_UPSCALE_Y = 128; const int MAX_UPSCALE_Z = 128; - ASSERT(a_Src != NULL); - ASSERT(a_Dst != NULL); + ASSERT(a_Src != nullptr); + ASSERT(a_Dst != nullptr); ASSERT(a_SrcSizeX > 0); ASSERT(a_SrcSizeY > 0); ASSERT(a_SrcSizeZ > 0); diff --git a/src/LoggerListeners.cpp b/src/LoggerListeners.cpp index 77e2aaf67..5c7097956 100644 --- a/src/LoggerListeners.cpp +++ b/src/LoggerListeners.cpp @@ -280,7 +280,7 @@ cFileListener::cFileListener(void) { cFile::CreateFolder(FILE_IO_PREFIX + AString("logs")); AString FileName; - FileName = Printf("%s%sLOG_%d.txt", FILE_IO_PREFIX, "logs/", (int)time(NULL)); + FileName = Printf("%s%sLOG_%d.txt", FILE_IO_PREFIX, "logs/", (int)time(nullptr)); m_File.Open(FileName, cFile::fmAppend); } diff --git a/src/Map.cpp b/src/Map.cpp index c106ccd83..fbde00cf7 100644 --- a/src/Map.cpp +++ b/src/Map.cpp @@ -21,7 +21,7 @@ cMapDecorator::cMapDecorator(cMap * a_Map, eType a_Type, int a_X, int a_Z, int a , m_PixelX(a_X) , m_PixelZ(a_Z) , m_Rot(a_Rot) - , m_Player(NULL) + , m_Player(nullptr) { } @@ -43,9 +43,9 @@ cMapDecorator::cMapDecorator(cMap * a_Map, cPlayer * a_Player) void cMapDecorator::Update(void) { - if (m_Player != NULL) + if (m_Player != nullptr) { - ASSERT(m_Map != NULL); + ASSERT(m_Map != nullptr); unsigned int PixelWidth = m_Map->GetPixelWidth(); int InsideWidth = (m_Map->GetWidth() / 2) - 1; @@ -221,7 +221,7 @@ bool cMap::UpdatePixel(unsigned int a_X, unsigned int a_Z) virtual bool Item(cChunk * a_Chunk) override { - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { return false; } @@ -322,7 +322,7 @@ bool cMap::UpdatePixel(unsigned int a_X, unsigned int a_Z) } } CalculatePixelCb(this, RelX, RelZ); - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->DoWithChunk(ChunkX, ChunkZ, CalculatePixelCb); SetPixel(a_X, a_Z, CalculatePixelCb.GetPixelData()); @@ -349,7 +349,7 @@ void cMap::UpdateDecorators(void) void cMap::AddPlayer(cPlayer * a_Player, Int64 a_WorldAge) { cClientHandle * Handle = a_Player->GetClientHandle(); - if (Handle == NULL) + if (Handle == nullptr) { return; } @@ -454,10 +454,10 @@ void cMap::StreamNext(cMapClient & a_Client) void cMap::UpdateClient(cPlayer * a_Player) { - ASSERT(a_Player != NULL); + ASSERT(a_Player != nullptr); cClientHandle * Handle = a_Player->GetClientHandle(); - if (Handle == NULL) + if (Handle == nullptr) { return; } @@ -498,7 +498,7 @@ void cMap::EraseData(void) eDimension cMap::GetDimension(void) const { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); return m_World->GetDimension(); } diff --git a/src/MapManager.cpp b/src/MapManager.cpp index e7df75118..2a3ab192b 100644 --- a/src/MapManager.cpp +++ b/src/MapManager.cpp @@ -15,7 +15,7 @@ cMapManager::cMapManager(cWorld * a_World) : m_World(a_World) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); } @@ -27,7 +27,7 @@ bool cMapManager::DoWithMap(int a_ID, cMapCallback & a_Callback) cCSLock Lock(m_CS); cMap * Map = GetMapData(a_ID); - if (Map == NULL) + if (Map == nullptr) { return false; } @@ -68,7 +68,7 @@ cMap * cMapManager::GetMapData(unsigned int a_ID) } else { - return NULL; + return nullptr; } } @@ -83,7 +83,7 @@ cMap * cMapManager::CreateMap(int a_CenterX, int a_CenterY, int a_Scale) if (m_MapData.size() >= 65536) { LOGWARN("Could not craft map - Too many maps in use"); - return NULL; + return nullptr; } cMap Map((unsigned)m_MapData.size(), a_CenterX, a_CenterY, m_World, a_Scale); diff --git a/src/MapManager.h b/src/MapManager.h index a40ec2630..2cc6a7bce 100644 --- a/src/MapManager.h +++ b/src/MapManager.h @@ -31,12 +31,12 @@ public: cMapManager(cWorld * a_World); - /** Returns the map with the specified ID, NULL if out of range. + /** Returns the map with the specified ID, nullptr if out of range. WARNING: The returned map object is not thread safe. */ cMap * GetMapData(unsigned int a_ID); - /** Creates a new map. Returns NULL on error */ + /** Creates a new map. Returns nullptr on error */ cMap * CreateMap(int a_CenterX, int a_CenterY, int a_Scale = 3); /** Calls the callback for the map with the specified ID. diff --git a/src/MersenneTwister.h b/src/MersenneTwister.h index 759b8a1ae..e83a470e2 100644 --- a/src/MersenneTwister.h +++ b/src/MersenneTwister.h @@ -19,11 +19,11 @@ // Copyright (C) 1997 - 2002, Makoto Matsumoto and Takuji Nishimura, // Copyright (C) 2000 - 2009, Richard J. Wagner // All rights reserved. -// +// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: -// +// // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // @@ -31,10 +31,10 @@ // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // -// 3. The names of its contributors may not be used to endorse or promote -// products derived from this software without specific prior written +// 3. The names of its contributors may not be used to endorse or promote +// products derived from this software without specific prior written // permission. -// +// // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -63,13 +63,13 @@ class MTRand { // Data public: typedef UInt32 uint32; // unsigned integer type, at least 32 bits - + enum { N = 624 }; // length of state vector enum { SAVE = N + 1 }; // length of array for save() protected: enum { M = 397 }; // period parameter - + uint32 state[N]; // internal state uint32 *pNext; // next value to get from state uint32 left; // number of values left before reload needed @@ -80,11 +80,11 @@ public: MTRand( uint32 *const bigSeed, uint32 const seedLength = N ); // or array MTRand(); // auto-initialize with /dev/urandom or time() and clock() MTRand( const MTRand& o ); // copy - + // Do NOT use for CRYPTOGRAPHY without securely hashing several returned // values together, otherwise the generator state can be learned after // reading 624 consecutive values. - + // Access to 32-bit random numbers uint32 randInt(); // integer in [0,2^32-1] uint32 randInt( const uint32 n ); // integer in [0,n] for n < 2^32 @@ -95,18 +95,18 @@ public: double randDblExc(); // real number in (0,1) double randDblExc( const double n ); // real number in (0,n) double operator()(); // same as rand() - + // Access to 53-bit random numbers (capacity of IEEE double precision) double rand53(); // real number in [0,1) - + // Access to nonuniform random number distributions double randNorm( const double mean = 0.0, const double stddev = 1.0 ); - + // Re-seeding functions with same behavior as initializers void seed( const uint32 oneSeed ); void seed( uint32 *const bigSeed, const uint32 seedLength = N ); void seed(); - + // Saving and loading generator state void save( uint32* saveArray ) const; // to array of size SAVE void load( uint32 *const loadArray ); // from such array @@ -136,9 +136,9 @@ inline MTRand::uint32 MTRand::hash( time_t t, clock_t c ) // Get a uint32 from t and c // Better than uint32(x) in case x is floating point in [0,1] // Based on code by Lawrence Kirby (fred@genesis.demon.co.uk) - + static uint32 differ = 0; // guarantee time-based seeds will change - + uint32 h1 = 0; unsigned char *p = (unsigned char *) &t; for( size_t i = 0; i < sizeof(t); ++i ) @@ -185,7 +185,7 @@ inline void MTRand::reload() for( i = M; --i; ++p ) *p = twist( p[MmN], p[0], p[1] ); *p = twist( p[MmN], p[0], state[0] ); - + left = N, pNext = state; } @@ -207,7 +207,7 @@ inline void MTRand::seed( uint32 *const bigSeed, const uint32 seedLength ) initialize(19650218UL); uint32 i = 1; uint32 j = 0; - uint32 k = ( (uint32)N > seedLength ? (uint32)N : seedLength ); + uint32 k = ( static_cast<uint32>(N) > seedLength ? static_cast<uint32>(N) : seedLength ); for( ; k; --k ) { state[i] = @@ -235,7 +235,7 @@ inline void MTRand::seed() { // Seed the generator with an array from /dev/urandom if available // Otherwise use a hash of time() and clock() values - + // First try getting an array from /dev/urandom /* // Commented out by FakeTruth because doing this 200 times a tick is SUUUUPEERRR SLOW!!~~!\D5Ne @@ -252,7 +252,7 @@ inline void MTRand::seed() if( success ) { seed( bigSeed, N ); return; } } */ - + // Was not successful, so use time() and clock() instead seed( hash( time(NULL), clock() ) ); } @@ -280,10 +280,10 @@ inline MTRand::uint32 MTRand::randInt() { // Pull a 32-bit integer from the generator state // Every other access function simply transforms the numbers extracted here - + if( left == 0 ) reload(); --left; - + uint32 s1; s1 = *pNext++; s1 ^= (s1 >> 11); @@ -302,7 +302,7 @@ inline MTRand::uint32 MTRand::randInt( const uint32 n ) used |= used >> 4; used |= used >> 8; used |= used >> 16; - + // Draw numbers until one is found in [0,n] uint32 i; do diff --git a/src/MobSpawner.cpp b/src/MobSpawner.cpp index ea3fe8c72..e461fae4c 100644 --- a/src/MobSpawner.cpp +++ b/src/MobSpawner.cpp @@ -301,7 +301,7 @@ bool cMobSpawner::CanSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_R cMonster* cMobSpawner::TryToSpawnHere(cChunk * a_Chunk, int a_RelX, int a_RelY, int a_RelZ, EMCSBiome a_Biome, int& a_MaxPackSize) { - cMonster* toReturn = NULL; + cMonster* toReturn = nullptr; if (m_NewPack) { m_MobType = ChooseMobType(a_Biome); diff --git a/src/Mobs/AggressiveMonster.cpp b/src/Mobs/AggressiveMonster.cpp index be2f71f7a..41ef26e2a 100644 --- a/src/Mobs/AggressiveMonster.cpp +++ b/src/Mobs/AggressiveMonster.cpp @@ -26,7 +26,7 @@ void cAggressiveMonster::InStateChasing(float a_Dt) { super::InStateChasing(a_Dt); - if (m_Target != NULL) + if (m_Target != nullptr) { if (m_Target->IsPlayer()) { @@ -74,7 +74,7 @@ void cAggressiveMonster::Tick(float a_Dt, cChunk & a_Chunk) CheckEventSeePlayer(); } - if (m_Target == NULL) + if (m_Target == nullptr) return; cTracer LineOfSight(GetWorld()); @@ -95,7 +95,7 @@ void cAggressiveMonster::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if ((m_Target == NULL) || (m_AttackInterval < 3.0)) + if ((m_Target == nullptr) || (m_AttackInterval < 3.0)) { return; } diff --git a/src/Mobs/Blaze.cpp b/src/Mobs/Blaze.cpp index b4104d530..16869c79d 100644 --- a/src/Mobs/Blaze.cpp +++ b/src/Mobs/Blaze.cpp @@ -19,7 +19,7 @@ cBlaze::cBlaze(void) : void cBlaze::GetDrops(cItems & a_Drops, cEntity * a_Killer) { - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { int LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); AddRandomDropItem(a_Drops, 0, 1 + LootingLevel, E_ITEM_BLAZE_ROD); @@ -34,20 +34,20 @@ void cBlaze::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cFireChargeEntity * FireCharge = new cFireChargeEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (FireCharge == NULL) + if (FireCharge == nullptr) { return; } if (!FireCharge->Initialize(*m_World)) { delete FireCharge; - FireCharge = NULL; + FireCharge = nullptr; return; } m_World->BroadcastSpawnEntity(*FireCharge); diff --git a/src/Mobs/Blaze.h b/src/Mobs/Blaze.h index f283b1070..e2a4ad9f1 100644 --- a/src/Mobs/Blaze.h +++ b/src/Mobs/Blaze.h @@ -17,6 +17,6 @@ public: CLASS_PROTODEF(cBlaze) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; } ; diff --git a/src/Mobs/CaveSpider.cpp b/src/Mobs/CaveSpider.cpp index 118a6e93b..045b47e73 100644 --- a/src/Mobs/CaveSpider.cpp +++ b/src/Mobs/CaveSpider.cpp @@ -45,12 +45,12 @@ void cCaveSpider::Attack(float a_Dt) void cCaveSpider::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_STRING); - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { AddRandomUncommonDropItem(a_Drops, 33.0f, E_ITEM_SPIDER_EYE); } diff --git a/src/Mobs/CaveSpider.h b/src/Mobs/CaveSpider.h index f9ed10e1b..494ba1360 100644 --- a/src/Mobs/CaveSpider.h +++ b/src/Mobs/CaveSpider.h @@ -18,7 +18,7 @@ public: virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void Attack(float a_Dt) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Chicken.cpp b/src/Mobs/Chicken.cpp index f7e44238f..634867cfa 100644 --- a/src/Mobs/Chicken.cpp +++ b/src/Mobs/Chicken.cpp @@ -49,7 +49,7 @@ void cChicken::Tick(float a_Dt, cChunk & a_Chunk) void cChicken::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Chicken.h b/src/Mobs/Chicken.h index b1a50b61c..07b921884 100644 --- a/src/Mobs/Chicken.h +++ b/src/Mobs/Chicken.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cChicken) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_SEEDS); } diff --git a/src/Mobs/Cow.cpp b/src/Mobs/Cow.cpp index 9914df6b5..7dc6f3f37 100644 --- a/src/Mobs/Cow.cpp +++ b/src/Mobs/Cow.cpp @@ -22,7 +22,7 @@ cCow::cCow(void) : void cCow::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Cow.h b/src/Mobs/Cow.h index 8814b7e09..ee1a4fafe 100644 --- a/src/Mobs/Cow.h +++ b/src/Mobs/Cow.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cCow) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_WHEAT); } diff --git a/src/Mobs/Creeper.cpp b/src/Mobs/Creeper.cpp index 02718edf8..a073224cf 100644 --- a/src/Mobs/Creeper.cpp +++ b/src/Mobs/Creeper.cpp @@ -61,13 +61,13 @@ void cCreeper::GetDrops(cItems & a_Drops, cEntity * a_Killer) } int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_GUNPOWDER); - if ((a_Killer != NULL) && a_Killer->IsProjectile() && (((cProjectileEntity *)a_Killer)->GetCreatorUniqueID() >= 0)) + if ((a_Killer != nullptr) && a_Killer->IsProjectile() && (((cProjectileEntity *)a_Killer)->GetCreatorUniqueID() >= 0)) { class cProjectileCreatorCallback : public cEntityCallback { diff --git a/src/Mobs/Creeper.h b/src/Mobs/Creeper.h index 747daca09..bf3272e22 100644 --- a/src/Mobs/Creeper.h +++ b/src/Mobs/Creeper.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cCreeper) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override; virtual void Attack(float a_Dt) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Mobs/EnderDragon.h b/src/Mobs/EnderDragon.h index 1d4cd657c..e4ca9dcf9 100644 --- a/src/Mobs/EnderDragon.h +++ b/src/Mobs/EnderDragon.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cEnderDragon) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Enderman.cpp b/src/Mobs/Enderman.cpp index 567714382..56ea10245 100644 --- a/src/Mobs/Enderman.cpp +++ b/src/Mobs/Enderman.cpp @@ -15,7 +15,7 @@ class cPlayerLookCheck : { public: cPlayerLookCheck(Vector3d a_EndermanPos, int a_SightDistance) : - m_Player(NULL), + m_Player(nullptr), m_EndermanPos(a_EndermanPos), m_SightDistance(a_SightDistance) { @@ -92,7 +92,7 @@ cEnderman::cEnderman(void) : void cEnderman::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -104,7 +104,7 @@ void cEnderman::GetDrops(cItems & a_Drops, cEntity * a_Killer) void cEnderman::CheckEventSeePlayer() { - if (m_Target != NULL) + if (m_Target != nullptr) { return; } @@ -115,7 +115,7 @@ void cEnderman::CheckEventSeePlayer() return; } - ASSERT(Callback.GetPlayer() != NULL); + ASSERT(Callback.GetPlayer() != nullptr); if (!CheckLight()) { @@ -196,7 +196,7 @@ void cEnderman::Tick(float a_Dt, cChunk & a_Chunk) if (IsSwimming()) { EventLosePlayer(); - TakeDamage(dtDrowning, NULL, 1, 0); + TakeDamage(dtDrowning, nullptr, 1, 0); // TODO teleport to a safe location } diff --git a/src/Mobs/Enderman.h b/src/Mobs/Enderman.h index 947c32b96..28bbceb84 100644 --- a/src/Mobs/Enderman.h +++ b/src/Mobs/Enderman.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cEnderman) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void CheckEventSeePlayer(void) override; virtual void CheckEventLostPlayer(void) override; virtual void EventLosePlayer(void) override; diff --git a/src/Mobs/Ghast.cpp b/src/Mobs/Ghast.cpp index 6aac14779..c65c0d29a 100644 --- a/src/Mobs/Ghast.cpp +++ b/src/Mobs/Ghast.cpp @@ -20,7 +20,7 @@ cGhast::cGhast(void) : void cGhast::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -36,20 +36,20 @@ void cGhast::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cGhastFireballEntity * GhastBall = new cGhastFireballEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (GhastBall == NULL) + if (GhastBall == nullptr) { return; } if (!GhastBall->Initialize(*m_World)) { delete GhastBall; - GhastBall = NULL; + GhastBall = nullptr; return; } m_World->BroadcastSpawnEntity(*GhastBall); diff --git a/src/Mobs/Ghast.h b/src/Mobs/Ghast.h index 1d4e6b94a..a28940a01 100644 --- a/src/Mobs/Ghast.h +++ b/src/Mobs/Ghast.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cGhast) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; bool IsCharging(void) const {return false; } diff --git a/src/Mobs/Giant.h b/src/Mobs/Giant.h index 7c04c9b4f..8d3060940 100644 --- a/src/Mobs/Giant.h +++ b/src/Mobs/Giant.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cGiant) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Horse.cpp b/src/Mobs/Horse.cpp index 67a09d4ab..d92f0d023 100644 --- a/src/Mobs/Horse.cpp +++ b/src/Mobs/Horse.cpp @@ -49,7 +49,7 @@ void cHorse::Tick(float a_Dt, cChunk & a_Chunk) } } - if ((m_Attachee != NULL) && (!m_bIsTame)) + if ((m_Attachee != nullptr) && (!m_bIsTame)) { if (m_TameAttemptTimes < m_TimesToTame) { @@ -113,7 +113,7 @@ void cHorse::OnRightClicked(cPlayer & a_Player) } else { - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -141,7 +141,7 @@ void cHorse::OnRightClicked(cPlayer & a_Player) void cHorse::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Horse.h b/src/Mobs/Horse.h index 47189b3b0..4c644e512 100644 --- a/src/Mobs/Horse.h +++ b/src/Mobs/Horse.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cHorse) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void OnRightClicked(cPlayer & a_Player) override; diff --git a/src/Mobs/IronGolem.h b/src/Mobs/IronGolem.h index c5341ed76..721ca2701 100644 --- a/src/Mobs/IronGolem.h +++ b/src/Mobs/IronGolem.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cIronGolem) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; // Iron golems do not drown nor float virtual void HandleAir(void) override {} diff --git a/src/Mobs/MagmaCube.h b/src/Mobs/MagmaCube.h index bfe63fa2e..d66ea423a 100644 --- a/src/Mobs/MagmaCube.h +++ b/src/Mobs/MagmaCube.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cMagmaCube) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; int GetSize(void) const { return m_Size; } protected: diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index 73dbcb3c3..23b4d9f45 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -79,7 +79,7 @@ cMonster::cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const A : super(etMonster, a_Width, a_Height) , m_EMState(IDLE) , m_EMPersonality(AGGRESSIVE) - , m_Target(NULL) + , m_Target(nullptr) , m_bMovingToDestination(false) , m_LastGroundHeight(POSY_TOINT) , m_IdleInterval(0) @@ -274,8 +274,8 @@ void cMonster::Tick(float a_Dt, cChunk & a_Chunk) return; } - if ((m_Target != NULL) && m_Target->IsDestroyed()) - m_Target = NULL; + if ((m_Target != nullptr) && m_Target->IsDestroyed()) + m_Target = nullptr; // Burning in daylight HandleDaylightBurning(a_Chunk); @@ -379,7 +379,7 @@ void cMonster::Tick(float a_Dt, cChunk & a_Chunk) void cMonster::SetPitchAndYawFromDestination() { Vector3d FinalDestination = m_FinalDestination; - if (m_Target != NULL) + if (m_Target != nullptr) { if (m_Target->IsPlayer()) { @@ -423,7 +423,7 @@ void cMonster::HandleFalling() if (Damage > 0) { - TakeDamage(dtFalling, NULL, Damage, Damage, 0); + TakeDamage(dtFalling, nullptr, Damage, Damage, 0); // Fall particles GetWorld()->BroadcastSoundParticleEffect(2006, POSX_TOINT, POSY_TOINT - 1, POSZ_TOINT, Damage /* Used as particle effect speed modifier */); @@ -479,7 +479,7 @@ bool cMonster::DoTakeDamage(TakeDamageInfo & a_TDI) m_World->BroadcastSoundEffect(m_SoundHurt, GetPosX(), GetPosY(), GetPosZ(), 1.0f, 0.8f); } - if (a_TDI.Attacker != NULL) + if (a_TDI.Attacker != nullptr) { m_Target = a_TDI.Attacker; } @@ -556,7 +556,7 @@ void cMonster::KilledBy(TakeDamageInfo & a_TDI) break; } } - if ((a_TDI.Attacker != NULL) && (!IsBaby())) + if ((a_TDI.Attacker != nullptr) && (!IsBaby())) { m_World->SpawnExperienceOrb(GetPosX(), GetPosY(), GetPosZ(), Reward); } @@ -593,7 +593,7 @@ void cMonster::CheckEventSeePlayer(void) // TODO: Rewrite this to use cWorld's DoWithPlayers() cPlayer * Closest = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance, false); - if (Closest != NULL) + if (Closest != nullptr) { EventSeePlayer(Closest); } @@ -605,7 +605,7 @@ void cMonster::CheckEventSeePlayer(void) void cMonster::CheckEventLostPlayer(void) { - if (m_Target != NULL) + if (m_Target != nullptr) { if ((m_Target->GetPosition() - GetPosition()).Length() > m_SightDistance) { @@ -635,7 +635,7 @@ void cMonster::EventSeePlayer(cEntity * a_SeenPlayer) void cMonster::EventLosePlayer(void) { - m_Target = NULL; + m_Target = nullptr; m_EMState = IDLE; } @@ -697,7 +697,7 @@ void cMonster::InStateEscaping(float a_Dt) { UNUSED(a_Dt); - if (m_Target != NULL) + if (m_Target != nullptr) { Vector3d newloc = GetPosition(); newloc.x = (m_Target->GetPosition().x < newloc.x)? (newloc.x + m_SightDistance): (newloc.x - m_SightDistance); @@ -724,7 +724,7 @@ void cMonster::SetCustomName(const AString & a_CustomName) m_CustomName = a_CustomName.substr(0, 64); } - if (m_World != NULL) + if (m_World != nullptr) { m_World->BroadcastEntityMetadata(*this); } @@ -737,7 +737,7 @@ void cMonster::SetCustomName(const AString & a_CustomName) void cMonster::SetCustomNameAlwaysVisible(bool a_CustomNameAlwaysVisible) { m_CustomNameAlwaysVisible = a_CustomNameAlwaysVisible; - if (m_World != NULL) + if (m_World != nullptr) { m_World->BroadcastEntityMetadata(*this); } @@ -893,7 +893,7 @@ int cMonster::GetSpawnDelay(cMonster::eFamily a_MobFamily) cMonster * cMonster::NewMonsterFromType(eMonsterType a_MobType) { cFastRandom Random; - cMonster * toReturn = NULL; + cMonster * toReturn = nullptr; // Create the mob entity switch (a_MobType) diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index 9fd67d67c..f5ae2cb4d 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -35,12 +35,12 @@ public: mfNoSpawn, mfUnhandled, // Nothing. Be sure this is the last and the others are in order } ; - + // tolua_end - + enum MState{ATTACKING, IDLE, CHASING, ESCAPING} m_EMState; enum MPersonality{PASSIVE, AGGRESSIVE, COWARDLY} m_EMPersonality; - + /** Creates the mob object. If a_ConfigName is not empty, the configuration is loaded using GetMonsterConfig() a_MobType is the type of the mob (also used in the protocol ( http://wiki.vg/Entities#Mobs 2012_12_22)) @@ -49,47 +49,47 @@ public: cMonster(const AString & a_ConfigName, eMonsterType a_MobType, const AString & a_SoundHurt, const AString & a_SoundDeath, double a_Width, double a_Height); CLASS_PROTODEF(cMonster) - + virtual void SpawnOn(cClientHandle & a_ClientHandle) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override; - + virtual void KilledBy(TakeDamageInfo & a_TDI) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void MoveToPosition(const Vector3d & a_Position); // tolua_export virtual bool ReachedDestination(void); - + // tolua_begin eMonsterType GetMobType(void) const {return m_MobType; } eFamily GetMobFamily(void) const; // tolua_end - + virtual void CheckEventSeePlayer(void); virtual void EventSeePlayer(cEntity * a_Player); - + /// Reads the monster configuration for the specified monster name and assigns it to this object. void GetMonsterConfig(const AString & a_Name); - + /** Returns whether this mob is undead (skeleton, zombie, etc.) */ virtual bool IsUndead(void); - + virtual void EventLosePlayer(void); virtual void CheckEventLostPlayer(void); - + virtual void InStateIdle (float a_Dt); virtual void InStateChasing (float a_Dt); virtual void InStateEscaping(float a_Dt); - - int GetAttackRate() { return (int)m_AttackRate; } + + int GetAttackRate() { return static_cast<int>(m_AttackRate); } void SetAttackRate(float a_AttackRate) { m_AttackRate = a_AttackRate; } void SetAttackRange(int a_AttackRange) { m_AttackRange = a_AttackRange; } void SetAttackDamage(int a_AttackDamage) { m_AttackDamage = a_AttackDamage; } void SetSightDistance(int a_SightDistance) { m_SightDistance = a_SightDistance; } - + float GetDropChanceWeapon() { return m_DropChanceWeapon; } float GetDropChanceHelmet() { return m_DropChanceHelmet; } float GetDropChanceChestplate() { return m_DropChanceChestplate; } @@ -102,7 +102,7 @@ public: void SetDropChanceLeggings(float a_DropChanceLeggings) { m_DropChanceLeggings = a_DropChanceLeggings; } void SetDropChanceBoots(float a_DropChanceBoots) { m_DropChanceBoots = a_DropChanceBoots; } void SetCanPickUpLoot(bool a_CanPickUpLoot) { m_CanPickUpLoot = a_CanPickUpLoot; } - + /// Sets whether the mob burns in daylight. Only evaluated at next burn-decision tick void SetBurnsInDaylight(bool a_BurnsInDaylight) { m_BurnsInDaylight = a_BurnsInDaylight; } @@ -113,7 +113,7 @@ public: virtual bool IsBaby (void) const { return false; } virtual bool IsTame (void) const { return false; } virtual bool IsSitting (void) const { return false; } - + // tolua_begin /** Returns true if the monster has a custom name. */ @@ -135,10 +135,10 @@ public: /// Translates MobType enum to a string, empty string if unknown static AString MobTypeToString(eMonsterType a_MobType); - + /// Translates MobType string to the enum, mtInvalidType if not recognized static eMonsterType StringToMobType(const AString & a_MobTypeName); - + /// Returns the mob family based on the type static eFamily FamilyFromType(eMonsterType a_MobType); @@ -146,7 +146,7 @@ public: static int GetSpawnDelay(cMonster::eFamily a_MobFamily); // tolua_end - + /** Creates a new object of the specified mob. a_MobType is the type of the mob to be created Asserts and returns null if mob type is not specified @@ -154,7 +154,7 @@ public: static cMonster * NewMonsterFromType(eMonsterType a_MobType); protected: - + /* ======= PATHFINDING ======= */ /** A pointer to the entity this mobile is aiming to reach */ @@ -168,7 +168,7 @@ protected: /** Stores if mobile is currently moving towards the ultimate, final destination */ bool m_bMovingToDestination; - + /** Finds the first non-air block position (not the highest, as cWorld::GetHeight does) If current Y is nonsolid, goes down to try to find a solid block, then returns that + 1 If current Y is solid, goes up to find first nonsolid block, and returns that */ @@ -227,14 +227,14 @@ protected: int m_AttackRange; float m_AttackInterval; int m_SightDistance; - + float m_DropChanceWeapon; float m_DropChanceHelmet; float m_DropChanceChestplate; float m_DropChanceLeggings; float m_DropChanceBoots; bool m_CanPickUpLoot; - + void HandleDaylightBurning(cChunk & a_Chunk); bool m_BurnsInDaylight; @@ -242,22 +242,18 @@ protected: /** Adds a random number of a_Item between a_Min and a_Max to itemdrops a_Drops*/ void AddRandomDropItem(cItems & a_Drops, unsigned int a_Min, unsigned int a_Max, short a_Item, short a_ItemHealth = 0); - + /** Adds a item a_Item with the chance of a_Chance (in percent) to itemdrops a_Drops*/ void AddRandomUncommonDropItem(cItems & a_Drops, float a_Chance, short a_Item, short a_ItemHealth = 0); - + /** Adds one rare item out of the list of rare items a_Items modified by the looting level a_LootingLevel(I-III or custom) to the itemdrop a_Drops*/ void AddRandomRareDropItem(cItems & a_Drops, cItems & a_Items, short a_LootingLevel); - + /** Adds armor that is equipped with the chance saved in m_DropChance[...] (this will be greter than 1 if piccked up or 0.085 + (0.01 per LootingLevel) if born with) to the drop*/ void AddRandomArmorDropItem(cItems & a_Drops, short a_LootingLevel); - + /** Adds weapon that is equipped with the chance saved in m_DropChance[...] (this will be greter than 1 if piccked up or 0.085 + (0.01 per LootingLevel) if born with) to the drop*/ void AddRandomWeaponDropItem(cItems & a_Drops, short a_LootingLevel); - - -} ; // tolua_export - - +} ; // tolua_export diff --git a/src/Mobs/Mooshroom.cpp b/src/Mobs/Mooshroom.cpp index 99958720f..ec533cfca 100644 --- a/src/Mobs/Mooshroom.cpp +++ b/src/Mobs/Mooshroom.cpp @@ -25,7 +25,7 @@ cMooshroom::cMooshroom(void) : void cMooshroom::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Mooshroom.h b/src/Mobs/Mooshroom.h index fb002c2bf..754725c92 100644 --- a/src/Mobs/Mooshroom.h +++ b/src/Mobs/Mooshroom.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cMooshroom) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_WHEAT); } diff --git a/src/Mobs/PassiveAggressiveMonster.cpp b/src/Mobs/PassiveAggressiveMonster.cpp index e0cc2fd21..cb8650cb9 100644 --- a/src/Mobs/PassiveAggressiveMonster.cpp +++ b/src/Mobs/PassiveAggressiveMonster.cpp @@ -26,7 +26,7 @@ bool cPassiveAggressiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((m_Target != NULL) && (m_Target->IsPlayer())) + if ((m_Target != nullptr) && (m_Target->IsPlayer())) { if (!((cPlayer *)m_Target)->IsGameModeCreative()) { diff --git a/src/Mobs/PassiveMonster.cpp b/src/Mobs/PassiveMonster.cpp index be3043e3d..1048616d0 100644 --- a/src/Mobs/PassiveMonster.cpp +++ b/src/Mobs/PassiveMonster.cpp @@ -24,7 +24,7 @@ bool cPassiveMonster::DoTakeDamage(TakeDamageInfo & a_TDI) { return false; } - if ((a_TDI.Attacker != this) && (a_TDI.Attacker != NULL)) + if ((a_TDI.Attacker != this) && (a_TDI.Attacker != nullptr)) { m_EMState = ESCAPING; } @@ -49,7 +49,7 @@ void cPassiveMonster::Tick(float a_Dt, cChunk & a_Chunk) return; } cPlayer * a_Closest_Player = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance); - if (a_Closest_Player != NULL) + if (a_Closest_Player != nullptr) { if (a_Closest_Player->GetEquippedItem().IsEqual(FollowedItem)) { diff --git a/src/Mobs/Pig.cpp b/src/Mobs/Pig.cpp index 1f77cf613..55a4412ca 100644 --- a/src/Mobs/Pig.cpp +++ b/src/Mobs/Pig.cpp @@ -22,7 +22,7 @@ cPig::cPig(void) : void cPig::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -41,7 +41,7 @@ void cPig::OnRightClicked(cPlayer & a_Player) { if (m_bIsSaddled) { - if (m_Attachee != NULL) + if (m_Attachee != nullptr) { if (m_Attachee->GetUniqueID() == a_Player.GetUniqueID()) { @@ -85,7 +85,7 @@ void cPig::Tick(float a_Dt, cChunk & a_Chunk) super::Tick(a_Dt, a_Chunk); // If the attachee player is holding a carrot-on-stick, let them drive this pig: - if (m_bIsSaddled && (m_Attachee != NULL)) + if (m_bIsSaddled && (m_Attachee != nullptr)) { if (m_Attachee->IsPlayer() && (m_Attachee->GetEquippedWeapon().m_ItemType == E_ITEM_CARROT_ON_STICK)) { diff --git a/src/Mobs/Pig.h b/src/Mobs/Pig.h index 534a0ca6f..953850b3a 100644 --- a/src/Mobs/Pig.h +++ b/src/Mobs/Pig.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cPig) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Mobs/Sheep.cpp b/src/Mobs/Sheep.cpp index cbb33cb90..c46404391 100644 --- a/src/Mobs/Sheep.cpp +++ b/src/Mobs/Sheep.cpp @@ -41,7 +41,7 @@ void cSheep::GetDrops(cItems & a_Drops, cEntity * a_Killer) } int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Sheep.h b/src/Mobs/Sheep.h index 28e1c7254..16d5fddd3 100644 --- a/src/Mobs/Sheep.h +++ b/src/Mobs/Sheep.h @@ -22,7 +22,7 @@ public: CLASS_PROTODEF(cSheep) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void OnRightClicked(cPlayer & a_Player) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; diff --git a/src/Mobs/Skeleton.cpp b/src/Mobs/Skeleton.cpp index cd707f4bb..f17bc307c 100644 --- a/src/Mobs/Skeleton.cpp +++ b/src/Mobs/Skeleton.cpp @@ -23,7 +23,7 @@ cSkeleton::cSkeleton(bool IsWither) : void cSkeleton::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -71,20 +71,20 @@ void cSkeleton::Attack(float a_Dt) { m_AttackInterval += a_Dt * m_AttackRate; - if (m_Target != NULL && m_AttackInterval > 3.0) + if (m_Target != nullptr && m_AttackInterval > 3.0) { // Setting this higher gives us more wiggle room for attackrate Vector3d Speed = GetLookVector() * 20; Speed.y = Speed.y + 1; cArrowEntity * Arrow = new cArrowEntity(this, GetPosX(), GetPosY() + 1, GetPosZ(), Speed); - if (Arrow == NULL) + if (Arrow == nullptr) { return; } if (!Arrow->Initialize(*m_World)) { delete Arrow; - Arrow = NULL; + Arrow = nullptr; return; } m_World->BroadcastSpawnEntity(*Arrow); diff --git a/src/Mobs/Skeleton.h b/src/Mobs/Skeleton.h index 577588b32..cd1c6c3f0 100644 --- a/src/Mobs/Skeleton.h +++ b/src/Mobs/Skeleton.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cSkeleton) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void MoveToPosition(const Vector3d & a_Position) override; virtual void Attack(float a_Dt) override; virtual void SpawnOn(cClientHandle & a_ClientHandle) override; diff --git a/src/Mobs/Slime.cpp b/src/Mobs/Slime.cpp index b709ec664..1c68c5189 100644 --- a/src/Mobs/Slime.cpp +++ b/src/Mobs/Slime.cpp @@ -30,7 +30,7 @@ cSlime::cSlime(int a_Size) : void cSlime::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Slime.h b/src/Mobs/Slime.h index f0b800f94..a177a279c 100644 --- a/src/Mobs/Slime.h +++ b/src/Mobs/Slime.h @@ -19,7 +19,7 @@ public: CLASS_PROTODEF(cSlime) // cAggressiveMonster overrides: - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void Attack(float a_Dt) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; diff --git a/src/Mobs/SnowGolem.h b/src/Mobs/SnowGolem.h index aba89e52d..f036b1867 100644 --- a/src/Mobs/SnowGolem.h +++ b/src/Mobs/SnowGolem.h @@ -18,7 +18,7 @@ public: CLASS_PROTODEF(cSnowGolem) virtual void Tick(float a_Dt, cChunk & a_Chunk) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Spider.cpp b/src/Mobs/Spider.cpp index 8b978ff6b..deb263c41 100644 --- a/src/Mobs/Spider.cpp +++ b/src/Mobs/Spider.cpp @@ -19,12 +19,12 @@ cSpider::cSpider(void) : void cSpider::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } AddRandomDropItem(a_Drops, 0, 2 + LootingLevel, E_ITEM_STRING); - if ((a_Killer != NULL) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) + if ((a_Killer != nullptr) && (a_Killer->IsPlayer() || a_Killer->IsA("cWolf"))) { AddRandomUncommonDropItem(a_Drops, 33.0f, E_ITEM_SPIDER_EYE); } diff --git a/src/Mobs/Spider.h b/src/Mobs/Spider.h index 813d2e266..24134c00f 100644 --- a/src/Mobs/Spider.h +++ b/src/Mobs/Spider.h @@ -17,7 +17,7 @@ public: CLASS_PROTODEF(cSpider) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; } ; diff --git a/src/Mobs/Squid.cpp b/src/Mobs/Squid.cpp index bd0e141a0..59ee963ae 100644 --- a/src/Mobs/Squid.cpp +++ b/src/Mobs/Squid.cpp @@ -22,7 +22,7 @@ void cSquid::GetDrops(cItems & a_Drops, cEntity * a_Killer) { // Drops 0-3 Ink Sacs int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Squid.h b/src/Mobs/Squid.h index b57340427..a46d738c6 100644 --- a/src/Mobs/Squid.h +++ b/src/Mobs/Squid.h @@ -19,7 +19,7 @@ public: CLASS_PROTODEF(cSquid) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; // Squids do not drown (or float) virtual void HandleAir(void) override {} diff --git a/src/Mobs/Villager.cpp b/src/Mobs/Villager.cpp index 0efd5501e..5c9999a59 100644 --- a/src/Mobs/Villager.cpp +++ b/src/Mobs/Villager.cpp @@ -30,7 +30,7 @@ bool cVillager::DoTakeDamage(TakeDamageInfo & a_TDI) return false; } - if ((a_TDI.Attacker != NULL) && a_TDI.Attacker->IsPlayer()) + if ((a_TDI.Attacker != nullptr) && a_TDI.Attacker->IsPlayer()) { if (m_World->GetTickRandomNumber(5) == 3) { diff --git a/src/Mobs/Witch.cpp b/src/Mobs/Witch.cpp index 6956f7b7a..747a11f97 100644 --- a/src/Mobs/Witch.cpp +++ b/src/Mobs/Witch.cpp @@ -19,7 +19,7 @@ cWitch::cWitch(void) : void cWitch::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Witch.h b/src/Mobs/Witch.h index bd059f61d..03691fef1 100644 --- a/src/Mobs/Witch.h +++ b/src/Mobs/Witch.h @@ -18,7 +18,7 @@ public: CLASS_PROTODEF(cWitch) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; bool IsAngry(void) const {return ((m_EMState == ATTACKING) || (m_EMState == CHASING)); } } ; diff --git a/src/Mobs/Wither.h b/src/Mobs/Wither.h index 2403823ed..a20fed3d3 100644 --- a/src/Mobs/Wither.h +++ b/src/Mobs/Wither.h @@ -26,7 +26,7 @@ public: // cEntity overrides virtual bool Initialize(cWorld & a_World) override; - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual bool DoTakeDamage(TakeDamageInfo & a_TDI) override; virtual void Tick(float a_Dt, cChunk & a_Chunk) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; diff --git a/src/Mobs/Wolf.cpp b/src/Mobs/Wolf.cpp index 4fe1ff1d6..4711d5a7a 100644 --- a/src/Mobs/Wolf.cpp +++ b/src/Mobs/Wolf.cpp @@ -47,7 +47,7 @@ void cWolf::Attack(float a_Dt) { UNUSED(a_Dt); - if ((m_Target != NULL) && (m_Target->IsPlayer())) + if ((m_Target != nullptr) && (m_Target->IsPlayer())) { if (((cPlayer *)m_Target)->GetName() != m_OwnerName) { @@ -157,7 +157,7 @@ void cWolf::Tick(float a_Dt, cChunk & a_Chunk) } cPlayer * a_Closest_Player = m_World->FindClosestPlayer(GetPosition(), (float)m_SightDistance); - if (a_Closest_Player != NULL) + if (a_Closest_Player != nullptr) { switch (a_Closest_Player->GetEquippedItem().m_ItemType) { diff --git a/src/Mobs/Zombie.cpp b/src/Mobs/Zombie.cpp index 30225c32d..63042e252 100644 --- a/src/Mobs/Zombie.cpp +++ b/src/Mobs/Zombie.cpp @@ -24,7 +24,7 @@ cZombie::cZombie(bool a_IsVillagerZombie) : void cZombie::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } diff --git a/src/Mobs/Zombie.h b/src/Mobs/Zombie.h index 118b6e6e7..809c2a6fe 100644 --- a/src/Mobs/Zombie.h +++ b/src/Mobs/Zombie.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cZombie) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void MoveToPosition(const Vector3d & a_Position) override; virtual bool IsUndead(void) override { return true; } diff --git a/src/Mobs/ZombiePigman.cpp b/src/Mobs/ZombiePigman.cpp index 05350f877..8b415b0af 100644 --- a/src/Mobs/ZombiePigman.cpp +++ b/src/Mobs/ZombiePigman.cpp @@ -19,7 +19,7 @@ cZombiePigman::cZombiePigman(void) : void cZombiePigman::GetDrops(cItems & a_Drops, cEntity * a_Killer) { int LootingLevel = 0; - if (a_Killer != NULL) + if (a_Killer != nullptr) { LootingLevel = a_Killer->GetEquippedWeapon().m_Enchantments.GetLevel(cEnchantments::enchLooting); } @@ -41,7 +41,7 @@ void cZombiePigman::KilledBy(TakeDamageInfo & a_TDI) { super::KilledBy(a_TDI); - if ((a_TDI.Attacker != NULL) && (a_TDI.Attacker->IsPlayer())) + if ((a_TDI.Attacker != nullptr) && (a_TDI.Attacker->IsPlayer())) { // TODO: Anger all nearby zombie pigmen // TODO: In vanilla, if one player angers ZPs, do they attack any nearby player, or only that one attacker? diff --git a/src/Mobs/ZombiePigman.h b/src/Mobs/ZombiePigman.h index bae0115eb..d8b886ca4 100644 --- a/src/Mobs/ZombiePigman.h +++ b/src/Mobs/ZombiePigman.h @@ -16,7 +16,7 @@ public: CLASS_PROTODEF(cZombiePigman) - virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override; + virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override; virtual void KilledBy(TakeDamageInfo & a_TDI) override; virtual bool IsUndead(void) override { return true; } diff --git a/src/MonsterConfig.cpp b/src/MonsterConfig.cpp index f5e078213..ae2cbbc6b 100644 --- a/src/MonsterConfig.cpp +++ b/src/MonsterConfig.cpp @@ -3,7 +3,7 @@ #include "MonsterConfig.h" #include "Mobs/Monster.h" -#include "inifile/iniFile.h" +#include "IniFile.h" @@ -47,7 +47,7 @@ cMonsterConfig::cMonsterConfig(void) cMonsterConfig::~cMonsterConfig() { delete m_pState; - m_pState = NULL; + m_pState = nullptr; } diff --git a/src/Noise.cpp b/src/Noise.cpp index 71e801f30..8fcfe2920 100644 --- a/src/Noise.cpp +++ b/src/Noise.cpp @@ -845,7 +845,7 @@ void cPerlinNoise::Generate2D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY; if (ShouldFreeWorkspace) { @@ -886,7 +886,7 @@ void cPerlinNoise::Generate2D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -910,7 +910,7 @@ void cPerlinNoise::Generate3D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY * a_SizeZ; if (ShouldFreeWorkspace) { @@ -953,7 +953,7 @@ void cPerlinNoise::Generate3D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -1015,7 +1015,7 @@ void cRidgedMultiNoise::Generate2D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY; if (ShouldFreeWorkspace) { @@ -1056,7 +1056,7 @@ void cRidgedMultiNoise::Generate2D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } @@ -1080,7 +1080,7 @@ void cRidgedMultiNoise::Generate3D( return; } - bool ShouldFreeWorkspace = (a_Workspace == NULL); + bool ShouldFreeWorkspace = (a_Workspace == nullptr); int ArrayCount = a_SizeX * a_SizeY * a_SizeZ; if (ShouldFreeWorkspace) { @@ -1123,7 +1123,7 @@ void cRidgedMultiNoise::Generate3D( if (ShouldFreeWorkspace) { delete[] a_Workspace; - a_Workspace = NULL; + a_Workspace = nullptr; } } diff --git a/src/Noise.h b/src/Noise.h index 4cf8d4ad8..b7a90d5b7 100644 --- a/src/Noise.h +++ b/src/Noise.h @@ -155,7 +155,7 @@ public: NOISE_DATATYPE * a_Array, ///< Array to generate into int a_SizeX, ///< Count of the array NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -164,7 +164,7 @@ public: int a_SizeX, int a_SizeY, ///< Count of the array, in each direction NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -174,7 +174,7 @@ public: NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction NOISE_DATATYPE a_StartZ, NOISE_DATATYPE a_EndZ, ///< Noise-space coords of the array in the Z direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; protected: @@ -219,7 +219,7 @@ public: NOISE_DATATYPE * a_Array, ///< Array to generate into int a_SizeX, ///< Count of the array NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -228,7 +228,7 @@ public: int a_SizeX, int a_SizeY, ///< Count of the array, in each direction NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; @@ -238,7 +238,7 @@ public: NOISE_DATATYPE a_StartX, NOISE_DATATYPE a_EndX, ///< Noise-space coords of the array in the X direction NOISE_DATATYPE a_StartY, NOISE_DATATYPE a_EndY, ///< Noise-space coords of the array in the Y direction NOISE_DATATYPE a_StartZ, NOISE_DATATYPE a_EndZ, ///< Noise-space coords of the array in the Z direction - NOISE_DATATYPE * a_Workspace = NULL ///< Workspace that this function can use and trash + NOISE_DATATYPE * a_Workspace = nullptr ///< Workspace that this function can use and trash ) const; protected: diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index 429949c59..c3eabeef6 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -39,6 +39,10 @@ if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) if(UNIX) - target_link_libraries(OSSupport pthread rt) + if(NOT APPLE) + target_link_libraries(OSSupport rt) + endif() + + target_link_libraries(OSSupport pthread) endif() endif() diff --git a/src/OSSupport/Errors.cpp b/src/OSSupport/Errors.cpp index 9401ec257..a5361e1a6 100644 --- a/src/OSSupport/Errors.cpp +++ b/src/OSSupport/Errors.cpp @@ -10,7 +10,7 @@ AString GetOSErrorString( int a_ErrNo) #ifdef _WIN32 - FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, a_ErrNo, 0, buffer, ARRAYCOUNT(buffer), NULL); + FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, nullptr, a_ErrNo, 0, buffer, ARRAYCOUNT(buffer), nullptr); Printf(Out, "%d: %s", a_ErrNo, buffer); if (!Out.empty() && (Out[Out.length() - 1] == '\n')) { @@ -25,7 +25,7 @@ AString GetOSErrorString( int a_ErrNo) #if !defined(__APPLE__) && ( _GNU_SOURCE) && !defined(ANDROID_NDK) // GNU version of strerror_r() char * res = strerror_r( errno, buffer, ARRAYCOUNT(buffer)); - if (res != NULL) + if (res != nullptr) { Printf(Out, "%d: %s", a_ErrNo, res); return Out; diff --git a/src/OSSupport/Event.cpp b/src/OSSupport/Event.cpp index 7cf8a826c..87bc110ce 100644 --- a/src/OSSupport/Event.cpp +++ b/src/OSSupport/Event.cpp @@ -15,8 +15,8 @@ cEvent::cEvent(void) { #ifdef _WIN32 - m_Event = CreateEvent(NULL, FALSE, FALSE, NULL); - if (m_Event == NULL) + m_Event = CreateEvent(nullptr, FALSE, FALSE, nullptr); + if (m_Event == nullptr) { LOGERROR("cEvent: cannot create event, GLE = %u. Aborting server.", (unsigned)GetLastError()); abort(); @@ -71,7 +71,7 @@ cEvent::~cEvent() { sem_destroy(m_Event); delete m_Event; - m_Event = NULL; + m_Event = nullptr; } #endif } diff --git a/src/OSSupport/File.cpp b/src/OSSupport/File.cpp index cb6031da6..8957dfaef 100644 --- a/src/OSSupport/File.cpp +++ b/src/OSSupport/File.cpp @@ -17,7 +17,7 @@ cFile::cFile(void) : #ifdef USE_STDIO_FILE - m_File(NULL) + m_File(nullptr) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE @@ -31,7 +31,7 @@ cFile::cFile(void) : cFile::cFile(const AString & iFileName, eMode iMode) : #ifdef USE_STDIO_FILE - m_File(NULL) + m_File(nullptr) #else m_File(INVALID_HANDLE_VALUE) #endif // USE_STDIO_FILE @@ -64,7 +64,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) Close(); } - const char * Mode = NULL; + const char * Mode = nullptr; switch (iMode) { case fmRead: Mode = "rb"; break; @@ -72,7 +72,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) case fmReadWrite: Mode = "rb+"; break; case fmAppend: Mode = "a+"; break; } - if (Mode == NULL) + if (Mode == nullptr) { ASSERT(!"Unhandled file mode"); return false; @@ -84,7 +84,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) m_File = fopen((FILE_IO_PREFIX + iFileName).c_str(), Mode); #endif // _WIN32 - if ((m_File == NULL) && (iMode == fmReadWrite)) + if ((m_File == nullptr) && (iMode == fmReadWrite)) { // Fix for MS not following C spec, opening "a" mode files for writing at the end only // The file open operation has been tried with "read update", fails if file not found @@ -98,7 +98,7 @@ bool cFile::Open(const AString & iFileName, eMode iMode) #endif // _WIN32 } - return (m_File != NULL); + return (m_File != nullptr); } @@ -114,7 +114,7 @@ void cFile::Close(void) } fclose(m_File); - m_File = NULL; + m_File = nullptr; } @@ -123,7 +123,7 @@ void cFile::Close(void) bool cFile::IsOpen(void) const { - return (m_File != NULL); + return (m_File != nullptr); } @@ -366,7 +366,7 @@ int cFile::GetSize(const AString & a_FileName) bool cFile::CreateFolder(const AString & a_FolderPath) { #ifdef _WIN32 - return (CreateDirectoryA(a_FolderPath.c_str(), NULL) != 0); + return (CreateDirectoryA(a_FolderPath.c_str(), nullptr) != 0); #else return (mkdir(a_FolderPath.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0); #endif @@ -415,13 +415,13 @@ AStringVector cFile::GetFolderContents(const AString & a_Folder) { Folder = "."; } - if ((dp = opendir(Folder.c_str())) == NULL) + if ((dp = opendir(Folder.c_str())) == nullptr) { LOGERROR("Error (%i) opening directory \"%s\"\n", errno, Folder.c_str()); } else { - while ((dirp = readdir(dp)) != NULL) + while ((dirp = readdir(dp)) != nullptr) { AllFiles.push_back(dirp->d_name); } diff --git a/src/OSSupport/GZipFile.cpp b/src/OSSupport/GZipFile.cpp index 22d887783..32d84a0d5 100644 --- a/src/OSSupport/GZipFile.cpp +++ b/src/OSSupport/GZipFile.cpp @@ -11,7 +11,7 @@ cGZipFile::cGZipFile(void) : - m_File(NULL), m_Mode(fmRead) + m_File(nullptr), m_Mode(fmRead) { } @@ -30,14 +30,14 @@ cGZipFile::~cGZipFile() bool cGZipFile::Open(const AString & a_FileName, eMode a_Mode) { - if (m_File != NULL) + if (m_File != nullptr) { ASSERT(!"A file is already open in this object"); return false; } m_File = gzopen(a_FileName.c_str(), (a_Mode == fmRead) ? "r" : "w"); m_Mode = a_Mode; - return (m_File != NULL); + return (m_File != nullptr); } @@ -46,10 +46,10 @@ bool cGZipFile::Open(const AString & a_FileName, eMode a_Mode) void cGZipFile::Close(void) { - if (m_File != NULL) + if (m_File != nullptr) { gzclose(m_File); - m_File = NULL; + m_File = nullptr; } } @@ -59,7 +59,7 @@ void cGZipFile::Close(void) int cGZipFile::ReadRestOfFile(AString & a_Contents) { - if (m_File == NULL) + if (m_File == nullptr) { ASSERT(!"No file has been opened"); return -1; @@ -90,7 +90,7 @@ int cGZipFile::ReadRestOfFile(AString & a_Contents) bool cGZipFile::Write(const char * a_Contents, int a_Size) { - if (m_File == NULL) + if (m_File == nullptr) { ASSERT(!"No file has been opened"); return false; diff --git a/src/OSSupport/IsThread.h b/src/OSSupport/IsThread.h index 5de5f31c4..5c8d28d2d 100644 --- a/src/OSSupport/IsThread.h +++ b/src/OSSupport/IsThread.h @@ -31,20 +31,20 @@ protected: /// The overriden Execute() method should check this value periodically and terminate if this is true volatile bool m_ShouldTerminate; - + public: cIsThread(const AString & iThreadName); virtual ~cIsThread(); - + /// Starts the thread; returns without waiting for the actual start bool Start(void); - + /// Signals the thread to terminate and waits until it's finished void Stop(void); - + /// Waits for the thread to finish. Doesn't signalize the ShouldTerminate flag bool Wait(void); - + /// Returns the OS-dependent thread ID for the caller's thread static unsigned long GetCurrentID(void); @@ -53,7 +53,7 @@ public: protected: AString m_ThreadName; - + // Value used for "no handle": #ifdef _WIN32 #define NULL_HANDLE NULL @@ -62,34 +62,34 @@ protected: #endif #ifdef _WIN32 - + DWORD m_ThreadID; HANDLE m_Handle; - + static DWORD __stdcall thrExecute(LPVOID a_Param) { // Create a window so that the thread can be identified by 3rd party tools: HWND IdentificationWnd = CreateWindowA("STATIC", ((cIsThread *)a_Param)->m_ThreadName.c_str(), 0, 0, 0, 0, WS_OVERLAPPED, NULL, NULL, NULL, NULL); - + // Run the thread: ((cIsThread *)a_Param)->Execute(); - + // Destroy the identification window: DestroyWindow(IdentificationWnd); - + return 0; } - + #else // _WIN32 - + pthread_t m_Handle; - + static void * thrExecute(void * a_Param) { - ((cIsThread *)a_Param)->Execute(); + (static_cast<cIsThread *>(a_Param))->Execute(); return NULL; } - + #endif // else _WIN32 } ; @@ -98,7 +98,3 @@ protected: #endif // CISTHREAD_H_INCLUDED - - - - diff --git a/src/OSSupport/ListenThread.cpp b/src/OSSupport/ListenThread.cpp index 02e98acfc..b029634e9 100644 --- a/src/OSSupport/ListenThread.cpp +++ b/src/OSSupport/ListenThread.cpp @@ -214,7 +214,7 @@ void cListenThread::Execute(void) timeval tv; // On Linux select() doesn't seem to wake up when socket is closed, so let's kinda busy-wait: tv.tv_sec = 1; tv.tv_usec = 0; - if (select((int)Highest + 1, &fdRead, NULL, NULL, &tv) == -1) + if (select((int)Highest + 1, &fdRead, nullptr, nullptr, &tv) == -1) { LOG("select(R) call failed in cListenThread: \"%s\"", cSocket::GetLastErrorString().c_str()); continue; diff --git a/src/OSSupport/Semaphore.cpp b/src/OSSupport/Semaphore.cpp index c1fc7d9c7..6a2d57901 100644 --- a/src/OSSupport/Semaphore.cpp +++ b/src/OSSupport/Semaphore.cpp @@ -36,7 +36,7 @@ cSemaphore::cSemaphore( unsigned int a_MaxCount, unsigned int a_InitialCount /* } #else m_Handle = CreateSemaphore( - NULL, // security attribute + nullptr, // security attribute a_InitialCount, // initial count a_MaxCount, // maximum count 0 // name (optional) @@ -98,7 +98,7 @@ void cSemaphore::Signal() LOG("ERROR: Could not signal cSemaphore. (%i)", errno); } #else - ReleaseSemaphore( m_Handle, 1, NULL); + ReleaseSemaphore( m_Handle, 1, nullptr); #endif } diff --git a/src/OSSupport/Socket.cpp b/src/OSSupport/Socket.cpp index c07d31c8b..5025a09ad 100644 --- a/src/OSSupport/Socket.cpp +++ b/src/OSSupport/Socket.cpp @@ -292,7 +292,7 @@ bool cSocket::ConnectIPv4(const AString & a_HostNameOrAddr, unsigned short a_Por { // It is not an IP Address string, but rather a regular hostname, resolve: hostent * hp = gethostbyname(a_HostNameOrAddr.c_str()); - if (hp == NULL) + if (hp == nullptr) { LOGWARNING("%s: Could not resolve hostname \"%s\"", __FUNCTION__, a_HostNameOrAddr.c_str()); CloseSocket(); diff --git a/src/OSSupport/SocketThreads.cpp b/src/OSSupport/SocketThreads.cpp index f436318a5..7a3ef4274 100644 --- a/src/OSSupport/SocketThreads.cpp +++ b/src/OSSupport/SocketThreads.cpp @@ -61,7 +61,7 @@ bool cSocketThreads::AddClient(const cSocket & a_Socket, cCallback * a_Client) // There was an error launching the thread (but it was already logged along with the reason) LOGERROR("A new cSocketThread failed to start"); delete Thread; - Thread = NULL; + Thread = nullptr; return false; } Thread->AddClient(a_Socket, a_Client); @@ -233,7 +233,7 @@ bool cSocketThreads::cSocketThread::RemoveClient(const cCallback * a_Client) // More data to send, shut down reading and wait for the rest to get sent: m_Slots[i].m_State = sSlot::ssWritingRestOut; } - m_Slots[i].m_Client = NULL; + m_Slots[i].m_Client = nullptr; } // Notify the thread of the change: @@ -407,7 +407,7 @@ void cSocketThreads::cSocketThread::Execute(void) timeval Timeout; Timeout.tv_sec = 5; Timeout.tv_usec = 0; - if (select((int)Highest + 1, &fdRead, &fdWrite, NULL, &Timeout) == -1) + if (select((int)Highest + 1, &fdRead, &fdWrite, nullptr, &Timeout) == -1) { LOG("select() call failed in cSocketThread: \"%s\"", cSocket::GetLastErrorString().c_str()); continue; @@ -519,7 +519,7 @@ void cSocketThreads::cSocketThread::ReadFromSockets(fd_set * a_Read) } else { - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { m_Slots[i].m_Client->DataReceived(Buffer, Received); } @@ -545,7 +545,7 @@ void cSocketThreads::cSocketThread::WriteToSockets(fd_set * a_Write) if (m_Slots[i].m_Outgoing.empty()) { // Request another chunk of outgoing data: - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { AString Data; m_Slots[i].m_Client->GetOutgoingData(Data); @@ -573,7 +573,7 @@ void cSocketThreads::cSocketThread::WriteToSockets(fd_set * a_Write) int Err = cSocket::GetLastError(); LOGWARNING("Error %d while writing to client \"%s\", disconnecting. \"%s\"", Err, m_Slots[i].m_Socket.GetIPString().c_str(), GetOSErrorString(Err).c_str()); m_Slots[i].m_Socket.CloseSocket(); - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { m_Slots[i].m_Client->SocketClosed(); } @@ -668,7 +668,7 @@ void cSocketThreads::cSocketThread::QueueOutgoingData(void) cCSLock Lock(m_Parent->m_CS); for (int i = 0; i < m_NumSlots; i++) { - if (m_Slots[i].m_Client != NULL) + if (m_Slots[i].m_Client != nullptr) { AString Data; m_Slots[i].m_Client->GetOutgoingData(Data); diff --git a/src/OSSupport/SocketThreads.h b/src/OSSupport/SocketThreads.h index 944f5f3bc..df819468d 100644 --- a/src/OSSupport/SocketThreads.h +++ b/src/OSSupport/SocketThreads.h @@ -137,7 +137,7 @@ private: /** The socket is primarily owned by this object */ cSocket m_Socket; - /** The callback to call for events. May be NULL */ + /** The callback to call for events. May be nullptr */ cCallback * m_Client; /** If sending writes only partial data, the rest is stored here for another send. diff --git a/src/PolarSSL++/BlockingSslClientSocket.cpp b/src/PolarSSL++/BlockingSslClientSocket.cpp index 699bc57ee..59e1281ac 100644 --- a/src/PolarSSL++/BlockingSslClientSocket.cpp +++ b/src/PolarSSL++/BlockingSslClientSocket.cpp @@ -48,7 +48,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po } // If we have been assigned a trusted CA root cert store, push it into the SSL context: - if (m_CACerts.get() != NULL) + if (m_CACerts.get() != nullptr) { m_Ssl.SetCACerts(m_CACerts, m_ExpectedPeerName); } @@ -72,7 +72,7 @@ bool cBlockingSslClientSocket::Connect(const AString & a_ServerName, UInt16 a_Po bool cBlockingSslClientSocket::SetTrustedRootCertsFromString(const AString & a_CACerts, const AString & a_ExpectedPeerName) { // Warn if used multiple times, but don't signal an error: - if (m_CACerts.get() != NULL) + if (m_CACerts.get() != nullptr) { LOGWARNING( "SSL: Trying to set multiple trusted CA root cert stores, only the last one will be used. Name: %s", diff --git a/src/PolarSSL++/CallbackSslContext.cpp b/src/PolarSSL++/CallbackSslContext.cpp index c4d19b2a0..e061e3f03 100644 --- a/src/PolarSSL++/CallbackSslContext.cpp +++ b/src/PolarSSL++/CallbackSslContext.cpp @@ -12,7 +12,7 @@ cCallbackSslContext::cCallbackSslContext(void) : - m_Callbacks(NULL) + m_Callbacks(nullptr) { // Nothing needed, but the constructor needs to exist so } @@ -32,7 +32,7 @@ cCallbackSslContext::cCallbackSslContext(cCallbackSslContext::cDataCallbacks & a int cCallbackSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_NumBytes) { - if (m_Callbacks == NULL) + if (m_Callbacks == nullptr) { LOGWARNING("SSL: Trying to receive data with no callbacks, aborting."); return POLARSSL_ERR_NET_RECV_FAILED; @@ -46,7 +46,7 @@ int cCallbackSslContext::ReceiveEncrypted(unsigned char * a_Buffer, size_t a_Num int cCallbackSslContext::SendEncrypted(const unsigned char * a_Buffer, size_t a_NumBytes) { - if (m_Callbacks == NULL) + if (m_Callbacks == nullptr) { LOGWARNING("SSL: Trying to send data with no callbacks, aborting."); return POLARSSL_ERR_NET_SEND_FAILED; diff --git a/src/PolarSSL++/CryptoKey.cpp b/src/PolarSSL++/CryptoKey.cpp index 0763c387b..7c4f021b3 100644 --- a/src/PolarSSL++/CryptoKey.cpp +++ b/src/PolarSSL++/CryptoKey.cpp @@ -123,7 +123,7 @@ int cCryptoKey::ParsePrivate(const void * a_Data, size_t a_NumBytes, const AStri if (a_Password.empty()) { - return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, NULL, 0); + return pk_parse_key(&m_Pk, (const unsigned char *)a_Data, a_NumBytes, nullptr, 0); } else { diff --git a/src/PolarSSL++/SslContext.cpp b/src/PolarSSL++/SslContext.cpp index 482470c3a..902267f90 100644 --- a/src/PolarSSL++/SslContext.cpp +++ b/src/PolarSSL++/SslContext.cpp @@ -46,7 +46,7 @@ int cSslContext::Initialize(bool a_IsClient, const SharedPtr<cCtrDrbgContext> & // Set the CtrDrbg context, create a new one if needed: m_CtrDrbg = a_CtrDrbg; - if (m_CtrDrbg.get() == NULL) + if (m_CtrDrbg.get() == nullptr) { m_CtrDrbg.reset(new cCtrDrbgContext); m_CtrDrbg->Initialize("MCServer", 8); @@ -98,7 +98,7 @@ void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cRsaPrivateKe ASSERT(m_IsValid); // Call Initialize() first // Check that both the cert and the key is valid: - if ((a_OwnCert.get() == NULL) || (a_OwnCertPrivKey.get() == NULL)) + if ((a_OwnCert.get() == nullptr) || (a_OwnCertPrivKey.get() == nullptr)) { LOGWARNING("SSL: Own certificate is not valid, skipping the set."); return; @@ -121,7 +121,7 @@ void cSslContext::SetOwnCert(const cX509CertPtr & a_OwnCert, const cCryptoKeyPtr ASSERT(m_IsValid); // Call Initialize() first // Check that both the cert and the key is valid: - if ((a_OwnCert.get() == NULL) || (a_OwnCertPrivKey.get() == NULL)) + if ((a_OwnCert.get() == nullptr) || (a_OwnCertPrivKey.get() == nullptr)) { LOGWARNING("SSL: Own certificate is not valid, skipping the set."); return; @@ -150,7 +150,7 @@ void cSslContext::SetCACerts(const cX509CertPtr & a_CACert, const AString & a_Ex // Set the trusted CA root cert store: ssl_set_authmode(&m_Ssl, SSL_VERIFY_REQUIRED); - ssl_set_ca_chain(&m_Ssl, m_CACerts->GetInternal(), NULL, m_ExpectedPeerName.empty() ? NULL : m_ExpectedPeerName.c_str()); + ssl_set_ca_chain(&m_Ssl, m_CACerts->GetInternal(), nullptr, m_ExpectedPeerName.empty() ? nullptr : m_ExpectedPeerName.c_str()); } diff --git a/src/Protocol/Authenticator.cpp b/src/Protocol/Authenticator.cpp index 984000795..c9e4296a2 100644 --- a/src/Protocol/Authenticator.cpp +++ b/src/Protocol/Authenticator.cpp @@ -7,7 +7,7 @@ #include "../Server.h" #include "../ClientHandle.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index 0a6716e6f..67f513e44 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -7,7 +7,7 @@ #include "MojangAPI.h" #include "SQLiteCpp/Database.h" #include "SQLiteCpp/Statement.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" #include "../RankManager.h" @@ -196,7 +196,7 @@ cMojangAPI::cMojangAPI(void) : m_NameToUUIDAddress(DEFAULT_NAME_TO_UUID_ADDRESS), m_UUIDToProfileServer(DEFAULT_UUID_TO_PROFILE_SERVER), m_UUIDToProfileAddress(DEFAULT_UUID_TO_PROFILE_ADDRESS), - m_RankMgr(NULL), + m_RankMgr(nullptr), m_UpdateThread(new cUpdateThread()) { } @@ -214,14 +214,17 @@ cMojangAPI::~cMojangAPI() -void cMojangAPI::Start(cIniFile & a_SettingsIni) +void cMojangAPI::Start(cIniFile & a_SettingsIni, bool a_ShouldAuth) { m_NameToUUIDServer = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDServer", DEFAULT_NAME_TO_UUID_SERVER); m_NameToUUIDAddress = a_SettingsIni.GetValueSet("MojangAPI", "NameToUUIDAddress", DEFAULT_NAME_TO_UUID_ADDRESS); m_UUIDToProfileServer = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileServer", DEFAULT_UUID_TO_PROFILE_SERVER); m_UUIDToProfileAddress = a_SettingsIni.GetValueSet("MojangAPI", "UUIDToProfileAddress", DEFAULT_UUID_TO_PROFILE_ADDRESS); LoadCachesFromDisk(); - m_UpdateThread->Start(); + if (a_ShouldAuth) + { + m_UpdateThread->Start(); + } } @@ -332,7 +335,7 @@ AStringVector cMojangAPI::GetUUIDsFromPlayerNames(const AStringVector & a_Player void cMojangAPI::AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const AString & a_UUID) { AString UUID = MakeUUIDShort(a_UUID); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); m_NameToUUID[StrToLower(a_PlayerName)] = sProfile(a_PlayerName, UUID, "", "", Now); @@ -351,7 +354,7 @@ void cMojangAPI::AddPlayerNameToUUIDMapping(const AString & a_PlayerName, const void cMojangAPI::AddPlayerProfile(const AString & a_PlayerName, const AString & a_UUID, const Json::Value & a_Properties) { AString UUID = MakeUUIDShort(a_UUID); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); m_NameToUUID[StrToLower(a_PlayerName)] = sProfile(a_PlayerName, UUID, "", "", Now); @@ -555,7 +558,7 @@ void cMojangAPI::SaveCachesToDisk(void) db.exec("DELETE FROM UUIDToProfile"); // Save all cache entries - m_PlayerNameToUUID: - Int64 LimitDateTime = time(NULL) - MAX_AGE; + Int64 LimitDateTime = time(nullptr) - MAX_AGE; { SQLite::Statement stmt(db, "INSERT INTO PlayerNameToUUID(PlayerName, UUID, DateTime) VALUES (?, ?, ?)"); cCSLock Lock(m_CSNameToUUID); @@ -694,7 +697,7 @@ void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery) // Store the returned results into cache: Json::Value::UInt JsonCount = root.size(); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSNameToUUID); for (Json::Value::UInt idx = 0; idx < JsonCount; ++idx) @@ -828,7 +831,7 @@ void cMojangAPI::QueryUUIDToProfile(const AString & a_UUID) return; } Json::Value Properties = root.get("properties", ""); - Int64 Now = time(NULL); + Int64 Now = time(nullptr); { cCSLock Lock(m_CSUUIDToProfile); m_UUIDToProfile[a_UUID] = sProfile(PlayerName, a_UUID, Properties, Now); @@ -852,7 +855,7 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ { // Notify the rank manager: cCSLock Lock(m_CSRankMgr); - if (m_RankMgr != NULL) + if (m_RankMgr != nullptr) { m_RankMgr->NotifyNameUUID(a_PlayerName, a_UUID); } @@ -864,7 +867,7 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ void cMojangAPI::Update(void) { - Int64 LimitDateTime = time(NULL) - MAX_AGE; + Int64 LimitDateTime = time(nullptr) - MAX_AGE; // Re-query all playernames that are stale: AStringVector PlayerNames; diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h index fa4c16e4e..0dc2617b6 100644 --- a/src/Protocol/MojangAPI.h +++ b/src/Protocol/MojangAPI.h @@ -38,7 +38,7 @@ public: /** Initializes the API; reads the settings from the specified ini file. Loads cached results from disk. */ - void Start(cIniFile & a_SettingsIni); + void Start(cIniFile & a_SettingsIni, bool a_ShouldAuth); /** Connects to the specified server using SSL, sends the given request and receives the response. Checks Mojang certificates using the hard-coded Starfield root CA certificate. @@ -89,7 +89,7 @@ public: the profile to the respective mapping caches and updtes their datetime stamp to now. */ void AddPlayerProfile(const AString & a_PlayerName, const AString & a_UUID, const Json::Value & a_Properties); - /** Sets the m_RankMgr that is used for name-uuid notifications. Accepts NULL to remove the binding. */ + /** Sets the m_RankMgr that is used for name-uuid notifications. Accepts nullptr to remove the binding. */ void SetRankManager(cRankManager * a_RankManager) { m_RankMgr = a_RankManager; } protected: @@ -112,7 +112,7 @@ protected: m_UUID(), m_Textures(), m_TexturesSignature(), - m_DateTime(time(NULL)) + m_DateTime(time(nullptr)) { } @@ -176,7 +176,7 @@ protected: /** Protects m_UUIDToProfile against simultaneous multi-threaded access. */ cCriticalSection m_CSUUIDToProfile; - /** The rank manager that is notified of the name-uuid pairings. May be NULL. Protected by m_CSRankMgr. */ + /** The rank manager that is notified of the name-uuid pairings. May be nullptr. Protected by m_CSRankMgr. */ cRankManager * m_RankMgr; /** Protects m_RankMgr agains simultaneous multi-threaded access. */ diff --git a/src/Protocol/Protocol.h b/src/Protocol/Protocol.h index 7225f663d..02a8a52f6 100644 --- a/src/Protocol/Protocol.h +++ b/src/Protocol/Protocol.h @@ -130,7 +130,7 @@ public: virtual void SendWholeInventory (const cWindow & a_Window) = 0; virtual void SendWindowClose (const cWindow & a_Window) = 0; virtual void SendWindowOpen (const cWindow & a_Window) = 0; - virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) = 0; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) = 0; /// Returns the ServerID used for authentication through session.minecraft.net virtual AString GetAuthServerID(void) = 0; diff --git a/src/Protocol/Protocol17x.cpp b/src/Protocol/Protocol17x.cpp index a7abd240f..1d108ce9c 100644 --- a/src/Protocol/Protocol17x.cpp +++ b/src/Protocol/Protocol17x.cpp @@ -120,7 +120,7 @@ cProtocol172::cProtocol172(cClientHandle * a_Client, const AString & a_ServerAdd { static int sCounter = 0; cFile::CreateFolder("CommLogs"); - AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(NULL), sCounter++, a_Client->GetIPString().c_str()); + AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(nullptr), sCounter++, a_Client->GetIPString().c_str()); m_CommLogFile.Open(FileName, cFile::fmWrite); } } @@ -159,7 +159,7 @@ void cProtocol172::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_ cPacketizer Pkt(*this, 0x1b); // Attach Entity packet Pkt.WriteInt(a_Entity.GetUniqueID()); - Pkt.WriteInt((a_Vehicle != NULL) ? a_Vehicle->GetUniqueID() : 0); + Pkt.WriteInt((a_Vehicle != nullptr) ? a_Vehicle->GetUniqueID() : 0); Pkt.WriteBool(false); } @@ -254,7 +254,7 @@ void cProtocol172::SendChat(const cCompositeChat & a_Message) ASSERT(m_State == 3); // In game mode? cWorld * World = m_Client->GetPlayer()->GetWorld(); - bool ShouldUseChatPrefixes = (World == NULL) ? false : World->ShouldUseChatPrefixes(); + bool ShouldUseChatPrefixes = (World == nullptr) ? false : World->ShouldUseChatPrefixes(); // Send the message to the client: cPacketizer Pkt(*this, 0x02); @@ -1439,7 +1439,7 @@ void cProtocol172::SendWindowOpen(const cWindow & a_Window) -void cProtocol172::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocol172::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { ASSERT(m_State == 3); // In game mode? @@ -1901,6 +1901,7 @@ void cProtocol172::HandlePacketClientSettings(cByteBuffer & a_ByteBuffer) HANDLE_READ(a_ByteBuffer, ReadByte, Byte, ShowCape); m_Client->SetLocale(Locale); + m_Client->SetViewDistance(ViewDistance); // TODO: Do anything with the other values. } @@ -2803,7 +2804,7 @@ void cProtocol172::cPacketizer::WriteEntityMetadata(const cEntity & a_Entity) WriteByte(0xA2); WriteItem(Frame.GetItem()); WriteByte(0x3); - WriteByte(Frame.GetRotation() / 2); + WriteByte(Frame.GetItemRotation() / 2); break; } default: break; diff --git a/src/Protocol/Protocol17x.h b/src/Protocol/Protocol17x.h index 7709df59d..f939bfb5e 100644 --- a/src/Protocol/Protocol17x.h +++ b/src/Protocol/Protocol17x.h @@ -134,7 +134,7 @@ public: virtual void SendWholeInventory (const cWindow & a_Window) override; virtual void SendWindowClose (const cWindow & a_Window) override; virtual void SendWindowOpen (const cWindow & a_Window) override; - virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override { return m_AuthServerID; } diff --git a/src/Protocol/Protocol18x.cpp b/src/Protocol/Protocol18x.cpp index acdb48cf7..8170a494f 100644 --- a/src/Protocol/Protocol18x.cpp +++ b/src/Protocol/Protocol18x.cpp @@ -107,7 +107,7 @@ cProtocol180::cProtocol180(cClientHandle * a_Client, const AString & a_ServerAdd { static int sCounter = 0; cFile::CreateFolder("CommLogs"); - AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(NULL), sCounter++, a_Client->GetIPString().c_str()); + AString FileName = Printf("CommLogs/%x_%d__%s.log", (unsigned)time(nullptr), sCounter++, a_Client->GetIPString().c_str()); m_CommLogFile.Open(FileName, cFile::fmWrite); } } @@ -146,7 +146,7 @@ void cProtocol180::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_ cPacketizer Pkt(*this, 0x1b); // Attach Entity packet Pkt.WriteInt(a_Entity.GetUniqueID()); - Pkt.WriteInt((a_Vehicle != NULL) ? a_Vehicle->GetUniqueID() : 0); + Pkt.WriteInt((a_Vehicle != nullptr) ? a_Vehicle->GetUniqueID() : 0); Pkt.WriteBool(false); } @@ -234,7 +234,7 @@ void cProtocol180::SendChat(const cCompositeChat & a_Message) ASSERT(m_State == 3); // In game mode? cWorld * World = m_Client->GetPlayer()->GetWorld(); - bool ShouldUseChatPrefixes = (World == NULL) ? false : World->ShouldUseChatPrefixes(); + bool ShouldUseChatPrefixes = (World == nullptr) ? false : World->ShouldUseChatPrefixes(); // Send the message to the client: cPacketizer Pkt(*this, 0x02); @@ -1500,7 +1500,7 @@ void cProtocol180::SendWindowOpen(const cWindow & a_Window) -void cProtocol180::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocol180::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { ASSERT(m_State == 3); // In game mode? @@ -2160,6 +2160,7 @@ void cProtocol180::HandlePacketClientSettings(cByteBuffer & a_ByteBuffer) HANDLE_READ(a_ByteBuffer, ReadChar, char, SkinFlags); m_Client->SetLocale(Locale); + m_Client->SetViewDistance(ViewDistance); // TODO: Handle other values } @@ -3109,7 +3110,7 @@ void cProtocol180::cPacketizer::WriteEntityMetadata(const cEntity & a_Entity) WriteByte(0xA8); WriteItem(Frame.GetItem()); WriteByte(0x09); - WriteByte(Frame.GetRotation()); + WriteByte(Frame.GetItemRotation()); break; } default: break; diff --git a/src/Protocol/Protocol18x.h b/src/Protocol/Protocol18x.h index 8c0b77a21..92d9825ef 100644 --- a/src/Protocol/Protocol18x.h +++ b/src/Protocol/Protocol18x.h @@ -133,7 +133,7 @@ public: virtual void SendWholeInventory (const cWindow & a_Window) override; virtual void SendWindowClose (const cWindow & a_Window) override; virtual void SendWindowOpen (const cWindow & a_Window) override; - virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override { return m_AuthServerID; } diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 15bcd03b1..af9e0d1bc 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -22,7 +22,7 @@ cProtocolRecognizer::cProtocolRecognizer(cClientHandle * a_Client) : super(a_Client), - m_Protocol(NULL), + m_Protocol(nullptr), m_Buffer(8192) // We need a larger buffer to support BungeeCord - it sends one huge packet at the start { } @@ -34,7 +34,7 @@ cProtocolRecognizer::cProtocolRecognizer(cClientHandle * a_Client) : cProtocolRecognizer::~cProtocolRecognizer() { delete m_Protocol; - m_Protocol = NULL; + m_Protocol = nullptr; } @@ -59,7 +59,7 @@ AString cProtocolRecognizer::GetVersionTextFromInt(int a_ProtocolVersion) void cProtocolRecognizer::DataReceived(const char * a_Data, size_t a_Size) { - if (m_Protocol == NULL) + if (m_Protocol == nullptr) { if (!m_Buffer.Write(a_Data, a_Size)) { @@ -90,7 +90,7 @@ void cProtocolRecognizer::DataReceived(const char * a_Data, size_t a_Size) void cProtocolRecognizer::SendAttachEntity(const cEntity & a_Entity, const cEntity * a_Vehicle) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendAttachEntity(a_Entity, a_Vehicle); } @@ -100,7 +100,7 @@ void cProtocolRecognizer::SendAttachEntity(const cEntity & a_Entity, const cEnti void cProtocolRecognizer::SendBlockAction(int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockAction(a_BlockX, a_BlockY, a_BlockZ, a_Byte1, a_Byte2, a_BlockType); } @@ -110,7 +110,7 @@ void cProtocolRecognizer::SendBlockAction(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a_BlockY, int a_BlockZ, char stage) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockBreakAnim(a_entityID, a_BlockX, a_BlockY, a_BlockZ, stage); } @@ -120,7 +120,7 @@ void cProtocolRecognizer::SendBlockBreakAnim(int a_entityID, int a_BlockX, int a void cProtocolRecognizer::SendBlockChange(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockChange(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta); } @@ -130,7 +130,7 @@ void cProtocolRecognizer::SendBlockChange(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSetBlockVector & a_Changes) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendBlockChanges(a_ChunkX, a_ChunkZ, a_Changes); } @@ -140,7 +140,7 @@ void cProtocolRecognizer::SendBlockChanges(int a_ChunkX, int a_ChunkZ, const sSe void cProtocolRecognizer::SendChat(const AString & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChat(a_Message); } @@ -150,7 +150,7 @@ void cProtocolRecognizer::SendChat(const AString & a_Message) void cProtocolRecognizer::SendChat(const cCompositeChat & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChat(a_Message); } @@ -160,7 +160,7 @@ void cProtocolRecognizer::SendChat(const cCompositeChat & a_Message) void cProtocolRecognizer::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendChunkData(a_ChunkX, a_ChunkZ, a_Serializer); } @@ -170,7 +170,7 @@ void cProtocolRecognizer::SendChunkData(int a_ChunkX, int a_ChunkZ, cChunkDataSe void cProtocolRecognizer::SendCollectEntity(const cEntity & a_Entity, const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendCollectEntity(a_Entity, a_Player); } @@ -180,7 +180,7 @@ void cProtocolRecognizer::SendCollectEntity(const cEntity & a_Entity, const cPla void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendDestroyEntity(a_Entity); } @@ -190,7 +190,7 @@ void cProtocolRecognizer::SendDestroyEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) { - if (m_Protocol != NULL) + if (m_Protocol != nullptr) { m_Protocol->SendDisconnect(a_Reason); } @@ -212,7 +212,7 @@ void cProtocolRecognizer::SendDisconnect(const AString & a_Reason) void cProtocolRecognizer::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEditSign(a_BlockX, a_BlockY, a_BlockZ); } @@ -222,7 +222,7 @@ void cProtocolRecognizer::SendEditSign(int a_BlockX, int a_BlockY, int a_BlockZ) void cProtocolRecognizer::SendEntityEffect(const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityEffect(a_Entity, a_EffectID, a_Amplifier, a_Duration); } @@ -232,7 +232,7 @@ void cProtocolRecognizer::SendEntityEffect(const cEntity & a_Entity, int a_Effec void cProtocolRecognizer::SendEntityEquipment(const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityEquipment(a_Entity, a_SlotNum, a_Item); } @@ -242,7 +242,7 @@ void cProtocolRecognizer::SendEntityEquipment(const cEntity & a_Entity, short a_ void cProtocolRecognizer::SendEntityHeadLook(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityHeadLook(a_Entity); } @@ -252,7 +252,7 @@ void cProtocolRecognizer::SendEntityHeadLook(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityLook(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityLook(a_Entity); } @@ -262,7 +262,7 @@ void cProtocolRecognizer::SendEntityLook(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityMetadata(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityMetadata(a_Entity); } @@ -272,7 +272,7 @@ void cProtocolRecognizer::SendEntityMetadata(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityProperties(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityProperties(a_Entity); } @@ -282,7 +282,7 @@ void cProtocolRecognizer::SendEntityProperties(const cEntity & a_Entity) void cProtocolRecognizer::SendEntityRelMove(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityRelMove(a_Entity, a_RelX, a_RelY, a_RelZ); } @@ -292,7 +292,7 @@ void cProtocolRecognizer::SendEntityRelMove(const cEntity & a_Entity, char a_Rel void cProtocolRecognizer::SendEntityRelMoveLook(const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityRelMoveLook(a_Entity, a_RelX, a_RelY, a_RelZ); } @@ -302,7 +302,7 @@ void cProtocolRecognizer::SendEntityRelMoveLook(const cEntity & a_Entity, char a void cProtocolRecognizer::SendEntityStatus(const cEntity & a_Entity, char a_Status) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityStatus(a_Entity, a_Status); } @@ -312,7 +312,7 @@ void cProtocolRecognizer::SendEntityStatus(const cEntity & a_Entity, char a_Stat void cProtocolRecognizer::SendEntityVelocity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityVelocity(a_Entity); } @@ -322,7 +322,7 @@ void cProtocolRecognizer::SendEntityVelocity(const cEntity & a_Entity) void cProtocolRecognizer::SendExplosion(double a_BlockX, double a_BlockY, double a_BlockZ, float a_Radius, const cVector3iArray & a_BlocksAffected, const Vector3d & a_PlayerMotion) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExplosion(a_BlockX, a_BlockY, a_BlockZ, a_Radius, a_BlocksAffected, a_PlayerMotion); } @@ -332,7 +332,7 @@ void cProtocolRecognizer::SendExplosion(double a_BlockX, double a_BlockY, double void cProtocolRecognizer::SendGameMode(eGameMode a_GameMode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendGameMode(a_GameMode); } @@ -342,7 +342,7 @@ void cProtocolRecognizer::SendGameMode(eGameMode a_GameMode) void cProtocolRecognizer::SendHealth(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendHealth(); } @@ -350,9 +350,9 @@ void cProtocolRecognizer::SendHealth(void) -void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, int a_Property, int a_Value) +void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, short a_Property, short a_Value) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowProperty(a_Window, a_Property, a_Value); } @@ -362,7 +362,7 @@ void cProtocolRecognizer::SendWindowProperty(const cWindow & a_Window, int a_Pro void cProtocolRecognizer::SendInventorySlot(char a_WindowID, short a_SlotNum, const cItem & a_Item) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendInventorySlot(a_WindowID, a_SlotNum, a_Item); } @@ -372,7 +372,7 @@ void cProtocolRecognizer::SendInventorySlot(char a_WindowID, short a_SlotNum, co void cProtocolRecognizer::SendKeepAlive(int a_PingID) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendKeepAlive(a_PingID); } @@ -382,7 +382,7 @@ void cProtocolRecognizer::SendKeepAlive(int a_PingID) void cProtocolRecognizer::SendLogin(const cPlayer & a_Player, const cWorld & a_World) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendLogin(a_Player, a_World); } @@ -392,7 +392,7 @@ void cProtocolRecognizer::SendLogin(const cPlayer & a_Player, const cWorld & a_W void cProtocolRecognizer::SendLoginSuccess(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendLoginSuccess(); } @@ -402,7 +402,7 @@ void cProtocolRecognizer::SendLoginSuccess(void) void cProtocolRecognizer::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * a_Colors, unsigned int a_Length, unsigned int m_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapColumn(a_ID, a_X, a_Y, a_Colors, a_Length, m_Scale); } @@ -412,7 +412,7 @@ void cProtocolRecognizer::SendMapColumn(int a_ID, int a_X, int a_Y, const Byte * void cProtocolRecognizer::SendMapDecorators(int a_ID, const cMapDecoratorList & a_Decorators, unsigned int m_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapDecorators(a_ID, a_Decorators, m_Scale); } @@ -422,7 +422,7 @@ void cProtocolRecognizer::SendMapDecorators(int a_ID, const cMapDecoratorList & void cProtocolRecognizer::SendMapInfo(int a_ID, unsigned int a_Scale) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendMapInfo(a_ID, a_Scale); } @@ -432,7 +432,7 @@ void cProtocolRecognizer::SendMapInfo(int a_ID, unsigned int a_Scale) void cProtocolRecognizer::SendParticleEffect(const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendParticleEffect(a_ParticleName, a_SrcX, a_SrcY, a_SrcZ, a_OffsetX, a_OffsetY, a_OffsetZ, a_ParticleData, a_ParticleAmount); } @@ -450,7 +450,7 @@ void cProtocolRecognizer::SendPaintingSpawn(const cPainting & a_Painting) void cProtocolRecognizer::SendPickupSpawn(const cPickup & a_Pickup) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPickupSpawn(a_Pickup); } @@ -460,7 +460,7 @@ void cProtocolRecognizer::SendPickupSpawn(const cPickup & a_Pickup) void cProtocolRecognizer::SendPlayerAbilities(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerAbilities(); } @@ -470,7 +470,7 @@ void cProtocolRecognizer::SendPlayerAbilities(void) void cProtocolRecognizer::SendEntityAnimation(const cEntity & a_Entity, char a_Animation) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendEntityAnimation(a_Entity, a_Animation); } @@ -480,7 +480,7 @@ void cProtocolRecognizer::SendEntityAnimation(const cEntity & a_Entity, char a_A void cProtocolRecognizer::SendPlayerListAddPlayer(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListAddPlayer(a_Player); } @@ -490,7 +490,7 @@ void cProtocolRecognizer::SendPlayerListAddPlayer(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListRemovePlayer(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListRemovePlayer(a_Player); } @@ -500,7 +500,7 @@ void cProtocolRecognizer::SendPlayerListRemovePlayer(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdateGameMode(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdateGameMode(a_Player); } @@ -510,7 +510,7 @@ void cProtocolRecognizer::SendPlayerListUpdateGameMode(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdatePing(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdatePing(a_Player); } @@ -520,7 +520,7 @@ void cProtocolRecognizer::SendPlayerListUpdatePing(const cPlayer & a_Player) void cProtocolRecognizer::SendPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerListUpdateDisplayName(a_Player, a_CustomName); } @@ -530,7 +530,7 @@ void cProtocolRecognizer::SendPlayerListUpdateDisplayName(const cPlayer & a_Play void cProtocolRecognizer::SendPlayerMaxSpeed(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerMaxSpeed(); } @@ -540,7 +540,7 @@ void cProtocolRecognizer::SendPlayerMaxSpeed(void) void cProtocolRecognizer::SendPlayerMoveLook(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerMoveLook(); } @@ -550,7 +550,7 @@ void cProtocolRecognizer::SendPlayerMoveLook(void) void cProtocolRecognizer::SendPlayerPosition(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerPosition(); } @@ -560,7 +560,7 @@ void cProtocolRecognizer::SendPlayerPosition(void) void cProtocolRecognizer::SendPlayerSpawn(const cPlayer & a_Player) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPlayerSpawn(a_Player); } @@ -570,7 +570,7 @@ void cProtocolRecognizer::SendPlayerSpawn(const cPlayer & a_Player) void cProtocolRecognizer::SendPluginMessage(const AString & a_Channel, const AString & a_Message) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendPluginMessage(a_Channel, a_Message); } @@ -580,7 +580,7 @@ void cProtocolRecognizer::SendPluginMessage(const AString & a_Channel, const ASt void cProtocolRecognizer::SendRemoveEntityEffect(const cEntity & a_Entity, int a_EffectID) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendRemoveEntityEffect(a_Entity, a_EffectID); } @@ -590,7 +590,7 @@ void cProtocolRecognizer::SendRemoveEntityEffect(const cEntity & a_Entity, int a void cProtocolRecognizer::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnoreDimensionChecks) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendRespawn(a_Dimension, a_ShouldIgnoreDimensionChecks); } @@ -600,7 +600,7 @@ void cProtocolRecognizer::SendRespawn(eDimension a_Dimension, bool a_ShouldIgnor void cProtocolRecognizer::SendExperience(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExperience(); } @@ -610,7 +610,7 @@ void cProtocolRecognizer::SendExperience(void) void cProtocolRecognizer::SendExperienceOrb(const cExpOrb & a_ExpOrb) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendExperienceOrb(a_ExpOrb); } @@ -620,7 +620,7 @@ void cProtocolRecognizer::SendExperienceOrb(const cExpOrb & a_ExpOrb) void cProtocolRecognizer::SendScoreboardObjective(const AString & a_Name, const AString & a_DisplayName, Byte a_Mode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendScoreboardObjective(a_Name, a_DisplayName, a_Mode); } @@ -630,7 +630,7 @@ void cProtocolRecognizer::SendScoreboardObjective(const AString & a_Name, const void cProtocolRecognizer::SendScoreUpdate(const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendScoreUpdate(a_Objective, a_Player, a_Score, a_Mode); } @@ -640,7 +640,7 @@ void cProtocolRecognizer::SendScoreUpdate(const AString & a_Objective, const ASt void cProtocolRecognizer::SendDisplayObjective(const AString & a_Objective, cScoreboard::eDisplaySlot a_Display) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendDisplayObjective(a_Objective, a_Display); } @@ -650,7 +650,7 @@ void cProtocolRecognizer::SendDisplayObjective(const AString & a_Objective, cSco void cProtocolRecognizer::SendSoundEffect(const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSoundEffect(a_SoundName, a_X, a_Y, a_Z, a_Volume, a_Pitch); } @@ -660,7 +660,7 @@ void cProtocolRecognizer::SendSoundEffect(const AString & a_SoundName, double a_ void cProtocolRecognizer::SendSoundParticleEffect(int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSoundParticleEffect(a_EffectID, a_SrcX, a_SrcY, a_SrcZ, a_Data); } @@ -670,7 +670,7 @@ void cProtocolRecognizer::SendSoundParticleEffect(int a_EffectID, int a_SrcX, in void cProtocolRecognizer::SendSpawnFallingBlock(const cFallingBlock & a_FallingBlock) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnFallingBlock(a_FallingBlock); } @@ -680,7 +680,7 @@ void cProtocolRecognizer::SendSpawnFallingBlock(const cFallingBlock & a_FallingB void cProtocolRecognizer::SendSpawnMob(const cMonster & a_Mob) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnMob(a_Mob); } @@ -690,7 +690,7 @@ void cProtocolRecognizer::SendSpawnMob(const cMonster & a_Mob) void cProtocolRecognizer::SendSpawnObject(const cEntity & a_Entity, char a_ObjectType, int a_ObjectData, Byte a_Yaw, Byte a_Pitch) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnObject(a_Entity, a_ObjectType, a_ObjectData, a_Yaw, a_Pitch); } @@ -700,7 +700,7 @@ void cProtocolRecognizer::SendSpawnObject(const cEntity & a_Entity, char a_Objec void cProtocolRecognizer::SendSpawnVehicle(const cEntity & a_Vehicle, char a_VehicleType, char a_VehicleSubType) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendSpawnVehicle(a_Vehicle, a_VehicleType, a_VehicleSubType); } @@ -710,7 +710,7 @@ void cProtocolRecognizer::SendSpawnVehicle(const cEntity & a_Vehicle, char a_Veh void cProtocolRecognizer::SendStatistics(const cStatManager & a_Manager) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendStatistics(a_Manager); } @@ -720,7 +720,7 @@ void cProtocolRecognizer::SendStatistics(const cStatManager & a_Manager) void cProtocolRecognizer::SendTabCompletionResults(const AStringVector & a_Results) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTabCompletionResults(a_Results); } @@ -730,7 +730,7 @@ void cProtocolRecognizer::SendTabCompletionResults(const AStringVector & a_Resul void cProtocolRecognizer::SendTeleportEntity(const cEntity & a_Entity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTeleportEntity(a_Entity); } @@ -740,7 +740,7 @@ void cProtocolRecognizer::SendTeleportEntity(const cEntity & a_Entity) void cProtocolRecognizer::SendThunderbolt(int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendThunderbolt(a_BlockX, a_BlockY, a_BlockZ); } @@ -750,7 +750,7 @@ void cProtocolRecognizer::SendThunderbolt(int a_BlockX, int a_BlockY, int a_Bloc void cProtocolRecognizer::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bool a_DoDaylightCycle) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendTimeUpdate(a_WorldAge, a_TimeOfDay, a_DoDaylightCycle); } @@ -760,7 +760,7 @@ void cProtocolRecognizer::SendTimeUpdate(Int64 a_WorldAge, Int64 a_TimeOfDay, bo void cProtocolRecognizer::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUnloadChunk(a_ChunkX, a_ChunkZ); } @@ -770,7 +770,7 @@ void cProtocolRecognizer::SendUnloadChunk(int a_ChunkX, int a_ChunkZ) void cProtocolRecognizer::SendUpdateBlockEntity(cBlockEntity & a_BlockEntity) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUpdateBlockEntity(a_BlockEntity); } @@ -780,7 +780,7 @@ void cProtocolRecognizer::SendUpdateBlockEntity(cBlockEntity & a_BlockEntity) void cProtocolRecognizer::SendUpdateSign(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUpdateSign(a_BlockX, a_BlockY, a_BlockZ, a_Line1, a_Line2, a_Line3, a_Line4); } @@ -790,7 +790,7 @@ void cProtocolRecognizer::SendUpdateSign(int a_BlockX, int a_BlockY, int a_Block void cProtocolRecognizer::SendUseBed(const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendUseBed(a_Entity, a_BlockX, a_BlockY, a_BlockZ); } @@ -800,7 +800,7 @@ void cProtocolRecognizer::SendUseBed(const cEntity & a_Entity, int a_BlockX, int void cProtocolRecognizer::SendWeather(eWeather a_Weather) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWeather(a_Weather); } @@ -810,7 +810,7 @@ void cProtocolRecognizer::SendWeather(eWeather a_Weather) void cProtocolRecognizer::SendWholeInventory(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWholeInventory(a_Window); } @@ -820,7 +820,7 @@ void cProtocolRecognizer::SendWholeInventory(const cWindow & a_Window) void cProtocolRecognizer::SendWindowClose(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowClose(a_Window); } @@ -830,7 +830,7 @@ void cProtocolRecognizer::SendWindowClose(const cWindow & a_Window) void cProtocolRecognizer::SendWindowOpen(const cWindow & a_Window) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); m_Protocol->SendWindowOpen(a_Window); } @@ -840,7 +840,7 @@ void cProtocolRecognizer::SendWindowOpen(const cWindow & a_Window) AString cProtocolRecognizer::GetAuthServerID(void) { - ASSERT(m_Protocol != NULL); + ASSERT(m_Protocol != nullptr); return m_Protocol->GetAuthServerID(); } diff --git a/src/Protocol/ProtocolRecognizer.h b/src/Protocol/ProtocolRecognizer.h index b42cfdec2..dcf653e75 100644 --- a/src/Protocol/ProtocolRecognizer.h +++ b/src/Protocol/ProtocolRecognizer.h @@ -121,7 +121,7 @@ public: virtual void SendWholeInventory (const cWindow & a_Window) override; virtual void SendWindowClose (const cWindow & a_Window) override; virtual void SendWindowOpen (const cWindow & a_Window) override; - virtual void SendWindowProperty (const cWindow & a_Window, int a_Property, int a_Value) override; + virtual void SendWindowProperty (const cWindow & a_Window, short a_Property, short a_Value) override; virtual AString GetAuthServerID(void) override; diff --git a/src/RCONServer.cpp b/src/RCONServer.cpp index 141c67d1b..49ca4fc61 100644 --- a/src/RCONServer.cpp +++ b/src/RCONServer.cpp @@ -4,7 +4,7 @@ // Implements the cRCONServer class representing the RCON server #include "Globals.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "RCONServer.h" #include "Server.h" #include "Root.h" @@ -242,7 +242,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, if (strncmp(a_Payload, m_RCONServer.m_Password.c_str(), a_PayloadLength) != 0) { LOGINFO("RCON: Invalid password from client %s, dropping connection.", m_IPAddress.c_str()); - SendResponse(-1, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(-1, RCON_PACKET_RESPONSE, 0, nullptr); return false; } m_IsAuthenticated = true; @@ -250,7 +250,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, LOGD("RCON: Client at %s has successfully authenticated", m_IPAddress.c_str()); // Send OK response: - SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } @@ -268,7 +268,7 @@ bool cRCONServer::cConnection::ProcessPacket(int a_RequestID, int a_PacketType, cRoot::Get()->ExecuteConsoleCommand(cmd, *(new cRCONCommandOutput(*this, a_RequestID))); // Send an empty response: - SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, NULL); + SendResponse(a_RequestID, RCON_PACKET_RESPONSE, 0, nullptr); return true; } } @@ -310,7 +310,7 @@ void cRCONServer::cConnection::IntToBuffer(int a_Value, char * a_Buffer) /// Sends a RCON packet back to the client void cRCONServer::cConnection::SendResponse(int a_RequestID, int a_PacketType, int a_PayloadLength, const char * a_Payload) { - ASSERT((a_PayloadLength == 0) || (a_Payload != NULL)); // Either zero data to send, or a valid payload ptr + ASSERT((a_PayloadLength == 0) || (a_Payload != nullptr)); // Either zero data to send, or a valid payload ptr char Buffer[4]; int Length = a_PayloadLength + 10; diff --git a/src/RankManager.cpp b/src/RankManager.cpp index f5342ed3d..451de88e7 100644 --- a/src/RankManager.cpp +++ b/src/RankManager.cpp @@ -5,7 +5,7 @@ #include "Globals.h" #include "RankManager.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Protocol/MojangAPI.h" #include "ClientHandle.h" @@ -384,7 +384,7 @@ protected: cRankManager::cRankManager(void) : m_DB("Ranks.sqlite", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE), m_IsInitialized(false), - m_MojangAPI(NULL) + m_MojangAPI(nullptr) { } @@ -394,9 +394,9 @@ cRankManager::cRankManager(void) : cRankManager::~cRankManager() { - if (m_MojangAPI != NULL) + if (m_MojangAPI != nullptr) { - m_MojangAPI->SetRankManager(NULL); + m_MojangAPI->SetRankManager(nullptr); } } diff --git a/src/RankManager.h b/src/RankManager.h index 61c52fda6..5dff634b5 100644 --- a/src/RankManager.h +++ b/src/RankManager.h @@ -240,7 +240,7 @@ protected: bool m_IsInitialized; /** The MojangAPI instance that is used for translating playernames to UUIDs. - Set in Initialize(), may be NULL. */ + Set in Initialize(), may be nullptr. */ cMojangAPI * m_MojangAPI; diff --git a/src/Root.cpp b/src/Root.cpp index aa3d43cba..24c1a4cc8 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -19,11 +19,10 @@ #include "OSSupport/Timer.h" #include "LoggerListeners.h" #include "BuildInfo.h" - -#include "inifile/iniFile.h" +#include "IniFile.h" #ifdef _WIN32 - #include "conio.h" + #include <conio.h> #include <psapi.h> #elif defined(__linux__) #include <fstream> @@ -35,21 +34,21 @@ -cRoot* cRoot::s_Root = NULL; +cRoot* cRoot::s_Root = nullptr; cRoot::cRoot(void) : - m_pDefaultWorld(NULL), - m_InputThread(NULL), - m_Server(NULL), - m_MonsterConfig(NULL), - m_CraftingRecipes(NULL), - m_FurnaceRecipe(NULL), - m_WebAdmin(NULL), - m_PluginManager(NULL), + m_pDefaultWorld(nullptr), + m_InputThread(nullptr), + m_Server(nullptr), + m_MonsterConfig(nullptr), + m_CraftingRecipes(nullptr), + m_FurnaceRecipe(nullptr), + m_WebAdmin(nullptr), + m_PluginManager(nullptr), m_bStop(false), m_bRestart(false) { @@ -142,8 +141,9 @@ void cRoot::Start(void) } LOG("Starting server..."); - m_MojangAPI.Start(IniFile); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init - if (!m_Server->InitServer(IniFile)) + bool ShouldAuthenticate = IniFile.GetValueSetB("Authentication", "Authenticate", true); + m_MojangAPI.Start(IniFile, ShouldAuthenticate); // Mojang API needs to be started before plugins, so that plugins may use it for DB upgrades on server init + if (!m_Server->InitServer(IniFile, ShouldAuthenticate)) { IniFile.WriteFile("settings.ini"); LOGERROR("Failure starting server, aborting..."); @@ -154,7 +154,8 @@ void cRoot::Start(void) m_WebAdmin->Init(); LOGD("Loading settings..."); - m_RankManager.Initialize(m_MojangAPI); + m_RankManager = new cRankManager(); + m_RankManager->Initialize(m_MojangAPI); m_CraftingRecipes = new cCraftingRecipes; m_FurnaceRecipe = new cFurnaceRecipe(); @@ -213,7 +214,7 @@ void cRoot::Start(void) } #if !defined(ANDROID_NDK) - delete m_InputThread; m_InputThread = NULL; + delete m_InputThread; m_InputThread = nullptr; #endif // Stop the server: @@ -228,21 +229,21 @@ void cRoot::Start(void) m_Authenticator.Stop(); LOGD("Freeing MonsterConfig..."); - delete m_MonsterConfig; m_MonsterConfig = NULL; - delete m_WebAdmin; m_WebAdmin = NULL; + delete m_MonsterConfig; m_MonsterConfig = nullptr; + delete m_WebAdmin; m_WebAdmin = nullptr; LOGD("Unloading recipes..."); - delete m_FurnaceRecipe; m_FurnaceRecipe = NULL; - delete m_CraftingRecipes; m_CraftingRecipes = NULL; + delete m_FurnaceRecipe; m_FurnaceRecipe = nullptr; + delete m_CraftingRecipes; m_CraftingRecipes = nullptr; LOGD("Unloading worlds..."); UnloadWorlds(); LOGD("Stopping plugin manager..."); - delete m_PluginManager; m_PluginManager = NULL; + delete m_PluginManager; m_PluginManager = nullptr; cItemHandler::Deinit(); LOG("Cleaning up..."); - delete m_Server; m_Server = NULL; + delete m_Server; m_Server = nullptr; LOG("Shutdown successful!"); } @@ -317,7 +318,7 @@ void cRoot::LoadWorlds(cIniFile & IniFile) cWorld * cRoot::CreateAndInitializeWorld(const AString & a_WorldName, eDimension a_Dimension, const AString & a_OverworldName) { cWorld * World = m_WorldsByName[a_WorldName]; - if (World != NULL) + if (World != nullptr) { return World; } @@ -362,7 +363,7 @@ void cRoot::StopWorlds(void) void cRoot::UnloadWorlds(void) { - m_pDefaultWorld = NULL; + m_pDefaultWorld = nullptr; for (WorldMap::iterator itr = m_WorldsByName.begin(); itr != m_WorldsByName.end(); ++itr) { delete itr->second; @@ -395,7 +396,7 @@ cWorld * cRoot::GetWorld(const AString & a_WorldName, bool a_SearchForFolder) { return CreateAndInitializeWorld(a_WorldName); } - return NULL; + return nullptr; } @@ -407,7 +408,7 @@ bool cRoot::ForEachWorld(cWorldListCallback & a_Callback) for (WorldMap::iterator itr = m_WorldsByName.begin(), itr2 = itr; itr != m_WorldsByName.end(); itr = itr2) { ++itr2; - if (itr->second != NULL) + if (itr->second != nullptr) { if (a_Callback.Item(itr->second)) { @@ -542,7 +543,7 @@ void cRoot::BroadcastChat(const AString & a_Message, eMessageType a_ChatPrefix) { for (WorldMap::iterator itr = m_WorldsByName.begin(), end = m_WorldsByName.end(); itr != end; ++itr) { - itr->second->BroadcastChat(a_Message, NULL, a_ChatPrefix); + itr->second->BroadcastChat(a_Message, nullptr, a_ChatPrefix); } // for itr - m_WorldsByName[] } @@ -612,7 +613,7 @@ bool cRoot::FindAndDoWithPlayer(const AString & a_PlayerName, cPlayerListCallbac m_BestRating(0), m_NameLength(a_PlayerName.length()), m_PlayerName(a_PlayerName), - m_BestMatch(NULL), + m_BestMatch(nullptr), m_NumMatches(0) {} diff --git a/src/Root.h b/src/Root.h index 84c6a98ec..020a6cff0 100644 --- a/src/Root.h +++ b/src/Root.h @@ -86,7 +86,7 @@ public: cPluginManager * GetPluginManager (void) { return m_PluginManager; } // tolua_export cAuthenticator & GetAuthenticator (void) { return m_Authenticator; } cMojangAPI & GetMojangAPI (void) { return m_MojangAPI; } - cRankManager & GetRankManager (void) { return m_RankManager; } + cRankManager * GetRankManager (void) { return m_RankManager; } /** Queues a console command for execution through the cServer class. The command will be executed in the tick thread @@ -185,7 +185,7 @@ private: cPluginManager * m_PluginManager; cAuthenticator m_Authenticator; cMojangAPI m_MojangAPI; - cRankManager m_RankManager; + cRankManager * m_RankManager; cHTTPServer m_HTTPServer; bool m_bStop; diff --git a/src/Scoreboard.cpp b/src/Scoreboard.cpp index def952029..adce8b549 100644 --- a/src/Scoreboard.cpp +++ b/src/Scoreboard.cpp @@ -278,7 +278,7 @@ cScoreboard::cScoreboard(cWorld * a_World) : m_World(a_World) { for (int i = 0; i < (int) dsCount; ++i) { - m_Display[i] = NULL; + m_Display[i] = nullptr; } } @@ -294,14 +294,14 @@ cObjective* cScoreboard::RegisterObjective(const AString & a_Name, const AString if (Status.second) { - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastScoreboardObjective(a_Name, a_DisplayName, 0); return &Status.first->second; } else { - return NULL; + return nullptr; } } @@ -320,14 +320,14 @@ bool cScoreboard::RemoveObjective(const AString & a_Name) return false; } - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastScoreboardObjective(it->second.GetName(), it->second.GetDisplayName(), 1); for (unsigned int i = 0; i < (unsigned int) dsCount; ++i) { if (m_Display[i] == &it->second) { - SetDisplay(NULL, (eDisplaySlot) i); + SetDisplay(nullptr, (eDisplaySlot) i); } } @@ -348,7 +348,7 @@ cObjective * cScoreboard::GetObjective(const AString & a_Name) if (it == m_Objectives.end()) { - return NULL; + return nullptr; } else { @@ -369,7 +369,7 @@ cTeam * cScoreboard::RegisterTeam( std::pair<cTeamMap::iterator, bool> Status = m_Teams.insert(cNamedTeam(a_Name, Team)); - return Status.second ? &Status.first->second : NULL; + return Status.second ? &Status.first->second : nullptr; } @@ -404,7 +404,7 @@ cTeam * cScoreboard::GetTeam(const AString & a_Name) if (it == m_Teams.end()) { - return NULL; + return nullptr; } else { @@ -428,7 +428,7 @@ cTeam * cScoreboard::QueryPlayerTeam(const AString & a_Name) } } - return NULL; + return nullptr; } @@ -452,7 +452,7 @@ void cScoreboard::SetDisplay(cObjective * a_Objective, eDisplaySlot a_Slot) { m_Display[a_Slot] = a_Objective; - ASSERT(m_World != NULL); + ASSERT(m_World != nullptr); m_World->BroadcastDisplayObjective(a_Objective ? a_Objective->GetName() : "", a_Slot); } diff --git a/src/Scoreboard.h b/src/Scoreboard.h index f53b8c803..dd4073c89 100644 --- a/src/Scoreboard.h +++ b/src/Scoreboard.h @@ -226,22 +226,22 @@ public: // tolua_begin - /** Registers a new scoreboard objective, returns the cObjective instance, NULL on name collision */ + /** Registers a new scoreboard objective, returns the cObjective instance, nullptr on name collision */ cObjective * RegisterObjective(const AString & a_Name, const AString & a_DisplayName, cObjective::eType a_Type); /** Removes a registered objective, returns true if operation was successful */ bool RemoveObjective(const AString & a_Name); - /** Retrieves the objective with the specified name, NULL if not found */ + /** Retrieves the objective with the specified name, nullptr if not found */ cObjective * GetObjective(const AString & a_Name); - /** Registers a new team, returns the cTeam instance, NULL on name collision */ + /** Registers a new team, returns the cTeam instance, nullptr on name collision */ cTeam * RegisterTeam(const AString & a_Name, const AString & a_DisplayName, const AString & a_Prefix, const AString & a_Suffix); /** Removes a registered team, returns true if operation was successful */ bool RemoveTeam(const AString & a_Name); - /** Retrieves the team with the specified name, NULL if not found */ + /** Retrieves the team with the specified name, nullptr if not found */ cTeam * GetTeam(const AString & a_Name); void SetDisplay(const AString & a_Objective, eDisplaySlot a_Slot); diff --git a/src/Server.cpp b/src/Server.cpp index 969ffd693..bbb5ecff3 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -22,7 +22,7 @@ #include "MersenneTwister.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "Vector3.h" #include <fstream> @@ -196,7 +196,7 @@ void cServer::PlayerDestroying(const cPlayer * a_Player) -bool cServer::InitServer(cIniFile & a_SettingsIni) +bool cServer::InitServer(cIniFile & a_SettingsIni, bool a_ShouldAuth) { m_Description = a_SettingsIni.GetValueSet("Server", "Description", "MCServer - in C++!"); m_MaxPlayers = a_SettingsIni.GetValueSetI("Server", "MaxPlayers", 100); @@ -247,7 +247,7 @@ bool cServer::InitServer(cIniFile & a_SettingsIni) m_bIsConnected = true; m_ServerID = "-"; - m_ShouldAuthenticate = a_SettingsIni.GetValueSetB("Authentication", "Authenticate", true); + m_ShouldAuthenticate = a_ShouldAuth; if (m_ShouldAuthenticate) { MTRand mtrand1; @@ -338,7 +338,7 @@ void cServer::OnConnectionAccepted(cSocket & a_Socket) LOGERROR("Client \"%s\" cannot be handled, server probably unstable", ClientIP.c_str()); a_Socket.CloseSocket(); delete NewHandle; - NewHandle = NULL; + NewHandle = nullptr; return; } @@ -450,7 +450,7 @@ bool cServer::Start(void) bool cServer::Command(cClientHandle & a_Client, AString & a_Cmd) { - return cRoot::Get()->GetPluginManager()->CallHookChat(a_Client.GetPlayer(), a_Cmd); + return cRoot::Get()->GetPluginManager()->CallHookChat(*(a_Client.GetPlayer()), a_Cmd); } @@ -491,6 +491,17 @@ void cServer::ExecuteConsoleCommand(const AString & a_Cmd, cCommandOutputCallbac { if (split.size() > 1) { + cPluginManager::PluginMap map = cPluginManager::Get()->GetAllPlugins(); + + for (auto plugin_entry : map) + { + if (plugin_entry.first == split[1]) + { + a_Output.Out("Error! Plugin is already loaded!"); + a_Output.Finished(); + return; + } + } a_Output.Out(cPluginManager::Get()->LoadPlugin(split[1]) ? "Plugin loaded" : "Error occurred loading plugin"); } else @@ -626,17 +637,17 @@ void cServer::PrintHelp(const AStringVector & a_Split, cCommandOutputCallback & void cServer::BindBuiltInConsoleCommands(void) { cPluginManager * PlgMgr = cPluginManager::Get(); - PlgMgr->BindConsoleCommand("help", NULL, " - Shows the available commands"); - PlgMgr->BindConsoleCommand("reload", NULL, " - Reloads all plugins"); - PlgMgr->BindConsoleCommand("restart", NULL, " - Restarts the server cleanly"); - PlgMgr->BindConsoleCommand("stop", NULL, " - Stops the server cleanly"); - PlgMgr->BindConsoleCommand("chunkstats", NULL, " - Displays detailed chunk memory statistics"); - PlgMgr->BindConsoleCommand("load <pluginname>", NULL, " - Adds and enables the specified plugin"); - PlgMgr->BindConsoleCommand("unload <pluginname>", NULL, " - Disables the specified plugin"); - PlgMgr->BindConsoleCommand("destroyentities", NULL, " - Destroys all entities in all worlds"); + PlgMgr->BindConsoleCommand("help", nullptr, " - Shows the available commands"); + PlgMgr->BindConsoleCommand("reload", nullptr, " - Reloads all plugins"); + PlgMgr->BindConsoleCommand("restart", nullptr, " - Restarts the server cleanly"); + PlgMgr->BindConsoleCommand("stop", nullptr, " - Stops the server cleanly"); + PlgMgr->BindConsoleCommand("chunkstats", nullptr, " - Displays detailed chunk memory statistics"); + PlgMgr->BindConsoleCommand("load <pluginname>", nullptr, " - Adds and enables the specified plugin"); + PlgMgr->BindConsoleCommand("unload <pluginname>", nullptr, " - Disables the specified plugin"); + PlgMgr->BindConsoleCommand("destroyentities", nullptr, " - Destroys all entities in all worlds"); #if defined(_MSC_VER) && defined(_DEBUG) && defined(ENABLE_LEAK_FINDER) - PlgMgr->BindConsoleCommand("dumpmem", NULL, " - Dumps all used memory blocks together with their callstacks into memdump.xml"); + PlgMgr->BindConsoleCommand("dumpmem", nullptr, " - Dumps all used memory blocks together with their callstacks into memdump.xml"); #endif } @@ -705,7 +716,7 @@ void cServer::AuthenticateUser(int a_ClientID, const AString & a_Name, const ASt cServer::cNotifyWriteThread::cNotifyWriteThread(void) : super("ClientPacketThread"), - m_Server(NULL) + m_Server(nullptr) { } diff --git a/src/Server.h b/src/Server.h index 6d659fa40..022794bbc 100644 --- a/src/Server.h +++ b/src/Server.h @@ -56,7 +56,7 @@ class cServer // tolua_export public: // tolua_export virtual ~cServer() {} - bool InitServer(cIniFile & a_SettingsIni); + bool InitServer(cIniFile & a_SettingsIni, bool a_ShouldAuth); // tolua_begin diff --git a/src/SetChunkData.cpp b/src/SetChunkData.cpp index 707dfb9e8..e335176a8 100644 --- a/src/SetChunkData.cpp +++ b/src/SetChunkData.cpp @@ -42,15 +42,15 @@ cSetChunkData::cSetChunkData( m_ShouldMarkDirty(a_ShouldMarkDirty) { // Check the params' validity: - ASSERT(a_BlockTypes != NULL); - ASSERT(a_BlockMetas != NULL); + ASSERT(a_BlockTypes != nullptr); + ASSERT(a_BlockMetas != nullptr); // Copy block types and metas: memcpy(m_BlockTypes, a_BlockTypes, sizeof(cChunkDef::BlockTypes)); memcpy(m_BlockMetas, a_BlockMetas, sizeof(cChunkDef::BlockNibbles)); // Copy lights, if both given: - if ((a_BlockLight != NULL) && (a_SkyLight != NULL)) + if ((a_BlockLight != nullptr) && (a_SkyLight != nullptr)) { memcpy(m_BlockLight, a_BlockLight, sizeof(m_BlockLight)); memcpy(m_SkyLight, a_SkyLight, sizeof(m_SkyLight)); @@ -62,7 +62,7 @@ cSetChunkData::cSetChunkData( } // Copy the heightmap, if available: - if (a_HeightMap != NULL) + if (a_HeightMap != nullptr) { memcpy(m_HeightMap, a_HeightMap, sizeof(m_HeightMap)); m_IsHeightMapValid = true; @@ -73,7 +73,7 @@ cSetChunkData::cSetChunkData( } // Copy biomes, if available: - if (a_Biomes != NULL) + if (a_Biomes != nullptr) { memcpy(m_Biomes, a_Biomes, sizeof(m_Biomes)); m_AreBiomesValid = true; diff --git a/src/SetChunkData.h b/src/SetChunkData.h index 03e9ef4d9..1eeb75ca9 100644 --- a/src/SetChunkData.h +++ b/src/SetChunkData.h @@ -27,7 +27,7 @@ public: Will move the entity and blockentity lists into the internal storage, and empty the a_Entities and a_BlockEntities lists. a_BlockTypes and a_BlockMetas must always be valid. - If either of the light arrays are NULL, the chunk data will be marked as not having any light at all and + If either of the light arrays are nullptr, the chunk data will be marked as not having any light at all and will be scheduled for re-lighting once it is set into the chunkmap. If a_Biomes is not valid, the internal flag is set and the world will calculate the biomes using the chunk generator when setting the chunk data. diff --git a/src/Simulator/DelayedFluidSimulator.cpp b/src/Simulator/DelayedFluidSimulator.cpp index 59ea51aa0..dc8dffe2d 100644 --- a/src/Simulator/DelayedFluidSimulator.cpp +++ b/src/Simulator/DelayedFluidSimulator.cpp @@ -55,7 +55,7 @@ cDelayedFluidSimulatorChunkData::cDelayedFluidSimulatorChunkData(int a_TickDelay cDelayedFluidSimulatorChunkData::~cDelayedFluidSimulatorChunkData() { delete[] m_Slots; - m_Slots = NULL; + m_Slots = nullptr; } @@ -86,7 +86,7 @@ void cDelayedFluidSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, return; } - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } diff --git a/src/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp index 7ae84af7b..75ebefcf7 100644 --- a/src/Simulator/FireSimulator.cpp +++ b/src/Simulator/FireSimulator.cpp @@ -220,7 +220,7 @@ bool cFireSimulator::DoesBurnForever(BLOCKTYPE a_BlockType) void cFireSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } @@ -333,7 +333,7 @@ void cFireSimulator::TrySpreadFire(cChunk * a_Chunk, int a_RelX, int a_RelY, int int a_PosX = x + a_Chunk->GetPosX() * cChunkDef::Width; int a_PosZ = z + a_Chunk->GetPosZ() * cChunkDef::Width; - if (cRoot::Get()->GetPluginManager()->CallHookBlockSpread(&m_World, a_PosX, y, a_PosZ, ssFireSpread)) + if (cRoot::Get()->GetPluginManager()->CallHookBlockSpread(m_World, a_PosX, y, a_PosZ, ssFireSpread)) { return; } @@ -359,7 +359,7 @@ void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_Rel int Z = a_RelZ + gNeighborCoords[i].z; cChunkPtr Neighbour = a_Chunk->GetRelNeighborChunkAdjustCoords(X, Z); - if (Neighbour == NULL) + if (Neighbour == nullptr) { continue; } @@ -382,7 +382,7 @@ void cFireSimulator::RemoveFuelNeighbors(cChunk * a_Chunk, int a_RelX, int a_Rel } bool ShouldReplaceFuel = (m_World.GetTickRandomNumber(MAX_CHANCE_REPLACE_FUEL) < m_ReplaceFuelChance); - if (ShouldReplaceFuel && !cRoot::Get()->GetPluginManager()->CallHookBlockSpread(&m_World, AbsX, Y, AbsZ, ssFireSpread)) + if (ShouldReplaceFuel && !cRoot::Get()->GetPluginManager()->CallHookBlockSpread(m_World, AbsX, Y, AbsZ, ssFireSpread)) { Neighbour->SetBlock(X, Y, Z, E_BLOCK_FIRE, 0); } diff --git a/src/Simulator/FloodyFluidSimulator.cpp b/src/Simulator/FloodyFluidSimulator.cpp index b839aa746..e95ef216d 100644 --- a/src/Simulator/FloodyFluidSimulator.cpp +++ b/src/Simulator/FloodyFluidSimulator.cpp @@ -220,7 +220,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i ASSERT(a_NewMeta > 0); // Source blocks aren't spread a_NearChunk = a_NearChunk->GetRelNeighborChunkAdjustCoords(a_RelX, a_RelZ); - if ((a_NearChunk == NULL) || (!a_NearChunk->IsValid())) + if ((a_NearChunk == nullptr) || (!a_NearChunk->IsValid())) { // Chunk not available return; @@ -297,7 +297,7 @@ void cFloodyFluidSimulator::SpreadToNeighbor(cChunk * a_NearChunk, int a_RelX, i ChunkInterface, m_World, PluginInterface, - NULL, + nullptr, BlockX, a_RelY, BlockZ diff --git a/src/Simulator/FluidSimulator.cpp b/src/Simulator/FluidSimulator.cpp index 58501326f..9c8453d04 100644 --- a/src/Simulator/FluidSimulator.cpp +++ b/src/Simulator/FluidSimulator.cpp @@ -178,7 +178,7 @@ Direction cFluidSimulator::GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a } delete Pos; - Pos = NULL; + Pos = nullptr; } if (LowestPoint == m_World.GetBlockMeta(a_X, a_Y, a_Z)) diff --git a/src/Simulator/FluidSimulator.h b/src/Simulator/FluidSimulator.h index 0877a7bf1..d65a8e78b 100644 --- a/src/Simulator/FluidSimulator.h +++ b/src/Simulator/FluidSimulator.h @@ -51,7 +51,7 @@ public: virtual Direction GetFlowingDirection(int a_X, int a_Y, int a_Z, bool a_Over = true); /// Creates a ChunkData object for the simulator to use. The simulator returns the correct object type. - virtual cFluidSimulatorData * CreateChunkData(void) { return NULL; } + virtual cFluidSimulatorData * CreateChunkData(void) { return nullptr; } bool IsFluidBlock (BLOCKTYPE a_BlockType) const { return (a_BlockType == m_FluidBlock); } bool IsStationaryFluidBlock(BLOCKTYPE a_BlockType) const { return (a_BlockType == m_StationaryFluidBlock); } diff --git a/src/Simulator/IncrementalRedstoneSimulator.inc b/src/Simulator/IncrementalRedstoneSimulator.inc index 200fc0971..2d03584e2 100644 --- a/src/Simulator/IncrementalRedstoneSimulator.inc +++ b/src/Simulator/IncrementalRedstoneSimulator.inc @@ -2001,7 +2001,6 @@ bool cIncrementalRedstoneSimulator<ChunkType, WorldType, GetHandlerCompileTime, // Check if western(left) neighbor is a powered on repeater who is facing us if (m_Chunk->UnboundedRelGetBlock(a_RelBlockX - 1, a_RelBlockY, a_RelBlockZ, Block, OtherRepeaterDir) && (Block == E_BLOCK_REDSTONE_REPEATER_ON)) { - NIBBLETYPE OtherRepeaterDir = m_Chunk->GetMeta(a_RelBlockX -1, a_RelBlockY, a_RelBlockZ) & 0x3; if ((OtherRepeaterDir & 0x03) == 0x1) { return true; diff --git a/src/Simulator/NoopRedstoneSimulator.h b/src/Simulator/NoopRedstoneSimulator.h index 7c961f32b..832b26dfc 100644 --- a/src/Simulator/NoopRedstoneSimulator.h +++ b/src/Simulator/NoopRedstoneSimulator.h @@ -39,7 +39,7 @@ public: virtual cRedstoneSimulatorChunkData * CreateChunkData() override { - return NULL; + return nullptr; } } ; diff --git a/src/Simulator/SandSimulator.cpp b/src/Simulator/SandSimulator.cpp index aad41e463..dfbd3e458 100644 --- a/src/Simulator/SandSimulator.cpp +++ b/src/Simulator/SandSimulator.cpp @@ -7,7 +7,7 @@ #include "../Defines.h" #include "../Entities/FallingBlock.h" #include "../Chunk.h" -#include "inifile/iniFile.h" +#include "../IniFile.h" @@ -94,7 +94,7 @@ bool cSandSimulator::IsAllowedBlock(BLOCKTYPE a_BlockType) void cSandSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if ((a_Chunk == NULL) || !a_Chunk->IsValid()) + if ((a_Chunk == nullptr) || !a_Chunk->IsValid()) { return; } diff --git a/src/Simulator/VaporizeFluidSimulator.cpp b/src/Simulator/VaporizeFluidSimulator.cpp index 484cac334..119742346 100644 --- a/src/Simulator/VaporizeFluidSimulator.cpp +++ b/src/Simulator/VaporizeFluidSimulator.cpp @@ -22,7 +22,7 @@ cVaporizeFluidSimulator::cVaporizeFluidSimulator(cWorld & a_World, BLOCKTYPE a_F void cVaporizeFluidSimulator::AddBlock(int a_BlockX, int a_BlockY, int a_BlockZ, cChunk * a_Chunk) { - if (a_Chunk == NULL) + if (a_Chunk == nullptr) { return; } diff --git a/src/StackWalker.h b/src/StackWalker.h index bf47d3726..a609f6840 100644 --- a/src/StackWalker.h +++ b/src/StackWalker.h @@ -88,7 +88,7 @@ public: StackWalker( int options = OptionsAll, // 'int' is by design, to combine the enum-flags - LPCSTR szSymPath = NULL, + LPCSTR szSymPath = nullptr, DWORD dwProcessId = GetCurrentProcessId(), HANDLE hProcess = GetCurrentProcess() ); @@ -108,9 +108,9 @@ public: BOOL ShowCallstack( HANDLE hThread = GetCurrentThread(), - const CONTEXT *context = NULL, - PReadProcessMemoryRoutine readMemoryFunction = NULL, - LPVOID pUserData = NULL // optional to identify some data in the 'readMemoryFunction'-callback + const CONTEXT *context = nullptr, + PReadProcessMemoryRoutine readMemoryFunction = nullptr, + LPVOID pUserData = nullptr // optional to identify some data in the 'readMemoryFunction'-callback ); #if _MSC_VER >= 1300 @@ -180,11 +180,11 @@ protected: #define GET_CURRENT_CONTEXT(c, contextFlags) \ do { \ memset(&c, 0, sizeof(CONTEXT)); \ - EXCEPTION_POINTERS *pExp = NULL; \ + EXCEPTION_POINTERS *pExp = nullptr; \ __try { \ throw 0; \ } __except( ( (pExp = GetExceptionInformation()) ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_EXECUTE_HANDLER)) {} \ - if (pExp != NULL) \ + if (pExp != nullptr) \ memcpy(&c, pExp->ContextRecord, sizeof(CONTEXT)); \ c.ContextFlags = contextFlags; \ } while(0); diff --git a/src/StringUtils.cpp b/src/StringUtils.cpp index 21962f832..34f2da682 100644 --- a/src/StringUtils.cpp +++ b/src/StringUtils.cpp @@ -20,7 +20,7 @@ AString & AppendVPrintf(AString & str, const char * format, va_list args) { - ASSERT(format != NULL); + ASSERT(format != nullptr); char buffer[2048]; size_t len; @@ -562,7 +562,7 @@ AString & CreateHexDump(AString & a_Out, const void * a_Data, size_t a_Size, siz #else int Count = sprintf(line, "%08x:", (unsigned)i); #endif - // Remove the terminating NULL / leftover garbage in line, after the sprintf-ed value + // Remove the terminating nullptr / leftover garbage in line, after the sprintf-ed value memset(line + Count, 32, sizeof(line) - Count); p = line + 10; q = p + 2 + a_BytesPerLine * 3 + 1; diff --git a/src/UI/SlotArea.cpp b/src/UI/SlotArea.cpp index 999bed989..9113ec343 100644 --- a/src/UI/SlotArea.cpp +++ b/src/UI/SlotArea.cpp @@ -48,9 +48,9 @@ void cSlotArea::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickA ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -714,7 +714,7 @@ void cSlotAreaCrafting::UpdateRecipe(cPlayer & a_Player) { cCraftingGrid Grid(GetPlayerSlots(a_Player) + 1, m_GridSize, m_GridSize); cCraftingRecipe & Recipe = GetRecipeForPlayer(a_Player); - cRoot::Get()->GetCraftingRecipes()->GetRecipe(&a_Player, Grid, Recipe); + cRoot::Get()->GetCraftingRecipes()->GetRecipe(a_Player, Grid, Recipe); SetSlot(0, a_Player, Recipe.GetResult()); m_ParentWindow.SendSlot(a_Player, this, 0); } @@ -736,7 +736,7 @@ cCraftingRecipe & cSlotAreaCrafting::GetRecipeForPlayer(cPlayer & a_Player) // Not found. Add a new one: cCraftingGrid Grid(GetPlayerSlots(a_Player) + 1, m_GridSize, m_GridSize); cCraftingRecipe Recipe(Grid); - cRoot::Get()->GetCraftingRecipes()->GetRecipe(&a_Player, Grid, Recipe); + cRoot::Get()->GetCraftingRecipes()->GetRecipe(a_Player, Grid, Recipe); m_Recipes.push_back(std::make_pair(a_Player.GetUniqueID(), Recipe)); return m_Recipes.back().second; } @@ -791,9 +791,9 @@ void cSlotAreaAnvil::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_C } bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -980,7 +980,7 @@ void cSlotAreaAnvil::OnTakeResult(cPlayer & a_Player) m_ParentWindow.SetProperty(0, m_MaximumCost, a_Player); m_MaximumCost = 0; - ((cAnvilWindow*)&m_ParentWindow)->SetRepairedItemName("", NULL); + ((cAnvilWindow*)&m_ParentWindow)->SetRepairedItemName("", nullptr); int PosX, PosY, PosZ; ((cAnvilWindow*)&m_ParentWindow)->GetBlockPos(PosX, PosY, PosZ); @@ -1238,9 +1238,9 @@ void cSlotAreaBeacon::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -1408,9 +1408,9 @@ void cSlotAreaEnchanting::Clicked(cPlayer & a_Player, int a_SlotNum, eClickActio ASSERT((a_SlotNum >= 0) && (a_SlotNum < GetNumSlots())); bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -1709,19 +1709,19 @@ cSlotAreaFurnace::~cSlotAreaFurnace() void cSlotAreaFurnace::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_ClickAction, const cItem & a_ClickedItem) { - if (m_Furnace == NULL) + if (m_Furnace == nullptr) { - LOGERROR("cSlotAreaFurnace::Clicked(): m_Furnace == NULL"); - ASSERT(!"cSlotAreaFurnace::Clicked(): m_Furnace == NULL"); + LOGERROR("cSlotAreaFurnace::Clicked(): m_Furnace == nullptr"); + ASSERT(!"cSlotAreaFurnace::Clicked(): m_Furnace == nullptr"); return; } if (a_SlotNum == 2) { bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -2071,9 +2071,9 @@ void cSlotAreaArmor::Clicked(cPlayer & a_Player, int a_SlotNum, eClickAction a_C } bool bAsync = false; - if (GetSlot(a_SlotNum, a_Player) == NULL) + if (GetSlot(a_SlotNum, a_Player) == nullptr) { - LOGWARNING("GetSlot(%d) returned NULL! Ignoring click", a_SlotNum); + LOGWARNING("GetSlot(%d) returned nullptr! Ignoring click", a_SlotNum); return; } @@ -2223,15 +2223,15 @@ const cItem * cSlotAreaTemporary::GetSlot(int a_SlotNum, cPlayer & a_Player) con LOGERROR("cSlotAreaTemporary: player \"%s\" not found for slot %d!", a_Player.GetName().c_str(), a_SlotNum); ASSERT(!"cSlotAreaTemporary: player not found!"); - // Player not found, this should not happen, ever! Return NULL, but things may break by this. - return NULL; + // Player not found, this should not happen, ever! Return nullptr, but things may break by this. + return nullptr; } if (a_SlotNum >= (int)(itr->second.size())) { LOGERROR("cSlotAreaTemporary: asking for more slots than actually stored!"); ASSERT(!"cSlotAreaTemporary: asking for more slots than actually stored!"); - return NULL; + return nullptr; } return &(itr->second[a_SlotNum]); @@ -2320,7 +2320,7 @@ cItem * cSlotAreaTemporary::GetPlayerSlots(cPlayer & a_Player) cItemMap::iterator itr = m_Items.find(a_Player.GetUniqueID()); if (itr == m_Items.end()) { - return NULL; + return nullptr; } return &(itr->second[0]); } diff --git a/src/UI/Window.cpp b/src/UI/Window.cpp index d83336f75..1598dd3e7 100644 --- a/src/UI/Window.cpp +++ b/src/UI/Window.cpp @@ -33,7 +33,7 @@ cWindow::cWindow(WindowType a_WindowType, const AString & a_WindowTitle) : m_WindowTitle(a_WindowTitle), m_IsDestroyed(false), m_ShouldDistributeToHotbarFirst(true), - m_Owner(NULL) + m_Owner(nullptr) { if (a_WindowType == wtInventory) { @@ -105,10 +105,10 @@ const cItem * cWindow::GetSlot(cPlayer & a_Player, int a_SlotNum) const // Return the item at the specified slot for the specified player int LocalSlotNum = 0; const cSlotArea * Area = GetSlotArea(a_SlotNum, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { - LOGWARNING("%s: requesting item from an invalid SlotArea (SlotNum %d), returning NULL.", __FUNCTION__, a_SlotNum); - return NULL; + LOGWARNING("%s: requesting item from an invalid SlotArea (SlotNum %d), returning nullptr.", __FUNCTION__, a_SlotNum); + return nullptr; } return Area->GetSlot(LocalSlotNum, a_Player); } @@ -122,7 +122,7 @@ void cWindow::SetSlot(cPlayer & a_Player, int a_SlotNum, const cItem & a_Item) // Set the item to the specified slot for the specified player int LocalSlotNum = 0; cSlotArea * Area = GetSlotArea(a_SlotNum, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { LOGWARNING("%s: requesting write to an invalid SlotArea (SlotNum %d), ignoring.", __FUNCTION__, a_SlotNum); return; @@ -177,7 +177,7 @@ void cWindow::GetSlots(cPlayer & a_Player, cItems & a_Slots) const for (int i = 0; i < NumSlots; i++) { const cItem * Item = (*itr)->GetSlot(i, a_Player); - if (Item == NULL) + if (Item == nullptr) { a_Slots.push_back(cItem()); } @@ -311,7 +311,7 @@ bool cWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) } cClientHandle * ClientHandle = a_Player.GetClientHandle(); - if (ClientHandle != NULL) + if (ClientHandle != nullptr) { ClientHandle->SendWindowClose(*this); } @@ -345,7 +345,7 @@ bool cWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) void cWindow::OwnerDestroyed() { - m_Owner = NULL; + m_Owner = nullptr; // Close window for each player. Note that the last one needs special handling while (m_OpenedBy.size() > 1) { @@ -511,10 +511,10 @@ void cWindow::SendSlot(cPlayer & a_Player, cSlotArea * a_SlotArea, int a_Relativ void cWindow::Destroy(void) { - if (m_Owner != NULL) + if (m_Owner != nullptr) { m_Owner->CloseWindow(); - m_Owner = NULL; + m_Owner = nullptr; } m_IsDestroyed = true; } @@ -529,7 +529,7 @@ cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) { LOGWARNING("%s: requesting an invalid SlotNum: %d out of %d slots", __FUNCTION__, a_GlobalSlotNum, GetNumSlots() - 1); ASSERT(!"Invalid SlotNum"); - return NULL; + return nullptr; } // Iterate through all the SlotAreas, find the correct one @@ -547,7 +547,7 @@ cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) // We shouldn't be here - the check at the beginnning should prevent this. Log and assert LOGWARNING("%s: GetNumSlots() is out of sync: %d; LocalSlotNum = %d", __FUNCTION__, GetNumSlots(), LocalSlotNum); ASSERT(!"Invalid GetNumSlots"); - return NULL; + return nullptr; } @@ -560,7 +560,7 @@ const cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum { LOGWARNING("%s: requesting an invalid SlotNum: %d out of %d slots", __FUNCTION__, a_GlobalSlotNum, GetNumSlots() - 1); ASSERT(!"Invalid SlotNum"); - return NULL; + return nullptr; } // Iterate through all the SlotAreas, find the correct one @@ -578,7 +578,7 @@ const cSlotArea * cWindow::GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum // We shouldn't be here - the check at the beginnning should prevent this. Log and assert LOGWARNING("%s: GetNumSlots() is out of sync: %d; LocalSlotNum = %d", __FUNCTION__, GetNumSlots(), LocalSlotNum); ASSERT(!"Invalid GetNumSlots"); - return NULL; + return nullptr; } @@ -669,7 +669,7 @@ int cWindow::DistributeItemToSlots(cPlayer & a_Player, const cItem & a_Item, int { int LocalSlotNum = 0; cSlotArea * Area = GetSlotArea(*itr, LocalSlotNum); - if (Area == NULL) + if (Area == nullptr) { LOGWARNING("%s: Bad SlotArea for slot %d", __FUNCTION__, *itr); continue; @@ -758,20 +758,7 @@ void cWindow::BroadcastWholeWindow(void) -void cWindow::BroadcastProgress(int a_Progressbar, int a_Value) -{ - cCSLock Lock(m_CS); - for (cPlayerList::iterator itr = m_OpenedBy.begin(); itr != m_OpenedBy.end(); ++itr) - { - (*itr)->GetClientHandle()->SendWindowProperty(*this, a_Progressbar, a_Value); - } // for itr - m_OpenedBy[] -} - - - - - -void cWindow::SetProperty(int a_Property, int a_Value) +void cWindow::SetProperty(short a_Property, short a_Value) { cCSLock Lock(m_CS); for (cPlayerList::iterator itr = m_OpenedBy.begin(), end = m_OpenedBy.end(); itr != end; ++itr) @@ -784,7 +771,7 @@ void cWindow::SetProperty(int a_Property, int a_Value) -void cWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Player) +void cWindow::SetProperty(short a_Property, short a_Value, cPlayer & a_Player) { a_Player.GetClientHandle()->SendWindowProperty(*this, a_Property, a_Value); } @@ -849,7 +836,7 @@ void cAnvilWindow::SetRepairedItemName(const AString & a_Name, cPlayer * a_Playe { m_RepairedItemName = a_Name; - if (a_Player != NULL) + if (a_Player != nullptr) { m_AnvilSlotArea->UpdateResult(*a_Player); } @@ -919,7 +906,7 @@ cEnchantingWindow::cEnchantingWindow(int a_BlockX, int a_BlockY, int a_BlockZ) : -void cEnchantingWindow::SetProperty(int a_Property, int a_Value) +void cEnchantingWindow::SetProperty(short a_Property, short a_Value) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { @@ -935,7 +922,7 @@ void cEnchantingWindow::SetProperty(int a_Property, int a_Value) -void cEnchantingWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Player) +void cEnchantingWindow::SetProperty(short a_Property, short a_Value, cPlayer & a_Player) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { @@ -951,7 +938,7 @@ void cEnchantingWindow::SetProperty(int a_Property, int a_Value, cPlayer & a_Pla -int cEnchantingWindow::GetPropertyValue(int a_Property) +short cEnchantingWindow::GetPropertyValue(short a_Property) { if ((a_Property < 0) || ((size_t)a_Property >= ARRAYCOUNT(m_PropertyValue))) { @@ -976,7 +963,7 @@ cChestWindow::cChestWindow(cChestEntity * a_Chest) : m_BlockY(a_Chest->GetPosY()), m_BlockZ(a_Chest->GetPosZ()), m_PrimaryChest(a_Chest), - m_SecondaryChest(NULL) + m_SecondaryChest(nullptr) { m_SlotAreas.push_back(new cSlotAreaChest(a_Chest, *this)); m_SlotAreas.push_back(new cSlotAreaInventory(*this)); @@ -1027,7 +1014,7 @@ void cChestWindow::OpenedByPlayer(cPlayer & a_Player) cChunkDef::BlockToChunk(m_PrimaryChest->GetPosX(), m_PrimaryChest->GetPosZ(), ChunkX, ChunkZ); m_PrimaryChest->GetWorld()->MarkRedstoneDirty(ChunkX, ChunkZ); - if (m_SecondaryChest != NULL) + if (m_SecondaryChest != nullptr) { m_SecondaryChest->SetNumberOfPlayers(m_SecondaryChest->GetNumberOfPlayers() + 1); cChunkDef::BlockToChunk(m_SecondaryChest->GetPosX(), m_SecondaryChest->GetPosZ(), ChunkX, ChunkZ); @@ -1049,7 +1036,7 @@ bool cChestWindow::ClosedByPlayer(cPlayer & a_Player, bool a_CanRefuse) cChunkDef::BlockToChunk(m_PrimaryChest->GetPosX(), m_PrimaryChest->GetPosZ(), ChunkX, ChunkZ); m_PrimaryChest->GetWorld()->MarkRedstoneDirty(ChunkX, ChunkZ); - if (m_SecondaryChest != NULL) + if (m_SecondaryChest != nullptr) { m_SecondaryChest->SetNumberOfPlayers(m_SecondaryChest->GetNumberOfPlayers() - 1); cChunkDef::BlockToChunk(m_SecondaryChest->GetPosX(), m_SecondaryChest->GetPosZ(), ChunkX, ChunkZ); diff --git a/src/UI/Window.h b/src/UI/Window.h index 6b6dce346..e62176d50 100644 --- a/src/UI/Window.h +++ b/src/UI/Window.h @@ -90,7 +90,7 @@ public: // tolua_begin - /// Returns the item at the specified slot for the specified player. Returns NULL if invalid SlotNum requested + /// Returns the item at the specified slot for the specified player. Returns nullptr if invalid SlotNum requested const cItem * GetSlot(cPlayer & a_Player, int a_SlotNum) const; /// Sets the item to the specified slot for the specified player @@ -130,9 +130,6 @@ public: /// Sends the contents of the whole window to all clients of this window. void BroadcastWholeWindow(void); - - /// Sends the progressbar to all clients of this window (same as SetProperty) - void BroadcastProgress(int a_Progressbar, int a_Value); // tolua_begin @@ -140,10 +137,10 @@ public: void SetWindowTitle(const AString & a_WindowTitle) { m_WindowTitle = a_WindowTitle; } /// Sends the UpdateWindowProperty (0x69) packet to all clients of the window - virtual void SetProperty(int a_Property, int a_Value); + virtual void SetProperty(short a_Property, short a_Value); /// Sends the UpdateWindowPropert(0x69) packet to the specified player - virtual void SetProperty(int a_Property, int a_Value, cPlayer & a_Player); + virtual void SetProperty(short a_Property, short a_Value, cPlayer & a_Player); // tolua_end @@ -192,13 +189,13 @@ protected: /** Returns the correct slot area for the specified window-global SlotNum Also returns the area-local SlotNum corresponding to the GlobalSlotNum - If the global SlotNum is out of range, returns NULL + If the global SlotNum is out of range, returns nullptr */ cSlotArea * GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum); /** Returns the correct slot area for the specified window-global SlotNum Also returns the area-local SlotNum corresponding to the GlobalSlotNum - If the global SlotNum is out of range, returns NULL. + If the global SlotNum is out of range, returns nullptr. Const version. */ const cSlotArea * GetSlotArea(int a_GlobalSlotNum, int & a_LocalSlotNum) const; @@ -287,16 +284,16 @@ class cEnchantingWindow : typedef cWindow super; public: cEnchantingWindow(int a_BlockX, int a_BlockY, int a_BlockZ); - virtual void SetProperty(int a_Property, int a_Value, cPlayer & a_Player) override; - virtual void SetProperty(int a_Property, int a_Value) override; + virtual void SetProperty(short a_Property, short a_Value, cPlayer & a_Player) override; + virtual void SetProperty(short a_Property, short a_Value) override; /** Return the Value of a Property */ - int GetPropertyValue(int a_Property); + short GetPropertyValue(short a_Property); cSlotArea * m_SlotArea; protected: - int m_PropertyValue[3]; + short m_PropertyValue[3]; int m_BlockX, m_BlockY, m_BlockZ; }; diff --git a/src/UI/WindowOwner.h b/src/UI/WindowOwner.h index 6845a161b..4dc3cf080 100644 --- a/src/UI/WindowOwner.h +++ b/src/UI/WindowOwner.h @@ -22,7 +22,7 @@ class cWindowOwner { public: cWindowOwner() : - m_Window(NULL) + m_Window(nullptr) { } @@ -32,7 +32,7 @@ public: void CloseWindow(void) { - m_Window = NULL; + m_Window = nullptr; } void OpenWindow(cWindow * a_Window) diff --git a/src/WebAdmin.cpp b/src/WebAdmin.cpp index db2ace386..dbf600c25 100644 --- a/src/WebAdmin.cpp +++ b/src/WebAdmin.cpp @@ -224,7 +224,7 @@ void cWebAdmin::HandleWebadminRequest(cHTTPConnection & a_Connection, cHTTPReque // Retrieve the request data: cWebadminRequestData * Data = (cWebadminRequestData *)(a_Request.GetUserData()); - if (Data == NULL) + if (Data == nullptr) { a_Connection.SendStatusAndReason(500, "Bad UserData"); return; @@ -483,7 +483,7 @@ AString cWebAdmin::GetDefaultPage(void) const cPluginManager::PluginMap & List = PM->GetAllPlugins(); for (cPluginManager::PluginMap::const_iterator itr = List.begin(); itr != List.end(); ++itr) { - if (itr->second == NULL) + if (itr->second == nullptr) { continue; } @@ -494,7 +494,7 @@ AString cWebAdmin::GetDefaultPage(void) cPlayerAccum PlayerAccum; cWorld * World = cRoot::Get()->GetDefaultWorld(); // TODO - Create a list of worlds and players - if (World != NULL) + if (World != nullptr) { World->ForEachPlayer(PlayerAccum); Content.append(PlayerAccum.m_Contents); @@ -625,7 +625,7 @@ void cWebAdmin::OnRequestBody(cHTTPConnection & a_Connection, cHTTPRequest & a_R { UNUSED(a_Connection); cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); - if (Data == NULL) + if (Data == nullptr) { return; } @@ -659,7 +659,7 @@ void cWebAdmin::OnRequestFinished(cHTTPConnection & a_Connection, cHTTPRequest & // Delete any request data assigned to the request: cRequestData * Data = (cRequestData *)(a_Request.GetUserData()); delete Data; - Data = NULL; + Data = nullptr; } diff --git a/src/WebAdmin.h b/src/WebAdmin.h index 94b95dbcf..a85fb1f0c 100644 --- a/src/WebAdmin.h +++ b/src/WebAdmin.h @@ -7,7 +7,7 @@ #include "OSSupport/Socket.h" #include "Bindings/LuaState.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "HTTPServer/HTTPServer.h" #include "HTTPServer/HTTPFormParser.h" diff --git a/src/World.cpp b/src/World.cpp index a3c804b44..2e079d447 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -8,7 +8,7 @@ #include "Server.h" #include "Item.h" #include "Root.h" -#include "inifile/iniFile.h" +#include "IniFile.h" #include "ChunkMap.h" #include "Generating/ChunkDesc.h" #include "OSSupport/Timer.h" @@ -256,14 +256,14 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin m_IsDeepSnowEnabled(false), m_ShouldLavaSpawnFire(true), m_VillagersShouldHarvestCrops(true), - m_SimulatorManager(NULL), - m_SandSimulator(NULL), - m_WaterSimulator(NULL), - m_LavaSimulator(NULL), - m_FireSimulator(NULL), - m_RedstoneSimulator(NULL), + m_SimulatorManager(), + m_SandSimulator(), + m_WaterSimulator(nullptr), + m_LavaSimulator(nullptr), + m_FireSimulator(), + m_RedstoneSimulator(nullptr), m_MaxPlayers(10), - m_ChunkMap(NULL), + m_ChunkMap(), m_bAnimals(true), m_Weather(eWeather_Sunny), m_WeatherInterval(24000), // Guaranteed 1 day of sunshine at server start :) @@ -303,12 +303,9 @@ cWorld::cWorld(const AString & a_WorldName, eDimension a_Dimension, const AStrin cWorld::~cWorld() { - delete m_SimulatorManager; m_SimulatorManager = NULL; - delete m_SandSimulator; m_SandSimulator = NULL; - delete m_WaterSimulator; m_WaterSimulator = NULL; - delete m_LavaSimulator; m_LavaSimulator = NULL; - delete m_FireSimulator; m_FireSimulator = NULL; - delete m_RedstoneSimulator; m_RedstoneSimulator = NULL; + delete m_WaterSimulator; m_WaterSimulator = nullptr; + delete m_LavaSimulator; m_LavaSimulator = nullptr; + delete m_RedstoneSimulator; m_RedstoneSimulator = nullptr; UnloadUnusedChunks(); @@ -319,8 +316,6 @@ cWorld::~cWorld() Serializer.Save(); m_MapManager.SaveMapData(); - - delete m_ChunkMap; } @@ -631,7 +626,7 @@ void cWorld::Start(void) InitialiseAndLoadMobSpawningValues(IniFile); SetTimeOfDay(IniFile.GetValueSetI("General", "TimeInTicks", m_TimeOfDay)); - m_ChunkMap = new cChunkMap(this); + m_ChunkMap = make_unique<cChunkMap>(this); m_LastSave = 0; m_LastUnload = 0; @@ -641,16 +636,16 @@ void cWorld::Start(void) m_BlockTickQueueCopy.reserve(1000); // Simulators: - m_SimulatorManager = new cSimulatorManager(*this); + m_SimulatorManager = make_unique<cSimulatorManager>(*this); m_WaterSimulator = InitializeFluidSimulator(IniFile, "Water", E_BLOCK_WATER, E_BLOCK_STATIONARY_WATER); m_LavaSimulator = InitializeFluidSimulator(IniFile, "Lava", E_BLOCK_LAVA, E_BLOCK_STATIONARY_LAVA); - m_SandSimulator = new cSandSimulator(*this, IniFile); - m_FireSimulator = new cFireSimulator(*this, IniFile); + m_SandSimulator = make_unique<cSandSimulator>(*this, IniFile); + m_FireSimulator = make_unique<cFireSimulator>(*this, IniFile); m_RedstoneSimulator = InitializeRedstoneSimulator(IniFile); // Water, Lava and Redstone simulators get registered in their initialize function. - m_SimulatorManager->RegisterSimulator(m_SandSimulator, 1); - m_SimulatorManager->RegisterSimulator(m_FireSimulator, 1); + m_SimulatorManager->RegisterSimulator(m_SandSimulator.get(), 1); + m_SimulatorManager->RegisterSimulator(m_FireSimulator.get(), 1); m_Lighting.Start(this); m_Storage.Start(this, m_StorageSchema, m_StorageCompressionFactor); @@ -1059,7 +1054,6 @@ void cWorld::TickQueuedTasks(void) for (cTasks::iterator itr = Tasks.begin(), end = Tasks.end(); itr != end; ++itr) { (*itr)->Run(*this); - delete *itr; } // for itr - m_Tasks[] } @@ -1069,14 +1063,28 @@ void cWorld::TickQueuedTasks(void) void cWorld::TickScheduledTasks(void) { - // Make a copy of the tasks to avoid deadlocks on accessing m_Tasks + // Move the tasks to be executed to a seperate vector to avoid deadlocks on accessing m_Tasks cScheduledTasks Tasks; { cCSLock Lock(m_CSScheduledTasks); - while (!m_ScheduledTasks.empty() && (m_ScheduledTasks.front()->m_TargetTick < m_WorldAge)) + auto WorldAge = m_WorldAge; + + // Move all the due tasks from m_ScheduledTasks into Tasks: + for (auto itr = m_ScheduledTasks.begin(); itr != m_ScheduledTasks.end();) // Cannot use range-basd for, we're modifying the container { - Tasks.push_back(m_ScheduledTasks.front()); - m_ScheduledTasks.pop_front(); + if ((*itr)->m_TargetTick < WorldAge) + { + auto next = itr; + ++next; + Tasks.push_back(std::move(*itr)); + m_ScheduledTasks.erase(itr); + itr = next; + } + else + { + // All the eligible tasks have been moved, bail out now + break; + } } } @@ -1084,7 +1092,6 @@ void cWorld::TickScheduledTasks(void) for (cScheduledTasks::iterator itr = Tasks.begin(), end = Tasks.end(); itr != end; ++itr) { (*itr)->m_Task->Run(*this); - delete *itr; } // for itr - m_Tasks[] } @@ -1254,7 +1261,7 @@ void cWorld::DoExplosionAt(double a_ExplosionSize, double a_BlockX, double a_Blo for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if (ch == NULL) + if (ch == nullptr) { continue; } @@ -2009,7 +2016,7 @@ void cWorld::BroadcastChat(const AString & a_Message, const cClientHandle * a_Ex for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2027,7 +2034,7 @@ void cWorld::BroadcastChat(const cCompositeChat & a_Message, const cClientHandle for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2170,7 +2177,7 @@ void cWorld::BroadcastPlayerListAddPlayer(const cPlayer & a_Player, const cClien for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2188,7 +2195,7 @@ void cWorld::BroadcastPlayerListRemovePlayer(const cPlayer & a_Player, const cCl for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2206,7 +2213,7 @@ void cWorld::BroadcastPlayerListUpdateGameMode(const cPlayer & a_Player, const c for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2224,7 +2231,7 @@ void cWorld::BroadcastPlayerListUpdatePing(const cPlayer & a_Player, const cClie for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2242,7 +2249,7 @@ void cWorld::BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, cons for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2269,7 +2276,7 @@ void cWorld::BroadcastScoreboardObjective(const AString & a_Name, const AString for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2287,7 +2294,7 @@ void cWorld::BroadcastScoreUpdate(const AString & a_Objective, const AString & a for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2305,7 +2312,7 @@ void cWorld::BroadcastDisplayObjective(const AString & a_Objective, cScoreboard: for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2350,7 +2357,7 @@ void cWorld::BroadcastTeleportEntity(const cEntity & a_Entity, const cClientHand for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2377,7 +2384,7 @@ void cWorld::BroadcastTimeUpdate(const cClientHandle * a_Exclude) for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2404,7 +2411,7 @@ void cWorld::BroadcastWeather(eWeather a_Weather, const cClientHandle * a_Exclud for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch == a_Exclude) || (ch == NULL) || !ch->IsLoggedIn() || ch->IsDestroyed()) + if ((ch == a_Exclude) || (ch == nullptr) || !ch->IsLoggedIn() || ch->IsDestroyed()) { continue; } @@ -2593,14 +2600,14 @@ void cWorld::UnloadUnusedChunks(void) void cWorld::QueueUnloadUnusedChunks(void) { - QueueTask(new cWorld::cTaskUnloadUnusedChunks); + QueueTask(make_unique<cWorld::cTaskUnloadUnusedChunks>()); } -void cWorld::CollectPickupsByPlayer(cPlayer * a_Player) +void cWorld::CollectPickupsByPlayer(cPlayer & a_Player) { m_ChunkMap->CollectPickupsByPlayer(a_Player); } @@ -2639,7 +2646,7 @@ void cWorld::RemovePlayer(cPlayer * a_Player, bool a_RemoveFromChunk) // Remove the player's client from the list of clients to be ticked: cClientHandle * Client = a_Player->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { Client->RemoveFromWorld(); m_ChunkMap->RemoveClientFromChunks(Client); @@ -2692,7 +2699,7 @@ bool cWorld::DoWithPlayer(const AString & a_PlayerName, cPlayerListCallback & a_ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCallback & a_Callback) { - cPlayer * BestMatch = NULL; + cPlayer * BestMatch = nullptr; size_t BestRating = 0; size_t NameLength = a_PlayerNameHint.length(); @@ -2711,7 +2718,7 @@ bool cWorld::FindAndDoWithPlayer(const AString & a_PlayerNameHint, cPlayerListCa } } // for itr - m_Players[] - if (BestMatch != NULL) + if (BestMatch != nullptr) { return a_Callback.Item (BestMatch); } @@ -2728,7 +2735,7 @@ cPlayer * cWorld::FindClosestPlayer(const Vector3d & a_Pos, float a_SightLimit, cTracer LineOfSight(this); double ClosestDistance = a_SightLimit; - cPlayer * ClosestPlayer = NULL; + cPlayer * ClosestPlayer = nullptr; cCSLock Lock(m_CSPlayers); for (cPlayerList::const_iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) @@ -2767,7 +2774,7 @@ void cWorld::SendPlayerList(cPlayer * a_DestPlayer) for (cPlayerList::iterator itr = m_Players.begin(); itr != m_Players.end(); ++itr) { cClientHandle * ch = (*itr)->GetClientHandle(); - if ((ch != NULL) && !ch->IsDestroyed()) + if ((ch != nullptr) && !ch->IsDestroyed()) { a_DestPlayer->GetClientHandle()->SendPlayerListAddPlayer(*(*itr)); } @@ -2850,19 +2857,19 @@ void cWorld::RemoveClientFromChunks(cClientHandle * a_Client) -void cWorld::SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cWorld::SendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client) { - m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Client); + m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client); } -void cWorld::ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client) +void cWorld::ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client) { a_Client->AddWantedChunk(a_ChunkX, a_ChunkZ); - m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Client); + m_ChunkSender.QueueSendChunkTo(a_ChunkX, a_ChunkZ, a_Priority, a_Client); } @@ -2902,13 +2909,13 @@ bool cWorld::SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AStrin AString Line2(a_Line2); AString Line3(a_Line3); AString Line4(a_Line4); - if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player)) + if (cRoot::Get()->GetPluginManager()->CallHookUpdatingSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player)) { return false; } if (m_ChunkMap->SetSignLines(a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4)) { - cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player); + cRoot::Get()->GetPluginManager()->CallHookUpdatedSign(*this, a_BlockX, a_BlockY, a_BlockZ, Line1, Line2, Line3, Line4, a_Player); return true; } return false; @@ -3049,17 +3056,17 @@ void cWorld::SaveAllChunks(void) void cWorld::QueueSaveAllChunks(void) { - QueueTask(new cWorld::cTaskSaveAllChunks); + QueueTask(make_unique<cWorld::cTaskSaveAllChunks>()); } -void cWorld::QueueTask(cTask * a_Task) +void cWorld::QueueTask(std::unique_ptr<cTask> a_Task) { cCSLock Lock(m_CSTasks); - m_Tasks.push_back(a_Task); + m_Tasks.push_back(std::move(a_Task)); } @@ -3076,11 +3083,11 @@ void cWorld::ScheduleTask(int a_DelayTicks, cTask * a_Task) { if ((*itr)->m_TargetTick >= TargetTick) { - m_ScheduledTasks.insert(itr, new cScheduledTask(TargetTick, a_Task)); + m_ScheduledTasks.insert(itr, make_unique<cScheduledTask>(TargetTick, a_Task)); return; } } - m_ScheduledTasks.push_back(new cScheduledTask(TargetTick, a_Task)); + m_ScheduledTasks.push_back(make_unique<cScheduledTask>(TargetTick, a_Task)); } @@ -3211,10 +3218,10 @@ bool cWorld::IsBlockDirectlyWatered(int a_BlockX, int a_BlockY, int a_BlockZ) int cWorld::SpawnMob(double a_PosX, double a_PosY, double a_PosZ, eMonsterType a_MonsterType) { - cMonster * Monster = NULL; + cMonster * Monster = nullptr; Monster = cMonster::NewMonsterFromType(a_MonsterType); - if (Monster != NULL) + if (Monster != nullptr) { Monster->SetPosition(a_PosX, a_PosY, a_PosZ); } @@ -3240,7 +3247,7 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) if (cPluginManager::Get()->CallHookSpawningMonster(*this, *a_Monster)) { delete a_Monster; - a_Monster = NULL; + a_Monster = nullptr; return -1; } @@ -3248,7 +3255,7 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) if (!a_Monster->Initialize(*this)) { delete a_Monster; - a_Monster = NULL; + a_Monster = nullptr; return -1; } @@ -3265,14 +3272,14 @@ int cWorld::SpawnMobFinalize(cMonster * a_Monster) int cWorld::CreateProjectile(double a_PosX, double a_PosY, double a_PosZ, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem * a_Item, const Vector3d * a_Speed) { cProjectileEntity * Projectile = cProjectileEntity::Create(a_Kind, a_Creator, a_PosX, a_PosY, a_PosZ, a_Item, a_Speed); - if (Projectile == NULL) + if (Projectile == nullptr) { return -1; } if (!Projectile->Initialize(*this)) { delete Projectile; - Projectile = NULL; + Projectile = nullptr; return -1; } return Projectile->GetUniqueID(); @@ -3355,7 +3362,7 @@ cRedstoneSimulator<cChunk, cWorld> * cWorld::InitializeRedstoneSimulator(cIniFil SimulatorName = "Incremental"; } - cRedstoneSimulator<cChunk, cWorld> * res = NULL; + cRedstoneSimulator<cChunk, cWorld> * res = nullptr; if (NoCaseCompare(SimulatorName, "Incremental") == 0) { @@ -3388,7 +3395,7 @@ cFluidSimulator * cWorld::InitializeFluidSimulator(cIniFile & a_IniFile, const c SimulatorName = "Vanilla"; } - cFluidSimulator * res = NULL; + cFluidSimulator * res = nullptr; bool IsWater = (strcmp(a_FluidName, "Water") == 0); // Used for defaults int Rate = 1; if ( @@ -3478,7 +3485,7 @@ void cWorld::AddQueuedPlayers(void) for (cPlayerList::iterator itr = PlayersToAdd.begin(), end = PlayersToAdd.end(); itr != end; ++itr) { cClientHandle * Client = (*itr)->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { m_Clients.push_back(Client); } @@ -3489,9 +3496,8 @@ void cWorld::AddQueuedPlayers(void) for (cPlayerList::iterator itr = PlayersToAdd.begin(), end = PlayersToAdd.end(); itr != end; ++itr) { cClientHandle * Client = (*itr)->GetClientHandle(); - if (Client != NULL) + if (Client != nullptr) { - Client->StreamChunks(); Client->SendPlayerMoveLook(); Client->SendHealth(); Client->SendWholeInventory(*(*itr)->GetWindow()); @@ -3590,7 +3596,7 @@ void cWorld::cChunkGeneratorCallbacks::OnChunkGenerated(cChunkDesc & a_ChunkDesc cSetChunkDataPtr SetChunkData(new cSetChunkData( a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), a_ChunkDesc.GetBlockTypes(), BlockMetas, - NULL, NULL, // We don't have lighting, chunk will be lighted when needed + nullptr, nullptr, // We don't have lighting, chunk will be lighted when needed &a_ChunkDesc.GetHeightMap(), &a_ChunkDesc.GetBiomeMap(), a_ChunkDesc.GetEntities(), a_ChunkDesc.GetBlockEntities(), true @@ -3633,7 +3639,7 @@ bool cWorld::cChunkGeneratorCallbacks::HasChunkAnyClients(int a_ChunkX, int a_Ch void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerating(cChunkDesc & a_ChunkDesc) { cPluginManager::Get()->CallHookChunkGenerating( - m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc + *m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc ); } @@ -3644,7 +3650,7 @@ void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerating(cChunkDesc & a_Ch void cWorld::cChunkGeneratorCallbacks::CallHookChunkGenerated (cChunkDesc & a_ChunkDesc) { cPluginManager::Get()->CallHookChunkGenerated( - m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc + *m_World, a_ChunkDesc.GetChunkX(), a_ChunkDesc.GetChunkZ(), &a_ChunkDesc ); } diff --git a/src/World.h b/src/World.h index 90dada259..ec6dcadde 100644 --- a/src/World.h +++ b/src/World.h @@ -103,7 +103,7 @@ public: virtual void Run(cWorld & a_World) = 0; } ; - typedef std::vector<cTask *> cTasks; + typedef std::vector<std::unique_ptr<cTask>> cTasks; class cTaskSaveAllChunks : @@ -212,52 +212,52 @@ public: // Broadcast respective packets to all clients of the chunk where the event is taking place // (Please keep these alpha-sorted) void BroadcastAttachEntity (const cEntity & a_Entity, const cEntity * a_Vehicle); - void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = NULL); - void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); ///< If there is a block entity at the specified coods, sends it to all clients except a_Exclude + void BroadcastBlockAction (int a_BlockX, int a_BlockY, int a_BlockZ, char a_Byte1, char a_Byte2, BLOCKTYPE a_BlockType, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastBlockBreakAnimation(int a_EntityID, int a_BlockX, int a_BlockY, int a_BlockZ, char a_Stage, const cClientHandle * a_Exclude = nullptr); + void BroadcastBlockEntity (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); ///< If there is a block entity at the specified coods, sends it to all clients except a_Exclude // tolua_begin - void BroadcastChat (const AString & a_Message, const cClientHandle * a_Exclude = NULL, eMessageType a_ChatPrefix = mtCustom); - void BroadcastChatInfo (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtInformation); } - void BroadcastChatFailure(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtFailure); } - void BroadcastChatSuccess(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtSuccess); } - void BroadcastChatWarning(const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtWarning); } - void BroadcastChatFatal (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtFailure); } - void BroadcastChatDeath (const AString & a_Message, const cClientHandle * a_Exclude = NULL) { BroadcastChat(a_Message, a_Exclude, mtDeath); } - void BroadcastChat (const cCompositeChat & a_Message, const cClientHandle * a_Exclude = NULL); + void BroadcastChat (const AString & a_Message, const cClientHandle * a_Exclude = nullptr, eMessageType a_ChatPrefix = mtCustom); + void BroadcastChatInfo (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtInformation); } + void BroadcastChatFailure(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtFailure); } + void BroadcastChatSuccess(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtSuccess); } + void BroadcastChatWarning(const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtWarning); } + void BroadcastChatFatal (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtFailure); } + void BroadcastChatDeath (const AString & a_Message, const cClientHandle * a_Exclude = nullptr) { BroadcastChat(a_Message, a_Exclude, mtDeath); } + void BroadcastChat (const cCompositeChat & a_Message, const cClientHandle * a_Exclude = nullptr); // tolua_end - void BroadcastChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = NULL); - void BroadcastCollectEntity (const cEntity & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = NULL); - void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - virtual void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = NULL) override; // tolua_export - void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastPlayerListAddPlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListRemovePlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdateGameMode (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdatePing (const cPlayer & a_Player, const cClientHandle * a_Exclude = NULL); - void BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName, const cClientHandle * a_Exclude = NULL); - void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = NULL); + void BroadcastChunkData (int a_ChunkX, int a_ChunkZ, cChunkDataSerializer & a_Serializer, const cClientHandle * a_Exclude = nullptr); + void BroadcastCollectEntity (const cEntity & a_Pickup, const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastDestroyEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEffect (const cEntity & a_Entity, int a_EffectID, int a_Amplifier, short a_Duration, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityEquipment (const cEntity & a_Entity, short a_SlotNum, const cItem & a_Item, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityHeadLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityLook (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityMetadata (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMove (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityRelMoveLook (const cEntity & a_Entity, char a_RelX, char a_RelY, char a_RelZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityStatus (const cEntity & a_Entity, char a_Status, const cClientHandle * a_Exclude = nullptr); + void BroadcastEntityVelocity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + virtual void BroadcastEntityAnimation (const cEntity & a_Entity, char a_Animation, const cClientHandle * a_Exclude = nullptr) override; // tolua_export + void BroadcastParticleEffect (const AString & a_ParticleName, float a_SrcX, float a_SrcY, float a_SrcZ, float a_OffsetX, float a_OffsetY, float a_OffsetZ, float a_ParticleData, int a_ParticleAmount, cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastPlayerListAddPlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListRemovePlayer (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdateGameMode (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdatePing (const cPlayer & a_Player, const cClientHandle * a_Exclude = nullptr); + void BroadcastPlayerListUpdateDisplayName(const cPlayer & a_Player, const AString & a_CustomName, const cClientHandle * a_Exclude = nullptr); + void BroadcastRemoveEntityEffect (const cEntity & a_Entity, int a_EffectID, const cClientHandle * a_Exclude = nullptr); void BroadcastScoreboardObjective (const AString & a_Name, const AString & a_DisplayName, Byte a_Mode); void BroadcastScoreUpdate (const AString & a_Objective, const AString & a_Player, cObjective::Score a_Score, Byte a_Mode); void BroadcastDisplayObjective (const AString & a_Objective, cScoreboard::eDisplaySlot a_Display); - void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = NULL); // tolua_export - void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastTeleportEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = NULL); - void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = NULL); - void BroadcastTimeUpdate (const cClientHandle * a_Exclude = NULL); + void BroadcastSoundEffect (const AString & a_SoundName, double a_X, double a_Y, double a_Z, float a_Volume, float a_Pitch, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastSoundParticleEffect (int a_EffectID, int a_SrcX, int a_SrcY, int a_SrcZ, int a_Data, const cClientHandle * a_Exclude = nullptr); // tolua_export + void BroadcastSpawnEntity (cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastTeleportEntity (const cEntity & a_Entity, const cClientHandle * a_Exclude = nullptr); + void BroadcastThunderbolt (int a_BlockX, int a_BlockY, int a_BlockZ, const cClientHandle * a_Exclude = nullptr); + void BroadcastTimeUpdate (const cClientHandle * a_Exclude = nullptr); virtual void BroadcastUseBed (const cEntity & a_Entity, int a_BlockX, int a_BlockY, int a_BlockZ) override; - void BroadcastWeather (eWeather a_Weather, const cClientHandle * a_Exclude = NULL); + void BroadcastWeather (eWeather a_Weather, const cClientHandle * a_Exclude = nullptr); virtual cBroadcastInterface & GetBroadcastManager(void) override { @@ -298,7 +298,7 @@ public: /** Queues a task to unload unused chunks onto the tick thread. The prefferred way of unloading*/ void QueueUnloadUnusedChunks(void); // tolua_export - void CollectPickupsByPlayer(cPlayer * a_Player); + void CollectPickupsByPlayer(cPlayer & a_Player); /** Adds the player to the world. Uses a queue to store the player object until the Tick thread processes the addition event. @@ -359,12 +359,12 @@ public: /** Sends the chunk to the client specified, if the client doesn't have the chunk yet. If chunk not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ - void SendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); + void SendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client); /** Sends the chunk to the client specified, even if the client already has the chunk. If the chunk's not valid, the request is postponed (ChunkSender will send that chunk when it becomes valid + lighted). */ - void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cClientHandle * a_Client); - + void ForceSendChunkTo(int a_ChunkX, int a_ChunkZ, cChunkSender::eChunkPriority a_Priority, cClientHandle * a_Client); + /** Removes client from ChunkSender's queue of chunks to be sent */ void RemoveClientFromChunkSender(cClientHandle * a_Client); @@ -374,11 +374,11 @@ public: /** Marks the chunk as failed-to-load: */ void ChunkLoadFailed(int a_ChunkX, int a_ChunkZ); - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as UpdateSign() */ - bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as UpdateSign() */ + bool SetSignLines(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp - /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be NULL. Returns true if sign text changed. Same as SetSignLines() */ - bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = NULL); // Exported in ManualBindings.cpp + /** Sets the sign text, asking plugins for permission first. a_Player is the player who this change belongs to, may be nullptr. Returns true if sign text changed. Same as SetSignLines() */ + bool UpdateSign(int a_X, int a_Y, int a_Z, const AString & a_Line1, const AString & a_Line2, const AString & a_Line3, const AString & a_Line4, cPlayer * a_Player = nullptr); // Exported in ManualBindings.cpp /** Sets the command block command. Returns true if command changed. */ bool SetCommandBlockCommand(int a_BlockX, int a_BlockY, int a_BlockZ, const AString & a_Command); // tolua_export @@ -396,7 +396,7 @@ public: void GenerateChunk(int a_ChunkX, int a_ChunkZ); // tolua_export /** Queues a chunk for lighting; a_Callback is called after the chunk is lighted */ - void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = NULL); + void QueueLightChunk(int a_ChunkX, int a_ChunkZ, cChunkCoordCallback * a_Callback = nullptr); bool IsChunkLighted(int a_ChunkX, int a_ChunkZ); @@ -506,7 +506,7 @@ public: // tolua_end - inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager; } + inline cSimulatorManager * GetSimulatorManager(void) { return m_SimulatorManager.get(); } inline cFluidSimulator * GetWaterSimulator(void) { return m_WaterSimulator; } inline cFluidSimulator * GetLavaSimulator (void) { return m_LavaSimulator; } @@ -671,7 +671,7 @@ public: void QueueSaveAllChunks(void); // tolua_export /** Queues a task onto the tick thread. The task object will be deleted once the task is finished */ - void QueueTask(cTask * a_Task); // Exported in ManualBindings.cpp + void QueueTask(std::unique_ptr<cTask> a_Task); // Exported in ManualBindings.cpp /** Queues a task onto the tick thread, with the specified delay. The task object will be deleted once the task is finished */ @@ -764,7 +764,7 @@ public: cChunkGenerator & GetGenerator(void) { return m_Generator; } cWorldStorage & GetStorage (void) { return m_Storage; } - cChunkMap * GetChunkMap (void) { return m_ChunkMap; } + cChunkMap * GetChunkMap (void) { return m_ChunkMap.get(); } /** Sets the blockticking to start at the specified block. Only one blocktick per chunk may be set, second call overwrites the first call */ void SetNextBlockTick(int a_BlockX, int a_BlockY, int a_BlockZ); // tolua_export @@ -781,7 +781,7 @@ public: /** Creates a projectile of the specified type. Returns the projectile's EntityID if successful, <0 otherwise Item parameter used currently for Fireworks to correctly set entity metadata based on item metadata */ - int CreateProjectile(double a_PosX, double a_PosY, double a_PosZ, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem * a_Item, const Vector3d * a_Speed = NULL); // tolua_export + int CreateProjectile(double a_PosX, double a_PosY, double a_PosZ, cProjectileEntity::eKind a_Kind, cEntity * a_Creator, const cItem * a_Item, const Vector3d * a_Speed = nullptr); // tolua_export /** Returns a random number from the m_TickRand in range [0 .. a_Range]. To be used only in the tick thread! */ int GetTickRandomNumber(unsigned a_Range) { return (int)(m_TickRand.randInt(a_Range)); } @@ -857,11 +857,12 @@ private: virtual ~cScheduledTask() { delete m_Task; - m_Task = NULL; + m_Task = nullptr; } }; - typedef std::list<cScheduledTask *> cScheduledTasks; + typedef std::unique_ptr<cScheduledTask> cScheduledTaskPtr; + typedef std::list<cScheduledTaskPtr> cScheduledTasks; AString m_WorldName; @@ -913,11 +914,11 @@ private: std::vector<BlockTickQueueItem *> m_BlockTickQueue; std::vector<BlockTickQueueItem *> m_BlockTickQueueCopy; // Second is for safely removing the objects from the queue - cSimulatorManager * m_SimulatorManager; - cSandSimulator * m_SandSimulator; - cFluidSimulator * m_WaterSimulator; - cFluidSimulator * m_LavaSimulator; - cFireSimulator * m_FireSimulator; + std::unique_ptr<cSimulatorManager> m_SimulatorManager; + std::unique_ptr<cSandSimulator> m_SandSimulator; + cFluidSimulator * m_WaterSimulator; + cFluidSimulator * m_LavaSimulator; + std::unique_ptr<cFireSimulator> m_FireSimulator; cRedstoneSimulator<cChunk, cWorld> * m_RedstoneSimulator; cCriticalSection m_CSPlayers; @@ -927,7 +928,7 @@ private: unsigned int m_MaxPlayers; - cChunkMap * m_ChunkMap; + std::unique_ptr<cChunkMap> m_ChunkMap; bool m_bAnimals; std::set<eMonsterType> m_AllowedMobs; diff --git a/src/WorldStorage/NBTChunkSerializer.cpp b/src/WorldStorage/NBTChunkSerializer.cpp index 28b9dd042..4daa8cc7b 100644 --- a/src/WorldStorage/NBTChunkSerializer.cpp +++ b/src/WorldStorage/NBTChunkSerializer.cpp @@ -467,7 +467,7 @@ void cNBTChunkSerializer::AddMinecartEntity(cMinecart * a_Minecart) void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster) { - const char * EntityClass = NULL; + const char * EntityClass = nullptr; switch (a_Monster->GetMobType()) { case mtBat: EntityClass = "Bat"; break; @@ -604,6 +604,28 @@ void cNBTChunkSerializer::AddMonsterEntity(cMonster * a_Monster) m_Writer.AddByte("IsConverting", (((const cZombie *)a_Monster)->IsConverting() ? 1 : 0)); break; } + case mtInvalidType: + case mtBlaze: + case mtCaveSpider: + case mtChicken: + case mtCow: + case mtEnderDragon: + case mtGhast: + case mtGiant: + case mtIronGolem: + case mtMooshroom: + case mtOcelot: + case mtPig: + case mtSilverfish: + case mtSnowGolem: + case mtSpider: + case mtSquid: + case mtWitch: + case mtZombiePigman: + { + // Other mobs have no special tags. + break; + } } m_Writer.EndCompound(); } @@ -685,21 +707,21 @@ void cNBTChunkSerializer::AddProjectileEntity(cProjectileEntity * a_Projectile) void cNBTChunkSerializer::AddHangingEntity(cHangingEntity * a_Hanging) { - m_Writer.AddByte("Direction", (unsigned char)a_Hanging->GetDirection()); - m_Writer.AddInt("TileX", a_Hanging->GetTileX()); - m_Writer.AddInt("TileY", a_Hanging->GetTileY()); - m_Writer.AddInt("TileZ", a_Hanging->GetTileZ()); - switch (a_Hanging->GetDirection()) + m_Writer.AddInt("TileX", a_Hanging->GetBlockX()); + m_Writer.AddInt("TileY", a_Hanging->GetBlockY()); + m_Writer.AddInt("TileZ", a_Hanging->GetBlockZ()); + switch (a_Hanging->GetFacing()) { - case BLOCK_FACE_YM: m_Writer.AddByte("Dir", (unsigned char)2); break; - case BLOCK_FACE_YP: m_Writer.AddByte("Dir", (unsigned char)1); break; - case BLOCK_FACE_ZM: m_Writer.AddByte("Dir", (unsigned char)0); break; - case BLOCK_FACE_ZP: m_Writer.AddByte("Dir", (unsigned char)3); break; + case BLOCK_FACE_XM: m_Writer.AddByte("Facing", 1); break; + case BLOCK_FACE_XP: m_Writer.AddByte("Facing", 3); break; + case BLOCK_FACE_ZM: m_Writer.AddByte("Facing", 2); break; + case BLOCK_FACE_ZP: m_Writer.AddByte("Facing", 0); break; - case BLOCK_FACE_XM: - case BLOCK_FACE_XP: + case BLOCK_FACE_YM: + case BLOCK_FACE_YP: case BLOCK_FACE_NONE: { + // These directions are invalid, but they may have been previously loaded, so keep them. break; } } @@ -740,7 +762,7 @@ void cNBTChunkSerializer::AddItemFrameEntity(cItemFrame * a_ItemFrame) AddBasicEntity(a_ItemFrame, "ItemFrame"); AddHangingEntity(a_ItemFrame); AddItem(a_ItemFrame->GetItem(), -1, "Item"); - m_Writer.AddByte("ItemRotation", (unsigned char)a_ItemFrame->GetRotation()); + m_Writer.AddByte("ItemRotation", (unsigned char)a_ItemFrame->GetItemRotation()); m_Writer.AddFloat("ItemDropChance", 1.0F); m_Writer.EndCompound(); } diff --git a/src/WorldStorage/ScoreboardSerializer.cpp b/src/WorldStorage/ScoreboardSerializer.cpp index e30eecf67..404604382 100644 --- a/src/WorldStorage/ScoreboardSerializer.cpp +++ b/src/WorldStorage/ScoreboardSerializer.cpp @@ -174,13 +174,13 @@ void cScoreboardSerializer::SaveScoreboardToNBT(cFastNBTWriter & a_Writer) a_Writer.BeginCompound("DisplaySlots"); cObjective * Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsList); - a_Writer.AddString("slot_0", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_0", (Objective == nullptr) ? "" : Objective->GetName()); Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsSidebar); - a_Writer.AddString("slot_1", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_1", (Objective == nullptr) ? "" : Objective->GetName()); Objective = m_ScoreBoard->GetObjectiveIn(cScoreboard::dsName); - a_Writer.AddString("slot_2", (Objective == NULL) ? "" : Objective->GetName()); + a_Writer.AddString("slot_2", (Objective == nullptr) ? "" : Objective->GetName()); a_Writer.EndCompound(); // DisplaySlots diff --git a/src/WorldStorage/WSSAnvil.cpp b/src/WorldStorage/WSSAnvil.cpp index 092b9514c..0c77b4d67 100644 --- a/src/WorldStorage/WSSAnvil.cpp +++ b/src/WorldStorage/WSSAnvil.cpp @@ -126,7 +126,7 @@ cWSSAnvil::cWSSAnvil(cWorld * a_World, int a_CompressionFactor) : #endif // _DEBUG gzFile gz = gzopen((FILE_IO_PREFIX + fnam).c_str(), "wb"); - if (gz != NULL) + if (gz != nullptr) { gzwrite(gz, Writer.GetResult().data(), (unsigned)Writer.GetResult().size()); } @@ -193,7 +193,7 @@ bool cWSSAnvil::GetChunkData(const cChunkCoords & a_Chunk, AString & a_Data) { cCSLock Lock(m_CS); cMCAFile * File = LoadMCAFile(a_Chunk); - if (File == NULL) + if (File == nullptr) { return false; } @@ -208,7 +208,7 @@ bool cWSSAnvil::SetChunkData(const cChunkCoords & a_Chunk, const AString & a_Dat { cCSLock Lock(m_CS); cMCAFile * File = LoadMCAFile(a_Chunk); - if (File == NULL) + if (File == nullptr) { return false; } @@ -234,7 +234,7 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk) // Is it already cached? for (cMCAFiles::iterator itr = m_Files.begin(); itr != m_Files.end(); ++itr) { - if (((*itr) != NULL) && ((*itr)->GetRegionX() == RegionX) && ((*itr)->GetRegionZ() == RegionZ)) + if (((*itr) != nullptr) && ((*itr)->GetRegionX() == RegionX) && ((*itr)->GetRegionZ() == RegionZ)) { // Move the file to front and return it: cMCAFile * f = *itr; @@ -253,9 +253,9 @@ cWSSAnvil::cMCAFile * cWSSAnvil::LoadMCAFile(const cChunkCoords & a_Chunk) cFile::CreateFolder(FILE_IO_PREFIX + FileName); AppendPrintf(FileName, "/r.%d.%d.mca", RegionX, RegionZ); cMCAFile * f = new cMCAFile(FileName, RegionX, RegionZ); - if (f == NULL) + if (f == nullptr) { - return NULL; + return nullptr; } m_Files.push_front(f); @@ -373,7 +373,7 @@ bool cWSSAnvil::LoadChunkFromNBT(const cChunkCoords & a_Chunk, const cParsedNBT // Load the biomes from NBT, if present and valid. First try MCS-style, then Vanilla-style: cChunkDef::BiomeMap BiomeMap; cChunkDef::BiomeMap * Biomes = LoadBiomeMapFromNBT(&BiomeMap, a_NBT, a_NBT.FindChildByName(Level, "MCSBiomes")); - if (Biomes == NULL) + if (Biomes == nullptr) { // MCS-style biomes not available, load vanilla-style: Biomes = LoadVanillaBiomeMapFromNBT(&BiomeMap, a_NBT, a_NBT.FindChildByName(Level, "Biomes")); @@ -426,9 +426,9 @@ bool cWSSAnvil::LoadChunkFromNBT(const cChunkCoords & a_Chunk, const cParsedNBT cSetChunkDataPtr SetChunkData(new cSetChunkData( a_Chunk.m_ChunkX, a_Chunk.m_ChunkZ, BlockTypes, MetaData, - IsLightValid ? BlockLight : NULL, - IsLightValid ? SkyLight : NULL, - NULL, Biomes, + IsLightValid ? BlockLight : nullptr, + IsLightValid ? SkyLight : nullptr, + nullptr, Biomes, Entities, BlockEntities, false )); @@ -525,12 +525,12 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap { if ((a_TagIdx < 0) || (a_NBT.GetType(a_TagIdx) != TAG_ByteArray)) { - return NULL; + return nullptr; } if (a_NBT.GetDataLength(a_TagIdx) != 16 * 16) { // The biomes stored don't match in size - return NULL; + return nullptr; } const unsigned char * VanillaBiomeData = (const unsigned char *)(a_NBT.GetData(a_TagIdx)); for (size_t i = 0; i < ARRAYCOUNT(*a_BiomeMap); i++) @@ -538,7 +538,7 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap if ((VanillaBiomeData)[i] == 0xff) { // Unassigned biomes - return NULL; + return nullptr; } (*a_BiomeMap)[i] = (EMCSBiome)(VanillaBiomeData[i]); } @@ -553,12 +553,12 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_Bio { if ((a_TagIdx < 0) || (a_NBT.GetType(a_TagIdx) != TAG_IntArray)) { - return NULL; + return nullptr; } if (a_NBT.GetDataLength(a_TagIdx) != sizeof(*a_BiomeMap)) { // The biomes stored don't match in size - return NULL; + return nullptr; } const char * BiomeData = (a_NBT.GetData(a_TagIdx)); for (size_t i = 0; i < ARRAYCOUNT(*a_BiomeMap); i++) @@ -567,7 +567,7 @@ cChunkDef::BiomeMap * cWSSAnvil::LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_Bio if ((*a_BiomeMap)[i] == 0xff) { // Unassigned biomes - return NULL; + return nullptr; } } return a_BiomeMap; @@ -631,7 +631,7 @@ void cWSSAnvil::LoadBlockEntitiesFromNBT(cBlockEntityList & a_BlockEntities, con BLOCKTYPE BlockType = cChunkDef::GetBlock(a_BlockTypes, RelX, RelY, RelZ); NIBBLETYPE BlockMeta = cChunkDef::GetNibble(a_BlockMetas, RelX, RelY, RelZ); std::auto_ptr<cBlockEntity> be(LoadBlockEntityFromNBT(a_NBT, Child, x, y, z, BlockType, BlockMeta)); - if (be.get() == NULL) + if (be.get() == nullptr) { continue; } @@ -670,7 +670,7 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a case E_BLOCK_WALLSIGN: return LoadSignFromNBT (a_NBT, a_Tag, a_BlockX, a_BlockY, a_BlockZ, E_BLOCK_WALLSIGN); // Blocktypes that have block entities but don't load their contents from disk: - case E_BLOCK_ENDER_CHEST: return NULL; + case E_BLOCK_ENDER_CHEST: return nullptr; } // All the other blocktypes should have no entities assigned to them. Report an error: @@ -686,7 +686,7 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a ItemTypeToString(a_BlockType).c_str(), a_BlockType, TypeName.c_str(), a_BlockX, a_BlockY, a_BlockZ ); - return NULL; + return nullptr; } @@ -696,11 +696,28 @@ cBlockEntity * cWSSAnvil::LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a bool cWSSAnvil::LoadItemFromNBT(cItem & a_Item, const cParsedNBT & a_NBT, int a_TagIdx) { int Type = a_NBT.FindChildByName(a_TagIdx, "id"); - if ((Type < 0) || (a_NBT.GetType(Type) != TAG_Short)) + if (Type <= 0) { return false; } - a_Item.m_ItemType = a_NBT.GetShort(Type); + + if (a_NBT.GetType(Type) == TAG_String) + { + if (!StringToItem(a_NBT.GetString(Type), a_Item)) + { + // Can't resolve item type + return false; + } + } + else if (a_NBT.GetType(Type) == TAG_Short) + { + a_Item.m_ItemType = a_NBT.GetShort(Type); + } + else + { + return false; + } + if (a_Item.m_ItemType < 0) { a_Item.Empty(); @@ -836,7 +853,7 @@ cBlockEntity * cWSSAnvil::LoadBeaconFromNBT(const cParsedNBT & a_NBT, int a_TagI // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Beacon")) { - return NULL; + return nullptr; } std::auto_ptr<cBeaconEntity> Beacon(new cBeaconEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -881,13 +898,13 @@ cBlockEntity * cWSSAnvil::LoadChestFromNBT(const cParsedNBT & a_NBT, int a_TagId // https://github.com/mc-server/MCServer/blob/d0551e2e0a98a28f31a88d489d17b408e4a7d38d/src/WorldStorage/WSSAnvil.cpp#L637 if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Chest") && !CheckBlockEntityType(a_NBT, a_TagIdx, "TrappedChest")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty chest - the chunk loader will provide an empty cChestEntity for this + return nullptr; // Make it an empty chest - the chunk loader will provide an empty cChestEntity for this } std::auto_ptr<cChestEntity> Chest(new cChestEntity(a_BlockX, a_BlockY, a_BlockZ, m_World, a_ChestBlockType)); LoadItemGridFromNBT(Chest->GetContents(), a_NBT, Items); @@ -903,7 +920,7 @@ cBlockEntity * cWSSAnvil::LoadCommandBlockFromNBT(const cParsedNBT & a_NBT, int // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Control")) { - return NULL; + return nullptr; } std::auto_ptr<cCommandBlockEntity> CmdBlock(new cCommandBlockEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -940,13 +957,13 @@ cBlockEntity * cWSSAnvil::LoadDispenserFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Trap")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty dispenser - the chunk loader will provide an empty cDispenserEntity for this + return nullptr; // Make it an empty dispenser - the chunk loader will provide an empty cDispenserEntity for this } std::auto_ptr<cDispenserEntity> Dispenser(new cDispenserEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Dispenser->GetContents(), a_NBT, Items); @@ -962,13 +979,13 @@ cBlockEntity * cWSSAnvil::LoadDropperFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Dropper")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty dropper - the chunk loader will provide an empty cDropperEntity for this + return nullptr; // Make it an empty dropper - the chunk loader will provide an empty cDropperEntity for this } std::auto_ptr<cDropperEntity> Dropper(new cDropperEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Dropper->GetContents(), a_NBT, Items); @@ -984,7 +1001,7 @@ cBlockEntity * cWSSAnvil::LoadFlowerPotFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "FlowerPot")) { - return NULL; + return nullptr; } std::auto_ptr<cFlowerPotEntity> FlowerPot(new cFlowerPotEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1015,13 +1032,13 @@ cBlockEntity * cWSSAnvil::LoadFurnaceFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Furnace")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty furnace - the chunk loader will provide an empty cFurnaceEntity for this + return nullptr; // Make it an empty furnace - the chunk loader will provide an empty cFurnaceEntity for this } std::auto_ptr<cFurnaceEntity> Furnace(new cFurnaceEntity(a_BlockX, a_BlockY, a_BlockZ, a_BlockType, a_BlockMeta, m_World)); @@ -1073,13 +1090,13 @@ cBlockEntity * cWSSAnvil::LoadHopperFromNBT(const cParsedNBT & a_NBT, int a_TagI // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Hopper")) { - return NULL; + return nullptr; } int Items = a_NBT.FindChildByName(a_TagIdx, "Items"); if ((Items < 0) || (a_NBT.GetType(Items) != TAG_List)) { - return NULL; // Make it an empty hopper - the chunk loader will provide an empty cHopperEntity for this + return nullptr; // Make it an empty hopper - the chunk loader will provide an empty cHopperEntity for this } std::auto_ptr<cHopperEntity> Hopper(new cHopperEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); LoadItemGridFromNBT(Hopper->GetContents(), a_NBT, Items); @@ -1095,7 +1112,7 @@ cBlockEntity * cWSSAnvil::LoadJukeboxFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "RecordPlayer")) { - return NULL; + return nullptr; } std::auto_ptr<cJukeboxEntity> Jukebox(new cJukeboxEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1116,7 +1133,7 @@ cBlockEntity * cWSSAnvil::LoadMobHeadFromNBT(const cParsedNBT & a_NBT, int a_Tag // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Skull")) { - return NULL; + return nullptr; } std::auto_ptr<cMobHeadEntity> MobHead(new cMobHeadEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1151,7 +1168,7 @@ cBlockEntity * cWSSAnvil::LoadNoteBlockFromNBT(const cParsedNBT & a_NBT, int a_T // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Music")) { - return NULL; + return nullptr; } std::auto_ptr<cNoteEntity> NoteBlock(new cNoteEntity(a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1172,7 +1189,7 @@ cBlockEntity * cWSSAnvil::LoadSignFromNBT(const cParsedNBT & a_NBT, int a_TagIdx // Check if the data has a proper type: if (!CheckBlockEntityType(a_NBT, a_TagIdx, "Sign")) { - return NULL; + return nullptr; } std::auto_ptr<cSignEntity> Sign(new cSignEntity(a_BlockType, a_BlockX, a_BlockY, a_BlockZ, m_World)); @@ -1660,30 +1677,41 @@ void cWSSAnvil::LoadExpOrbFromNBT(cEntityList & a_Entities, const cParsedNBT & a void cWSSAnvil::LoadHangingFromNBT(cHangingEntity & a_Hanging, const cParsedNBT & a_NBT, int a_TagIdx) { - int Direction = a_NBT.FindChildByName(a_TagIdx, "Direction"); - if (Direction > 0) + // "Facing" tag is the prime source of the Facing; if not available, translate from older "Direction" or "Dir" + int Facing = a_NBT.FindChildByName(a_TagIdx, "Facing"); + if (Facing > 0) { - Direction = (int)a_NBT.GetByte(Direction); - if ((Direction < 2) || (Direction > 5)) - { - a_Hanging.SetDirection(BLOCK_FACE_NORTH); - } - else + Facing = (int)a_NBT.GetByte(Facing); + if ((Facing >= 2) && (Facing <= 5)) { - a_Hanging.SetDirection(static_cast<eBlockFace>(Direction)); + a_Hanging.SetFacing(static_cast<eBlockFace>(Facing)); } } else { - Direction = a_NBT.FindChildByName(a_TagIdx, "Dir"); - if (Direction > 0) + Facing = a_NBT.FindChildByName(a_TagIdx, "Direction"); + if (Facing > 0) { - switch ((int)a_NBT.GetByte(Direction)) + switch ((int)a_NBT.GetByte(Facing)) { - case 0: a_Hanging.SetDirection(BLOCK_FACE_NORTH); break; - case 1: a_Hanging.SetDirection(BLOCK_FACE_TOP); break; - case 2: a_Hanging.SetDirection(BLOCK_FACE_BOTTOM); break; - case 3: a_Hanging.SetDirection(BLOCK_FACE_SOUTH); break; + case 0: a_Hanging.SetFacing(BLOCK_FACE_ZM); break; + case 1: a_Hanging.SetFacing(BLOCK_FACE_XM); break; + case 2: a_Hanging.SetFacing(BLOCK_FACE_ZP); break; + case 3: a_Hanging.SetFacing(BLOCK_FACE_XP); break; + } + } + else + { + Facing = a_NBT.FindChildByName(a_TagIdx, "Dir"); // Has values 0 and 2 swapped + if (Facing > 0) + { + switch ((int)a_NBT.GetByte(Facing)) + { + case 0: a_Hanging.SetFacing(BLOCK_FACE_ZP); break; + case 1: a_Hanging.SetFacing(BLOCK_FACE_XM); break; + case 2: a_Hanging.SetFacing(BLOCK_FACE_ZM); break; + case 3: a_Hanging.SetFacing(BLOCK_FACE_XP); break; + } } } } @@ -1732,7 +1760,7 @@ void cWSSAnvil::LoadItemFrameFromNBT(cEntityList & a_Entities, const cParsedNBT int Rotation = a_NBT.FindChildByName(a_TagIdx, "ItemRotation"); if (Rotation > 0) { - ItemFrame->SetRotation((Byte)a_NBT.GetByte(Rotation)); + ItemFrame->SetItemRotation((Byte)a_NBT.GetByte(Rotation)); } a_Entities.push_back(ItemFrame.release()); @@ -1744,7 +1772,7 @@ void cWSSAnvil::LoadItemFrameFromNBT(cEntityList & a_Entities, const cParsedNBT void cWSSAnvil::LoadArrowFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cArrowEntity> Arrow(new cArrowEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cArrowEntity> Arrow(new cArrowEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Arrow.get(), a_NBT, a_TagIdx)) { return; @@ -1808,7 +1836,7 @@ void cWSSAnvil::LoadArrowFromNBT(cEntityList & a_Entities, const cParsedNBT & a_ void cWSSAnvil::LoadSplashPotionFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cSplashPotionEntity> SplashPotion(new cSplashPotionEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0), cItem())); + std::auto_ptr<cSplashPotionEntity> SplashPotion(new cSplashPotionEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0), cItem())); if (!LoadProjectileBaseFromNBT(*SplashPotion.get(), a_NBT, a_TagIdx)) { return; @@ -1832,7 +1860,7 @@ void cWSSAnvil::LoadSplashPotionFromNBT(cEntityList & a_Entities, const cParsedN void cWSSAnvil::LoadSnowballFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cThrownSnowballEntity> Snowball(new cThrownSnowballEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cThrownSnowballEntity> Snowball(new cThrownSnowballEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Snowball.get(), a_NBT, a_TagIdx)) { return; @@ -1848,7 +1876,7 @@ void cWSSAnvil::LoadSnowballFromNBT(cEntityList & a_Entities, const cParsedNBT & void cWSSAnvil::LoadEggFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cThrownEggEntity> Egg(new cThrownEggEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cThrownEggEntity> Egg(new cThrownEggEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Egg.get(), a_NBT, a_TagIdx)) { return; @@ -1864,7 +1892,7 @@ void cWSSAnvil::LoadEggFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NB void cWSSAnvil::LoadFireballFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cGhastFireballEntity> Fireball(new cGhastFireballEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cGhastFireballEntity> Fireball(new cGhastFireballEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Fireball.get(), a_NBT, a_TagIdx)) { return; @@ -1880,7 +1908,7 @@ void cWSSAnvil::LoadFireballFromNBT(cEntityList & a_Entities, const cParsedNBT & void cWSSAnvil::LoadFireChargeFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cFireChargeEntity> FireCharge(new cFireChargeEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cFireChargeEntity> FireCharge(new cFireChargeEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*FireCharge.get(), a_NBT, a_TagIdx)) { return; @@ -1896,7 +1924,7 @@ void cWSSAnvil::LoadFireChargeFromNBT(cEntityList & a_Entities, const cParsedNBT void cWSSAnvil::LoadThrownEnderpearlFromNBT(cEntityList & a_Entities, const cParsedNBT & a_NBT, int a_TagIdx) { - std::auto_ptr<cThrownEnderPearlEntity> Enderpearl(new cThrownEnderPearlEntity(NULL, 0, 0, 0, Vector3d(0, 0, 0))); + std::auto_ptr<cThrownEnderPearlEntity> Enderpearl(new cThrownEnderPearlEntity(nullptr, 0, 0, 0, Vector3d(0, 0, 0))); if (!LoadProjectileBaseFromNBT(*Enderpearl.get(), a_NBT, a_TagIdx)) { return; @@ -2853,7 +2881,7 @@ bool cWSSAnvil::cMCAFile::OpenFile(bool a_IsForReading) if (m_File.Read(m_Header, sizeof(m_Header)) != sizeof(m_Header)) { // Cannot read the header - perhaps the file has just been created? - // Try writing a NULL header (both chunk offsets and timestamps): + // Try writing a nullptr header (both chunk offsets and timestamps): memset(m_Header, 0, sizeof(m_Header)); if ( (m_File.Write(m_Header, sizeof(m_Header)) != sizeof(m_Header)) || // Real header - chunk offsets diff --git a/src/WorldStorage/WSSAnvil.h b/src/WorldStorage/WSSAnvil.h index 591ec6757..9c579a617 100644 --- a/src/WorldStorage/WSSAnvil.h +++ b/src/WorldStorage/WSSAnvil.h @@ -113,10 +113,10 @@ protected: /// Saves the chunk into NBT data using a_Writer; returns true on success bool SaveChunkToNBT(const cChunkCoords & a_Chunk, cFastNBTWriter & a_Writer); - /// Loads the chunk's biome map from vanilla-format; returns a_BiomeMap if biomes present and valid, NULL otherwise + /// Loads the chunk's biome map from vanilla-format; returns a_BiomeMap if biomes present and valid, nullptr otherwise cChunkDef::BiomeMap * LoadVanillaBiomeMapFromNBT(cChunkDef::BiomeMap * a_BiomeMap, const cParsedNBT & a_NBT, int a_TagIdx); - /// Loads the chunk's biome map from MCS format; returns a_BiomeMap if biomes present and valid, NULL otherwise + /// Loads the chunk's biome map from MCS format; returns a_BiomeMap if biomes present and valid, nullptr otherwise cChunkDef::BiomeMap * LoadBiomeMapFromNBT(cChunkDef::BiomeMap * a_BiomeMap, const cParsedNBT & a_NBT, int a_TagIdx); /// Loads the chunk's entities from NBT data (a_Tag is the Level\\Entities list tag; may be -1) @@ -126,7 +126,7 @@ protected: void LoadBlockEntitiesFromNBT(cBlockEntityList & a_BlockEntitites, const cParsedNBT & a_NBT, int a_Tag, BLOCKTYPE * a_BlockTypes, NIBBLETYPE * a_BlockMetas); /** Loads the data for a block entity from the specified NBT tag. - Returns the loaded block entity, or NULL upon failure. */ + Returns the loaded block entity, or nullptr upon failure. */ cBlockEntity * LoadBlockEntityFromNBT(const cParsedNBT & a_NBT, int a_Tag, int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta); /// Loads a cItem contents from the specified NBT tag; returns true if successful. Doesn't load the Slot tag diff --git a/src/WorldStorage/WorldStorage.cpp b/src/WorldStorage/WorldStorage.cpp index c611bfd90..31318ee67 100644 --- a/src/WorldStorage/WorldStorage.cpp +++ b/src/WorldStorage/WorldStorage.cpp @@ -39,8 +39,8 @@ protected: cWorldStorage::cWorldStorage(void) : super("cWorldStorage"), - m_World(NULL), - m_SaveSchema(NULL) + m_World(nullptr), + m_SaveSchema(nullptr) { } diff --git a/src/XMLParser.h b/src/XMLParser.h index e39405529..5b53e55cf 100644 --- a/src/XMLParser.h +++ b/src/XMLParser.h @@ -68,7 +68,7 @@ protected: 3, Create an instance of your class: CMyParser Parser; 4, Call Create(): - Parser.Create(NULL, NULL); + Parser.Create(nullptr, nullptr); 4, Call Parse(), repeatedly: Parser.Parse(Buffer, Length); */ @@ -84,7 +84,7 @@ public: CExpatImpl () { - m_p = NULL; + m_p = nullptr; } // @cmember Destructor @@ -99,24 +99,24 @@ public: // @cmember Create a parser - bool Create (const XML_Char * pszEncoding = NULL, const XML_Char * pszSep = NULL) + bool Create (const XML_Char * pszEncoding = nullptr, const XML_Char * pszSep = nullptr) { // Destroy the old parser Destroy (); - // If the encoding or seperator are empty, then NULL - if (pszEncoding != NULL && pszEncoding [0] == 0) + // If the encoding or seperator are empty, then nullptr + if (pszEncoding != nullptr && pszEncoding [0] == 0) { - pszEncoding = NULL; + pszEncoding = nullptr; } - if (pszSep != NULL && pszSep [0] == 0) + if (pszSep != nullptr && pszSep [0] == 0) { - pszSep = NULL; + pszSep = nullptr; } // Create the new parser - m_p = XML_ParserCreate_MM (pszEncoding, NULL, pszSep); - if (m_p == NULL) + m_p = XML_ParserCreate_MM (pszEncoding, nullptr, pszSep); + if (m_p == nullptr) { return false; } @@ -134,11 +134,11 @@ public: void Destroy (void) { - if (m_p != NULL) + if (m_p != nullptr) { XML_ParserFree (m_p); } - m_p = NULL; + m_p = nullptr; } @@ -146,7 +146,7 @@ public: bool Parse (const char *pszBuffer, int nLength, bool fIsFinal = true) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_Parse (m_p, pszBuffer, nLength, fIsFinal) != 0; } @@ -154,7 +154,7 @@ public: bool ParseBuffer (int nLength, bool fIsFinal = true) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_ParseBuffer (m_p, nLength, fIsFinal) != 0; } @@ -162,7 +162,7 @@ public: void *GetBuffer (int nLength) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetBuffer (m_p, nLength); } @@ -174,23 +174,23 @@ protected: void EnableStartElementHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartElementHandler (m_p, fEnable ? StartElementHandler : NULL); + assert (m_p != nullptr); + XML_SetStartElementHandler (m_p, fEnable ? StartElementHandler : nullptr); } // @cmember Enable/Disable the end element handler void EnableEndElementHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndElementHandler (m_p, fEnable ? EndElementHandler : NULL); + assert (m_p != nullptr); + XML_SetEndElementHandler (m_p, fEnable ? EndElementHandler : nullptr); } // @cmember Enable/Disable the element handlers void EnableElementHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartElementHandler (fEnable); EnableEndElementHandler (fEnable); } @@ -199,47 +199,47 @@ protected: void EnableCharacterDataHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetCharacterDataHandler (m_p, fEnable ? CharacterDataHandler : NULL); + assert (m_p != nullptr); + XML_SetCharacterDataHandler (m_p, fEnable ? CharacterDataHandler : nullptr); } // @cmember Enable/Disable the processing instruction handler void EnableProcessingInstructionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetProcessingInstructionHandler (m_p, fEnable ? ProcessingInstructionHandler : NULL); + assert (m_p != nullptr); + XML_SetProcessingInstructionHandler (m_p, fEnable ? ProcessingInstructionHandler : nullptr); } // @cmember Enable/Disable the comment handler void EnableCommentHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetCommentHandler (m_p, fEnable ? CommentHandler : NULL); + assert (m_p != nullptr); + XML_SetCommentHandler (m_p, fEnable ? CommentHandler : nullptr); } // @cmember Enable/Disable the start CDATA section handler void EnableStartCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartCdataSectionHandler (m_p, fEnable ? StartCdataSectionHandler : NULL); + assert (m_p != nullptr); + XML_SetStartCdataSectionHandler (m_p, fEnable ? StartCdataSectionHandler : nullptr); } // @cmember Enable/Disable the end CDATA section handler void EnableEndCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndCdataSectionHandler (m_p, fEnable ? EndCdataSectionHandler : NULL); + assert (m_p != nullptr); + XML_SetEndCdataSectionHandler (m_p, fEnable ? EndCdataSectionHandler : nullptr); } // @cmember Enable/Disable the CDATA section handlers void EnableCdataSectionHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartCdataSectionHandler (fEnable); EnableEndCdataSectionHandler (fEnable); } @@ -248,45 +248,45 @@ protected: void EnableDefaultHandler (bool fEnable = true, bool fExpand = true) { - assert (m_p != NULL); + assert (m_p != nullptr); if (fExpand) { - XML_SetDefaultHandlerExpand (m_p, fEnable ? DefaultHandler : NULL); + XML_SetDefaultHandlerExpand (m_p, fEnable ? DefaultHandler : nullptr); } else - XML_SetDefaultHandler (m_p, fEnable ? DefaultHandler : NULL); + XML_SetDefaultHandler (m_p, fEnable ? DefaultHandler : nullptr); } // @cmember Enable/Disable external entity ref handler void EnableExternalEntityRefHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetExternalEntityRefHandler (m_p, fEnable ? ExternalEntityRefHandler : NULL); + assert (m_p != nullptr); + XML_SetExternalEntityRefHandler (m_p, fEnable ? ExternalEntityRefHandler : nullptr); } // @cmember Enable/Disable unknown encoding handler void EnableUnknownEncodingHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetUnknownEncodingHandler (m_p, fEnable ? UnknownEncodingHandler : NULL); + assert (m_p != nullptr); + XML_SetUnknownEncodingHandler (m_p, fEnable ? UnknownEncodingHandler : nullptr); } // @cmember Enable/Disable start namespace handler void EnableStartNamespaceDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartNamespaceDeclHandler (m_p, fEnable ? StartNamespaceDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetStartNamespaceDeclHandler (m_p, fEnable ? StartNamespaceDeclHandler : nullptr); } // @cmember Enable/Disable end namespace handler void EnableEndNamespaceDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetEndNamespaceDeclHandler (m_p, fEnable ? EndNamespaceDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetEndNamespaceDeclHandler (m_p, fEnable ? EndNamespaceDeclHandler : nullptr); } // @cmember Enable/Disable namespace handlers @@ -301,32 +301,32 @@ protected: void EnableXmlDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetXmlDeclHandler (m_p, fEnable ? XmlDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetXmlDeclHandler (m_p, fEnable ? XmlDeclHandler : nullptr); } // @cmember Enable/Disable the start DOCTYPE declaration handler void EnableStartDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); - XML_SetStartDoctypeDeclHandler (m_p, fEnable ? StartDoctypeDeclHandler : NULL); + assert (m_p != nullptr); + XML_SetStartDoctypeDeclHandler (m_p, fEnable ? StartDoctypeDeclHandler : nullptr); } // @cmember Enable/Disable the end DOCTYPE declaration handler void EnableEndDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); XML_SetEndDoctypeDeclHandler (m_p, - fEnable ? EndDoctypeDeclHandler : NULL); + fEnable ? EndDoctypeDeclHandler : nullptr); } // @cmember Enable/Disable the DOCTYPE declaration handler void EnableDoctypeDeclHandler (bool fEnable = true) { - assert (m_p != NULL); + assert (m_p != nullptr); EnableStartDoctypeDeclHandler (fEnable); EnableEndDoctypeDeclHandler (fEnable); } @@ -338,7 +338,7 @@ public: enum XML_Error GetErrorCode () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetErrorCode (m_p); } @@ -346,7 +346,7 @@ public: long GetCurrentByteIndex () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentByteIndex (m_p); } @@ -354,7 +354,7 @@ public: int GetCurrentLineNumber () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentLineNumber (m_p); } @@ -362,7 +362,7 @@ public: int GetCurrentColumnNumber () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentColumnNumber (m_p); } @@ -370,7 +370,7 @@ public: int GetCurrentByteCount () { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetCurrentByteCount (m_p); } @@ -378,7 +378,7 @@ public: const char *GetInputContext (int *pnOffset, int *pnSize) { - assert (m_p != NULL); + assert (m_p != nullptr); return XML_GetInputContext (m_p, pnOffset, pnSize); } @@ -682,17 +682,17 @@ protected: XML_Parser m_p; - /// Returns the value of the specified attribute, if found; NULL otherwise + /// Returns the value of the specified attribute, if found; nullptr otherwise static const XML_Char * FindAttr(const XML_Char ** iAttrs, const XML_Char * iAttrToFind) { - for (const XML_Char ** Attr = iAttrs; *Attr != NULL; Attr += 2) + for (const XML_Char ** Attr = iAttrs; *Attr != nullptr; Attr += 2) { if (strcmp(*Attr, iAttrToFind) == 0) { return *(Attr + 1); } } // for Attr - iAttrs[] - return NULL; + return nullptr; } } ; diff --git a/src/main.cpp b/src/main.cpp index 86ecd4000..463c54c28 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -133,8 +133,8 @@ LONG WINAPI LastChanceExceptionFilter(__in struct _EXCEPTION_POINTERS * a_Except ExcInformation.ClientPointers = 0; // Write the dump file: - HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); - g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : NULL, NULL, NULL); + HANDLE dumpFile = CreateFile(g_DumpFileName, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + g_WriteMiniDump(GetCurrentProcess(), GetCurrentProcessId(), dumpFile, g_DumpFlags, (a_ExceptionInfo) ? &ExcInformation : nullptr, nullptr, nullptr); CloseHandle(dumpFile); // Revert to old stack: @@ -187,7 +187,7 @@ int main( int argc, char **argv) #if defined(_WIN32) && !defined(_WIN64) && defined(_MSC_VER) HINSTANCE hDbgHelp = LoadLibrary("DBGHELP.DLL"); g_WriteMiniDump = (pMiniDumpWriteDump)GetProcAddress(hDbgHelp, "MiniDumpWriteDump"); - if (g_WriteMiniDump != NULL) + if (g_WriteMiniDump != nullptr) { _snprintf_s(g_DumpFileName, ARRAYCOUNT(g_DumpFileName), _TRUNCATE, "crash_mcs_%x.dmp", GetCurrentProcessId()); SetUnhandledExceptionFilter(LastChanceExceptionFilter); @@ -269,7 +269,7 @@ int main( int argc, char **argv) } else if (NoCaseCompare(Arg, "nooutbuf") == 0) { - setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stdout, nullptr, _IONBF, 0); } } // for i - argv[] |