diff options
Diffstat (limited to 'src')
68 files changed, 1073 insertions, 517 deletions
diff --git a/src/Bindings/AllToLua.pkg b/src/Bindings/AllToLua.pkg index 37e6aecd2..73de98e22 100644 --- a/src/Bindings/AllToLua.pkg +++ b/src/Bindings/AllToLua.pkg @@ -27,6 +27,7 @@ $cfile "WebPlugin.h" $cfile "LuaWindow.h" $cfile "../BlockID.h" +$cfile "../Mobs/MonsterTypes.h" $cfile "../BlockInfo.h" $cfile "../StringUtils.h" $cfile "../Defines.h" diff --git a/src/Bindings/LuaChunkStay.cpp b/src/Bindings/LuaChunkStay.cpp index a3d3a8090..23da12f68 100644 --- a/src/Bindings/LuaChunkStay.cpp +++ b/src/Bindings/LuaChunkStay.cpp @@ -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 ba2f3c5e0..85e3f9fc5 100644 --- a/src/Bindings/LuaState.cpp +++ b/src/Bindings/LuaState.cpp @@ -861,6 +861,11 @@ void cLuaState::GetStackValue(int a_StackPos, eWeather & a_ReturnedVal) void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) { + if (lua_isnil(m_LuaState, a_StackPos)) + { + a_ReturnedVal = NULL; + return; + } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cBoundingBox", false, &err)) { @@ -874,6 +879,11 @@ void cLuaState::GetStackValue(int a_StackPos, pBoundingBox & a_ReturnedVal) void cLuaState::GetStackValue(int a_StackPos, pWorld & a_ReturnedVal) { + if (lua_isnil(m_LuaState, a_StackPos)) + { + a_ReturnedVal = NULL; + return; + } tolua_Error err; if (tolua_isusertype(m_LuaState, a_StackPos, "cWorld", false, &err)) { @@ -1396,10 +1406,8 @@ void cLuaState::LogStack(const char * a_Header) void cLuaState::LogStack(lua_State * a_LuaState, const char * a_Header) { - UNUSED(a_Header); // The param seems unused when compiling for release, so the compiler warns - // Format string consisting only of %s is used to appease the compiler - LOGD("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); + LOG("%s", (a_Header != NULL) ? a_Header : "Lua C API Stack contents:"); for (int i = lua_gettop(a_LuaState); i > 0; i--) { AString Value; diff --git a/src/Bindings/LuaState.h b/src/Bindings/LuaState.h index 094a200e0..779760017 100644 --- a/src/Bindings/LuaState.h +++ b/src/Bindings/LuaState.h @@ -240,10 +240,24 @@ 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) + { + PushFunction(a_Function); + 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 +318,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); + void LogStack(const char * a_Header = NULL); /** 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); protected: + lua_State * m_LuaState; /** If true, the state is owned by this object and will be auto-Closed. False => attached state */ @@ -327,6 +342,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/ManualBindings.cpp b/src/Bindings/ManualBindings.cpp index f4764447c..0558533ce 100644 --- a/src/Bindings/ManualBindings.cpp +++ b/src/Bindings/ManualBindings.cpp @@ -697,8 +697,12 @@ static int tolua_ForEachInBox(lua_State * tolua_S) Ty1 * Self = NULL; cBoundingBox * Box = NULL; L.GetStackValues(1, Self, Box); - ASSERT(Self != NULL); // We have verified the type at the top, so we should get valid objects here - ASSERT(Box != NULL); + if ((Self == NULL) || (Box == NULL)) + { + LOGWARNING("Invalid world (%p) or boundingbox (%p)", Self, Box); + L.LogStackTrace(); + return 0; + } // Create a reference for the function: cLuaState::cRef FnRef(L, 3); @@ -1156,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; } 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..eec31e8a6 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; } 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..43507a5fb 100644 --- a/src/Bindings/PluginManager.cpp +++ b/src/Bindings/PluginManager.cpp @@ -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,19 +1429,19 @@ 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; } @@ -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); } diff --git a/src/Bindings/PluginManager.h b/src/Bindings/PluginManager.h index fff3bc323..c69850be6 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 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); @@ -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/BlockID.cpp b/src/BlockID.cpp index 9026d81f2..755c721db 100644 --- a/src/BlockID.cpp +++ b/src/BlockID.cpp @@ -253,57 +253,6 @@ AString ItemToFullString(const cItem & a_Item) -int StringToMobType(const AString & a_MobString) -{ - static struct - { - int m_MobType; - const char * m_String; - } MobMap [] = - { - {mtCreeper, "Creeper"}, - {mtSkeleton, "Skeleton"}, - {mtSpider, "Spider"}, - {mtGiant, "Giant"}, - {mtZombie, "Zombie"}, - {mtSlime, "Slime"}, - {mtGhast, "Ghast"}, - {mtZombiePigman, "ZombiePigman"}, - {mtEnderman, "Enderman"}, - {mtCaveSpider, "CaveSpider"}, - {mtSilverfish, "SilverFish"}, - {mtBlaze, "Blaze"}, - {mtMagmaCube, "MagmaCube"}, - {mtEnderDragon, "EnderDragon"}, - {mtWither, "Wither"}, - {mtBat, "Bat"}, - {mtWitch, "Witch"}, - {mtPig, "Pig"}, - {mtSheep, "Sheep"}, - {mtCow, "Cow"}, - {mtChicken, "Chicken"}, - {mtSquid, "Squid"}, - {mtWolf, "Wolf"}, - {mtMooshroom, "Mooshroom"}, - {mtSnowGolem, "SnowGolem"}, - {mtOcelot, "Ocelot"}, - {mtIronGolem, "IronGolem"}, - {mtVillager, "Villager"}, - }; - for (size_t i = 0; i < ARRAYCOUNT(MobMap); i++) - { - if (NoCaseCompare(MobMap[i].m_String, a_MobString) == 0) - { - return MobMap[i].m_MobType; - } - } // for i - MobMap[] - return -1; -} - - - - - eDimension StringToDimension(const AString & a_DimensionString) { // First try decoding as a number diff --git a/src/BlockID.h b/src/BlockID.h index 69b5e2fe0..bb06722d2 100644 --- a/src/BlockID.h +++ b/src/BlockID.h @@ -445,6 +445,21 @@ enum //////////////////////////////////////////////////////////////////////////////// // Block metas: + // E_BLOCK_ANVIL metas + E_BLOCK_ANVIL_Z = 0, + E_BLOCK_ANVIL_X = 1, + E_BLOCK_ANVIL_NO_DAMAGE = 0, + E_BLOCK_ANVIL_LOW_DAMAGE = 4, + E_BLOCK_ANVIL_HIGH_DAMAGE = 8, + + // E_BLOCK_BED metas: + E_BLOCK_BED_ZP = 0, + E_BLOCK_BED_XM = 1, + E_BLOCK_BED_ZM = 2, + E_BLOCK_BED_XP = 3, + E_BLOCK_BED_OCCUPIED = 4, + E_BLOCK_BED_BED_HEAD = 8, + // E_BLOCK_BIG_FLOWER metas: E_META_BIG_FLOWER_SUNFLOWER = 0, E_META_BIG_FLOWER_LILAC = 1, @@ -453,6 +468,20 @@ enum E_META_BIG_FLOWER_ROSE_BUSH = 4, E_META_BIG_FLOWER_PEONY = 5, + // E_BLOCK_BREWING_STAND metas + E_META_BREWING_STAND_FILLED_SLOT_XP = 1, + E_META_BREWING_STAND_FILLED_SLOT_XM_ZP = 2, + E_META_BREWING_STAND_FILLED_SLOT_XM_ZM = 4, + + // E_BLOCK_BUTTON metas + E_BLOCK_BUTTON_YM = 0, + E_BLOCK_BUTTON_XP = 1, + E_BLOCK_BUTTON_XM = 2, + E_BLOCK_BUTTON_ZP = 3, + E_BLOCK_BUTTON_ZM = 4, + E_BLOCK_BUTTON_YP = 5, + E_BLOCK_BUTTON_PRESSED = 8, + // E_BLOCK_CARPET metas: E_META_CARPET_WHITE = 0, E_META_CARPET_ORANGE = 1, @@ -492,14 +521,17 @@ enum E_META_DROPSPENSER_FACING_XP = 5, // E_BLOCK_DOUBLE_STONE_SLAB metas: - E_META_DOUBLE_STONE_SLAB_STONE = 0, - E_META_DOUBLE_STONE_SLAB_SANDSTONE = 1, - E_META_DOUBLE_STONE_SLAB_WOODEN = 2, - E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, - E_META_DOUBLE_STONE_SLAB_BRICK = 4, - E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, - E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, - E_META_DOUBLE_STONE_SLAB_STONE_SECRET = 7, + E_META_DOUBLE_STONE_SLAB_STONE = 0, + E_META_DOUBLE_STONE_SLAB_SANDSTON = 1, + E_META_DOUBLE_STONE_SLAB_WOODEN = 2, + E_META_DOUBLE_STONE_SLAB_COBBLESTONE = 3, + E_META_DOUBLE_STONE_SLAB_BRICK = 4, + E_META_DOUBLE_STONE_SLAB_STONE_BRICK = 5, + E_META_DOUBLE_STONE_SLAB_NETHER_BRICK = 6, + E_META_DOUBLE_STONE_SLAB_QUARTZ = 7, + E_META_DOUBLE_STONE_SLAB_SMOOTH_STONE = 8, + E_META_DOUBLE_STONE_SLAB_SMOOTH_SANDSTONE = 9, + E_META_DOUBLE_STONE_SLAB_TILE_QUARTZ = 10, // E_BLOCK_FLOWER metas: E_META_FLOWER_POPPY = 0, @@ -512,8 +544,8 @@ enum E_META_FLOWER_OXEYE_DAISY = 8, // E_BLOCK_JUKEBOX metas: - E_META_JUKEBOX_OFF = 0, - E_META_JUKEBOX_ON = 1, + E_META_JUKEBOX_OFF = 0, + E_META_JUKEBOX_ON = 1, // E_BLOCK_HOPPER metas: E_META_HOPPER_FACING_YM = 0, @@ -524,10 +556,26 @@ enum E_META_HOPPER_FACING_XP = 5, // E_BLOCK_LEAVES metas: - E_META_LEAVES_APPLE = 0, - E_META_LEAVES_CONIFER = 1, - E_META_LEAVES_BIRCH = 2, - E_META_LEAVES_JUNGLE = 3, + E_META_LEAVES_APPLE = 0, + E_META_LEAVES_CONIFER = 1, + E_META_LEAVES_BIRCH = 2, + E_META_LEAVES_JUNGLE = 3, + E_META_LEAVES_APPLE_NO_DECAY = 4, + E_META_LEAVES_CONIFER_NO_DECAY = 5, + E_META_LEAVES_BIRCH_NO_DECAY = 6, + E_META_LEAVES_JUNGLE_NO_DECAY = 7, + E_META_LEAVES_APPLE_CHECK_DECAY = 8, + E_META_LEAVES_CONIFER_CHECK_DECAY = 9, + E_META_LEAVES_BIRCH_CHECK_DECAY = 10, + E_META_LEAVES_JUNGLE_CHECK_DECAY = 11, + + // E_BLOCK_LEAVES meta cont. (Block ID 161): + E_META_NEWLEAVES_ACACIA = 0, + E_META_NEWLEAVES_DARK_OAK = 1, + E_META_NEWLEAVES_ACACIA_NO_DECAY = 4, + E_META_NEWLEAVES_DARK_OAK_NO_DECAY = 5, + E_META_NEWLEAVES_ACACIA_CHECK_DECAY = 8, + E_META_NEWLEAVES_DARK_OAK_CHECK_DECAY = 9, // E_BLOCK_LOG metas: E_META_LOG_APPLE = 0, @@ -540,9 +588,19 @@ enum E_META_NEW_LEAVES_DARK_OAK_WOOD = 1, // E_BLOCK_NEW_LOG metas: - E_META_NEW_LOG_ACACIA_WOOD = 0, - E_META_NEW_LOG_DARK_OAK_WOOD = 1, + E_META_NEW_LOG_ACACIA_WOOD = 0, + E_META_NEW_LOG_DARK_OAK_WOOD = 1, + // E_BLOCK_PISTON metas: + E_META_PISTON_DOWN = 0, + E_META_PISTON_U = 1, + E_META_PISTON_ZM = 2, + E_META_PISTON_ZP = 3, + E_META_PISTON_XM = 4, + E_META_PISTON_XP = 5, + E_META_PISTON_HEAD_STICKY = 8, + E_META_PISTON_EXTENDED = 8, + // E_BLOCK_PLANKS metas: E_META_PLANKS_APPLE = 0, E_META_PLANKS_CONIFER = 1, @@ -552,7 +610,7 @@ enum E_META_PLANKS_DARK_OAK = 5, // E_BLOCK_(XXX_WEIGHTED)_PRESSURE_PLATE metas: - E_META_PRESSURE_PLATE_RAISED = 0, + E_META_PRESSURE_PLATE_RAISED = 0, E_META_PRESSURE_PLATE_DEPRESSED = 1, // E_BLOCK_PRISMARINE_BLOCK metas: @@ -561,21 +619,21 @@ enum E_META_PRISMARINE_BLOCK_DARK = 2, // E_BLOCK_QUARTZ_BLOCK metas: - E_META_QUARTZ_NORMAL = 0, + E_META_QUARTZ_NORMAL = 0, E_META_QUARTZ_CHISELLED = 1, - E_META_QUARTZ_PILLAR = 2, - - // E_BLOCK_RAIL metas: - E_META_RAIL_ZM_ZP = 0, - E_META_RAIL_XM_XP = 1, - E_META_RAIL_ASCEND_XP = 2, - E_META_RAIL_ASCEND_XM = 3, - E_META_RAIL_ASCEND_ZM = 4, - E_META_RAIL_ASCEND_ZP = 5, - E_META_RAIL_CURVED_ZP_XP = 6, - E_META_RAIL_CURVED_ZP_XM = 7, - E_META_RAIL_CURVED_ZM_XM = 8, - E_META_RAIL_CURVED_ZM_XP = 9, + E_META_QUARTZ_PILLAR = 2, + + // E_BLOCK_RAIL metas + E_META_RAIL_ZM_ZP = 0, + E_META_RAIL_XM_XP = 1, + E_META_RAIL_ASCEND_XP = 2, + E_META_RAIL_ASCEND_XM = 3, + E_META_RAIL_ASCEND_ZM = 4, + E_META_RAIL_ASCEND_ZP = 5, + E_META_RAIL_CURVED_ZP_XP = 6, + E_META_RAIL_CURVED_ZP_XM = 7, + E_META_RAIL_CURVED_ZM_XM = 8, + E_META_RAIL_CURVED_ZM_XP = 9, // E_BLOCK_RED_SANDSTONE metas: E_META_RED_SANDSTONE_NORMAL = 0, @@ -668,8 +726,15 @@ enum E_META_STAINED_GLASS_PANE_RED = 14, E_META_STAINED_GLASS_PANE_BLACK = 15, + // E_BLOCK_STAIRS metas: + E_BLOCK_STAIRS_XP = 0, + E_BLOCK_STAIRS_XM = 1, + E_BLOCK_STAIRS_ZP = 2, + E_BLOCK_STAIRS_ZM = 3, + E_BLOCK_STAIRS_UPSIDE_DOWN = 4, + // E_BLOCK_STONE metas: - E_META_STONE = 0, + E_META_STONE_STONE = 0, E_META_STONE_GRANITE = 1, E_META_STONE_POLISHED_GRANITE = 2, E_META_STONE_DIORITE = 3, @@ -685,18 +750,19 @@ enum E_META_STONE_SLAB_BRICK = 4, E_META_STONE_SLAB_STONE_BRICK = 5, E_META_STONE_SLAB_NETHER_BRICK = 6, - E_META_STONE_SLAB_STONE_SECRET = 7, + E_META_STONE_SLAB_QUARTZ = 7, // E_BLOCK_STONE_BRICKS metas: - E_META_STONE_BRICK_NORMAL = 0, - E_META_STONE_BRICK_MOSSY = 1, - E_META_STONE_BRICK_CRACKED = 2, - E_META_STONE_BRICK_ORNAMENT = 3, + E_META_STONE_BRICK_NORMAL = 0, + E_META_STONE_BRICK_MOSSY = 1, + E_META_STONE_BRICK_CRACKED = 2, + E_META_STONE_BRICK_ORNAMENT = 3, // E_BLOCK_TALL_GRASS metas: E_META_TALL_GRASS_DEAD_SHRUB = 0, E_META_TALL_GRASS_GRASS = 1, E_META_TALL_GRASS_FERN = 2, + E_META_TALL_GRASS_BIOME = 3, // E_BLOCK_TORCH, E_BLOCK_REDSTONE_TORCH_OFF, E_BLOCK_REDSTONE_TORCH_ON metas: E_META_TORCH_EAST = 1, // east face of the block, pointing east @@ -704,26 +770,55 @@ enum E_META_TORCH_SOUTH = 3, E_META_TORCH_NORTH = 4, E_META_TORCH_FLOOR = 5, - E_META_TORCH_XM = 1, // Torch attached to the XM side of its block - E_META_TORCH_XP = 2, // Torch attached to the XP side of its block - E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block - E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block - + E_META_TORCH_XM = 1, // Torch attached to the XM side of its block + E_META_TORCH_XP = 2, // Torch attached to the XP side of its block + E_META_TORCH_ZM = 3, // Torch attached to the ZM side of its block + E_META_TORCH_ZP = 4, // Torch attached to the ZP side of its block + + // E_META_LOG metas: + E_META_LOG_OAK_UP_DOWN = 0, + E_META_LOG_SPRUCE_UP_DOWN = 1, + E_META_LOG_BIRCH_UP_DOWN = 2, + E_META_LOG_JUNGLE_UP_DOWN = 3, + E_META_LOG_OAK_X = 4, + E_META_LOG_SPRUCE_X = 5, + E_META_LOG_BIRCH_X = 6, + E_META_LOG_JUNGLE_X = 7, + E_META_LOG_OAK_Z = 8, + E_META_LOG_SPRUCE_Z = 9, + E_META_LOG_BIRCH_Z = 10, + E_META_LOG_JUNGLE_Z = 11, + E_META_LOG_OAK_BARK_ONLY = 12, + E_META_LOG_SPRUCE_BARK_ONLY = 13, + E_META_LOG_BIRCH_BARK_ONLY = 14, + E_META_LOG_JUNGLE_BARK_ONLY = 15, + + // E_META_LOG metas cont. (Block ID 162): + E_META_NEWLOG_ACACIA_UP_DOWN = 0, + E_META_NEWLOG_DARK_OAK_UP_DOWN = 1, + E_META_NEWLOG_ACACIA_X = 4, + E_META_NEWLOG_DARK_OAK_X = 5, + E_META_NEWLOG_ACACIA_Z = 8, + E_META_NEWLOG_DARK_OAK_Z = 9, + E_META_NEWLOG_ACACIA_BARK_ONLY = 12, + E_META_NEWLOG_DARK_OAK_BARK_ONLY = 13, + // E_BLOCK_WOODEN_DOUBLE_SLAB metas: - E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, - E_META_WOODEN_DOUBLE_SLAB_CONIFER = 1, - E_META_WOODEN_DOUBLE_SLAB_BIRCH = 2, - E_META_WOODEN_DOUBLE_SLAB_JUNGLE = 3, - E_META_WOODEN_DOUBLE_SLAB_ACACIA = 4, - E_META_WOODEN_DOUBLE_SLAB_DARK_OAK = 5, + E_META_WOODEN_DOUBLE_SLAB_APPLE = 0, + E_META_WOODEN_DOUBLE_SLAB_CONIFER = 1, + E_META_WOODEN_DOUBLE_SLAB_BIRCH = 2, + E_META_WOODEN_DOUBLE_SLAB_JUNGLE = 3, + E_META_WOODEN_DOUBLE_SLAB_ACACIA = 4, + E_META_WOODEN_DOUBLE_SLAB_DARK_OAK = 5, // E_BLOCK_WOODEN_SLAB metas: - E_META_WOODEN_SLAB_APPLE = 0, - E_META_WOODEN_SLAB_CONIFER = 1, - E_META_WOODEN_SLAB_BIRCH = 2, - E_META_WOODEN_SLAB_JUNGLE = 3, - E_META_WOODEN_SLAB_ACACIA = 4, - E_META_WOODEN_SLAB_DARK_OAK = 5, + E_META_WOODEN_SLAB_APPLE = 0, + E_META_WOODEN_SLAB_CONIFER = 1, + E_META_WOODEN_SLAB_BIRCH = 2, + E_META_WOODEN_SLAB_JUNGLE = 3, + E_META_WOODEN_SLAB_ACACIA = 4, + E_META_WOODEN_SLAB_DARK_OAK = 5, + E_META_WOODEN_SLAB_UPSIDE_DOWN = 8, // E_BLOCK_WOOL metas: E_META_WOOL_WHITE = 0, @@ -1005,9 +1100,6 @@ extern AString ItemTypeToString(short a_ItemType); /// Translates a full item into a fully-specified string (including meta and count). If the ItemType is not recognized, the ItemType number is output into the string. extern AString ItemToFullString(const cItem & a_Item); -/// Translates a mob string ("ocelot") to mobtype (E_ENTITY_TYPE_OCELOT) -extern int StringToMobType(const AString & a_MobString); - /// Translates a dimension string to dimension enum. Takes either a number or a dimension alias (built-in). Returns dimOverworld on failure extern eDimension StringToDimension(const AString & a_DimensionString); 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 5e30514e2..bdd3a9c26 100644 --- a/src/BlockInfo.cpp +++ b/src/BlockInfo.cpp @@ -535,6 +535,7 @@ void cBlockInfo::Initialize(cBlockInfoArray & a_Info) a_Info[E_BLOCK_LAPIS_ORE ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_LOG ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MELON ].m_FullyOccupiesVoxel = true; + a_Info[E_BLOCK_MOB_SPAWNER ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MOSSY_COBBLESTONE ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_MYCELIUM ].m_FullyOccupiesVoxel = true; a_Info[E_BLOCK_NETHERRACK ].m_FullyOccupiesVoxel = true; diff --git a/src/Blocks/BlockDirt.h b/src/Blocks/BlockDirt.h index 19f889372..89dfc963d 100644 --- a/src/Blocks/BlockDirt.h +++ b/src/Blocks/BlockDirt.h @@ -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 ff0b201e7..b6ef5dd6f 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" @@ -36,7 +37,6 @@ #include "BlockGlass.h" #include "BlockGlowstone.h" #include "BlockGravel.h" -#include "BlockHayBale.h" #include "BlockMobHead.h" #include "BlockHopper.h" #include "BlockIce.h" @@ -83,7 +83,6 @@ #include "BlockWorkbench.h" -#include "BlockPluginInterface.h" @@ -231,7 +230,7 @@ cBlockHandler * cBlockHandler::CreateBlockHandler(BLOCKTYPE a_BlockType) case E_BLOCK_GLASS_PANE: return new cBlockGlassHandler (a_BlockType); case E_BLOCK_GRASS: return new cBlockDirtHandler (a_BlockType); case E_BLOCK_GRAVEL: return new cBlockGravelHandler (a_BlockType); - case E_BLOCK_HAY_BALE: return new cBlockHayBaleHandler (a_BlockType); + case E_BLOCK_HAY_BALE: return new cBlockSidewaysHandler (a_BlockType); case E_BLOCK_HEAD: return new cBlockMobHeadHandler (a_BlockType); case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE: return new cBlockPressurePlateHandler(a_BlockType); case E_BLOCK_HOPPER: return new cBlockHopperHandler (a_BlockType); diff --git a/src/Blocks/BlockHayBale.h b/src/Blocks/BlockHayBale.h deleted file mode 100644 index 8150b10d3..000000000 --- a/src/Blocks/BlockHayBale.h +++ /dev/null @@ -1,22 +0,0 @@ - -#pragma once - -#include "BlockSideways.h" - - - - - -class cBlockHayBaleHandler : - public cBlockSidewaysHandler -{ -public: - cBlockHayBaleHandler(BLOCKTYPE a_BlockType) - : cBlockSidewaysHandler(a_BlockType) - { - } -} ; - - - - 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/BlockStone.h b/src/Blocks/BlockStone.h index e52599c0f..69cc8301b 100644 --- a/src/Blocks/BlockStone.h +++ b/src/Blocks/BlockStone.h @@ -18,7 +18,7 @@ public: virtual void ConvertToPickups(cItems & a_Pickups, NIBBLETYPE a_BlockMeta) override { - if (a_BlockMeta == E_META_STONE) + if (a_BlockMeta == E_META_STONE_STONE) { a_Pickups.push_back(cItem(E_BLOCK_COBBLESTONE, 1, 0)); return; diff --git a/src/Blocks/BlockTorch.h b/src/Blocks/BlockTorch.h index dd252f2a4..e77bbd1b8 100644 --- a/src/Blocks/BlockTorch.h +++ b/src/Blocks/BlockTorch.h @@ -24,32 +24,23 @@ public: BLOCKTYPE & a_BlockType, NIBBLETYPE & a_BlockMeta ) override { - // Find proper placement of torch + BLOCKTYPE Block; + NIBBLETYPE Meta; + AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, true); // Set to clicked block + a_ChunkInterface.GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, Block, Meta); - if ((a_BlockFace == BLOCK_FACE_TOP) || (a_BlockFace == BLOCK_FACE_BOTTOM)) + if (!CanBePlacedOn(Block, Meta, a_BlockFace)) // Try to preserve original direction { - a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); // Top or bottom faces clicked, find a suitable face + // Torch couldn't be placed on whatever face was clicked, last ditch resort - find another face + + AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, false); // Reset to torch block + a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); // Set a_BlockFace to a valid direction which will be converted later to a metadata if (a_BlockFace == BLOCK_FACE_NONE) { - // Client wouldn't have sent anything anyway, but whatever + // No attachable face found - don't place the torch return false; } } - else - { - // Not top or bottom faces, try to preserve whatever face was clicked - AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, true); // Set to clicked block - if (!CanBePlacedOn(a_ChunkInterface.GetBlock(a_BlockX, a_BlockY, a_BlockZ), a_BlockFace)) - { - AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, a_BlockFace, false); // Reset to torch block - // Torch couldn't be placed on whatever face was clicked, last ditch resort - find another face - a_BlockFace = FindSuitableFace(a_ChunkInterface, a_BlockX, a_BlockY, a_BlockZ); - if (a_BlockFace == BLOCK_FACE_NONE) - { - return false; - } - } - } a_BlockType = m_BlockType; a_BlockMeta = DirectionToMetaData(a_BlockFace); @@ -97,46 +88,57 @@ public: } - static bool CanBePlacedOn(BLOCKTYPE a_BlockType, eBlockFace a_BlockFace) + static bool CanBePlacedOn(BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta, eBlockFace a_BlockFace) { - if (!cBlockInfo::FullyOccupiesVoxel(a_BlockType)) - { - return (a_BlockFace == BLOCK_FACE_TOP); // Allow placement only when torch upright (for glass, etc.); exceptions won't even be sent by client, no need to handle - } - else + switch (a_BlockType) { - return true; + case E_BLOCK_END_PORTAL_FRAME: + case E_BLOCK_SOULSAND: + { + // Exceptional vanilla behaviour + return true; + } + case E_BLOCK_GLASS: + case E_BLOCK_STAINED_GLASS: + case E_BLOCK_FENCE: + case E_BLOCK_NETHER_BRICK_FENCE: + case E_BLOCK_COBBLESTONE_WALL: + { + // Torches can only be placed on top of these blocks + return (a_BlockFace == BLOCK_FACE_YP); + } + case E_BLOCK_STONE_SLAB: + case E_BLOCK_WOODEN_SLAB: + { + // Toches can be placed on the top of these slabs only if the occupy the top half of the voxel + return ((a_BlockFace == BLOCK_FACE_YP) && ((a_BlockMeta & 0x08) == 0x08)); + } + default: + { + if (cBlockInfo::FullyOccupiesVoxel(a_BlockType)) + { + // Torches can be placed on all sides of full blocks except the bottom + return (a_BlockFace != BLOCK_FACE_YM); + } + return false; + } } } - /// Finds a suitable face to place the torch, returning BLOCK_FACE_NONE on failure + /** Finds a suitable face to place the torch, returning BLOCK_FACE_NONE on failure */ static eBlockFace FindSuitableFace(cChunkInterface & a_ChunkInterface, int a_BlockX, int a_BlockY, int a_BlockZ) { for (int i = BLOCK_FACE_YM; i <= BLOCK_FACE_XP; i++) // Loop through all directions { eBlockFace Face = static_cast<eBlockFace>(i); AddFaceDirection(a_BlockX, a_BlockY, a_BlockZ, Face, true); - BLOCKTYPE BlockInQuestion = a_ChunkInterface.GetBlock(a_BlockX, a_BlockY, a_BlockZ); - - // If on a block that can only hold a torch if torch is standing on it, return that face - if ( - ( - (BlockInQuestion == E_BLOCK_GLASS) || - (BlockInQuestion == E_BLOCK_FENCE) || - (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) - ) && - (Face == BLOCK_FACE_TOP) - ) - { - return Face; - } - else if (cBlockInfo::FullyOccupiesVoxel(BlockInQuestion) && (i != BLOCK_FACE_BOTTOM)) + BLOCKTYPE BlockInQuestion; + NIBBLETYPE BlockInQuestionMeta; + a_ChunkInterface.GetBlockTypeMeta(a_BlockX, a_BlockY, a_BlockZ, BlockInQuestion, BlockInQuestionMeta); + + if (CanBePlacedOn(BlockInQuestion, BlockInQuestionMeta, Face)) { - // Otherwise, if block in that direction is torch placeable and we haven't gotten to it via the bottom face, return that face return Face; } else @@ -152,36 +154,16 @@ public: virtual bool CanBeAt(cChunkInterface & a_ChunkInterface, int a_RelX, int a_RelY, int a_RelZ, const cChunk & a_Chunk) override { eBlockFace Face = MetaDataToDirection(a_Chunk.GetMeta(a_RelX, a_RelY, a_RelZ)); - AddFaceDirection(a_RelX, a_RelY, a_RelZ, Face, true); + BLOCKTYPE BlockInQuestion; - a_Chunk.UnboundedRelGetBlockType(a_RelX, a_RelY, a_RelZ, BlockInQuestion); - - if ( - (BlockInQuestion == E_BLOCK_GLASS) || - (BlockInQuestion == E_BLOCK_STAINED_GLASS) || - (BlockInQuestion == E_BLOCK_FENCE) || - (BlockInQuestion == E_BLOCK_SOULSAND) || - (BlockInQuestion == E_BLOCK_MOB_SPAWNER) || - (BlockInQuestion == E_BLOCK_END_PORTAL_FRAME) || // Actual vanilla behaviour - (BlockInQuestion == E_BLOCK_NETHER_BRICK_FENCE) || - (BlockInQuestion == E_BLOCK_COBBLESTONE_WALL) || - (BlockInQuestion == E_BLOCK_STONE_SLAB) || - (BlockInQuestion == E_BLOCK_WOODEN_SLAB) - ) - { - // Torches can be placed on tops of glass and fences, despite them being 'untorcheable' - // No need to check for upright orientation, it was done when the torch was placed - return true; - } - else if (!cBlockInfo::FullyOccupiesVoxel(BlockInQuestion)) + NIBBLETYPE BlockInQuestionMeta; + if (!a_Chunk.UnboundedRelGetBlock(a_RelX, a_RelY, a_RelZ, BlockInQuestion, BlockInQuestionMeta)) { return false; } - else - { - return true; - } + + return CanBePlacedOn(BlockInQuestion, BlockInQuestionMeta, Face); } diff --git a/src/Blocks/BlockVine.h b/src/Blocks/BlockVine.h index 06d84f2d4..213324cc1 100644 --- a/src/Blocks/BlockVine.h +++ b/src/Blocks/BlockVine.h @@ -166,23 +166,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/CMakeLists.txt b/src/Blocks/CMakeLists.txt index 9f971a8bd..eed949aab 100644 --- a/src/Blocks/CMakeLists.txt +++ b/src/Blocks/CMakeLists.txt @@ -45,7 +45,6 @@ SET (HDRS BlockGlowstone.h BlockGravel.h BlockHandler.h - BlockHayBale.h BlockHopper.h BlockIce.h BlockLadder.h 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 98c8bc66a..d03e0bf21 100644 --- a/src/Chunk.cpp +++ b/src/Chunk.cpp @@ -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()); @@ -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) { diff --git a/src/Chunk.h b/src/Chunk.h index 8e13ff00e..c50be263f 100644 --- a/src/Chunk.h +++ b/src/Chunk.h @@ -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); diff --git a/src/ChunkMap.cpp b/src/ChunkMap.cpp index 299fe0eca..6f56b23e0 100644 --- a/src/ChunkMap.cpp +++ b/src/ChunkMap.cpp @@ -954,7 +954,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); } @@ -1145,11 +1145,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); @@ -2973,7 +2973,7 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) if ( (m_Chunks[i] != NULL) && // 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 @@ -2987,6 +2987,8 @@ void cChunkMap::cChunkLayer::UnloadUnusedChunks(void) + + void cChunkMap::FastSetBlock(int a_BlockX, int a_BlockY, int a_BlockZ, BLOCKTYPE a_BlockType, NIBBLETYPE a_BlockMeta) { cCSLock Lock(m_CSFastSetBlock); diff --git a/src/ChunkMap.h b/src/ChunkMap.h index 6e92833f1..38e7f4052 100644 --- a/src/ChunkMap.h +++ b/src/ChunkMap.h @@ -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); diff --git a/src/ClientHandle.cpp b/src/ClientHandle.cpp index 359255a3e..f15d845ef 100644 --- a/src/ClientHandle.cpp +++ b/src/ClientHandle.cpp @@ -92,7 +92,8 @@ cClientHandle::cClientHandle(const cSocket * a_Socket, int a_ViewDistance) : m_NumBlockChangeInteractionsThisTick(0), m_UniqueID(0), m_HasSentPlayerChunk(false), - m_Locale("en_GB") + m_Locale("en_GB"), + m_ProtocolVersion(0) { m_Protocol = new cProtocolRecognizer(this); @@ -247,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", @@ -536,9 +540,11 @@ void cClientHandle::RemoveFromAllChunks() } { + // 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) @@ -583,15 +589,22 @@ void cClientHandle::HandlePing(void) bool cClientHandle::HandleLogin(int a_ProtocolVersion, const AString & a_Username) { + // If the protocol version hasn't been set yet, set it now: + if (m_ProtocolVersion == 0) + { + m_ProtocolVersion = a_ProtocolVersion; + } + m_Username = a_Username; - if (cRoot::Get()->GetPluginManager()->CallHookLogin(this, a_ProtocolVersion, a_Username)) + // Let the plugins know about this event, they may refuse the player: + if (cRoot::Get()->GetPluginManager()->CallHookLogin(*this, a_ProtocolVersion, a_Username)) { Destroy(); return false; } - // Schedule for authentication; until then, let them wait (but do not block) + // Schedule for authentication; until then, let the player wait (but do not block) m_State = csAuthenticating; cRoot::Get()->GetAuthenticator().Authenticate(GetUniqueID(), GetUsername(), m_Protocol->GetAuthServerID()); return true; @@ -1704,7 +1717,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()) { @@ -2016,7 +2029,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); + } } @@ -2026,8 +2049,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); + } } @@ -2091,6 +2121,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)) { @@ -2620,6 +2656,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); } diff --git a/src/ClientHandle.h b/src/ClientHandle.h index 674a8cafd..9733ff32d 100644 --- a/src/ClientHandle.h +++ b/src/ClientHandle.h @@ -316,6 +316,12 @@ public: /** Called when the player will enchant a Item */ void HandleEnchantItem(Byte & a_WindowID, Byte & a_Enchantment); + + /** Called by the protocol recognizer when the protocol version is known. */ + void SetProtocolVersion(UInt32 a_ProtocolVersion) { m_ProtocolVersion = a_ProtocolVersion; } + + /** Returns the protocol version number of the protocol that the client is talking. Returns zero if the protocol version is not (yet) known. */ + UInt32 GetProtocolVersion(void) const { return m_ProtocolVersion; } // tolua_export private: @@ -337,6 +343,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; // Store the coordinates of the chunks that the client has loaded cProtocol * m_Protocol; @@ -427,6 +434,9 @@ private: /** The brand identification of the client, as received in the MC|Brand plugin message or set from a plugin. */ AString m_ClientBrand; + /** The version of the protocol that the client is talking, or 0 if unknown. */ + UInt32 m_ProtocolVersion; + /** Handles the block placing packet when it is a real block placement (not block-using, item-using or eating) */ void HandlePlaceBlock(int a_BlockX, int a_BlockY, int a_BlockZ, eBlockFace a_BlockFace, int a_CursorX, int a_CursorY, int a_CursorZ, cItemHandler & a_ItemHandler); diff --git a/src/CraftingRecipes.cpp b/src/CraftingRecipes.cpp index ed3409207..0828a6c74 100644 --- a/src/CraftingRecipes.cpp +++ b/src/CraftingRecipes.cpp @@ -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; } @@ -294,7 +294,7 @@ void cCraftingRecipes::GetRecipe(const cPlayer * a_Player, const cCraftingGrid & if (Recipe.get() == NULL) { // 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); } diff --git a/src/CraftingRecipes.h b/src/CraftingRecipes.h index fe1e15817..5ebabe098 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: 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..7e429c62e 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; } @@ -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..1e4d8eebb 100644 --- a/src/Entities/ArrowEntity.h +++ b/src/Entities/ArrowEntity.h @@ -97,7 +97,7 @@ 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 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/Entity.h b/src/Entities/Entity.h index 3fa7e80c1..f0577aba2 100644 --- a/src/Entities/Entity.h +++ b/src/Entities/Entity.h @@ -27,9 +27,9 @@ return super::GetClass(); \ } -#define POSX_TOINT (int)floor(GetPosX()) -#define POSY_TOINT (int)floor(GetPosY()) -#define POSZ_TOINT (int)floor(GetPosZ()) +#define POSX_TOINT FloorC(GetPosX()) +#define POSY_TOINT FloorC(GetPosY()) +#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; } diff --git a/src/Entities/Minecart.h b/src/Entities/Minecart.h index 6b6ad36b5..ab906fd06 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: 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..b3cbeee0b 100644 --- a/src/Entities/Pickup.h +++ b/src/Entities/Pickup.h @@ -32,7 +32,7 @@ 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; diff --git a/src/Entities/Player.cpp b/src/Entities/Player.cpp index 86ee4a32d..6bd0a3d20 100644 --- a/src/Entities/Player.cpp +++ b/src/Entities/Player.cpp @@ -245,7 +245,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())) { diff --git a/src/Entities/ProjectileEntity.cpp b/src/Entities/ProjectileEntity.cpp index acc9bd674..ab25ac30c 100644 --- a/src/Entities/ProjectileEntity.cpp +++ b/src/Entities/ProjectileEntity.cpp @@ -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..03eda9739 100644 --- a/src/Entities/ProjectileEntity.h +++ b/src/Entities/ProjectileEntity.h @@ -59,7 +59,7 @@ public: } /// Called by Chunk when the projectile is eligible for player collection - virtual void CollectedBy(cPlayer * a_Dest); + virtual void CollectedBy(cPlayer & a_Dest); // tolua_begin diff --git a/src/Generating/BioGen.cpp b/src/Generating/BioGen.cpp index 8924a7999..9b3d4e98d 100644 --- a/src/Generating/BioGen.cpp +++ b/src/Generating/BioGen.cpp @@ -760,8 +760,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); diff --git a/src/Generating/ComposableGenerator.cpp b/src/Generating/ComposableGenerator.cpp index 4efcd1284..87461b944 100644 --- a/src/Generating/ComposableGenerator.cpp +++ b/src/Generating/ComposableGenerator.cpp @@ -422,7 +422,7 @@ void cComposableGenerator::InitFinishGens(cIniFile & a_IniFile) // Gravel vein cStructGenOreNests::OreInfo GravelVein; - GravelVein.BlockType = E_BLOCK_DIRT; + GravelVein.BlockType = E_BLOCK_GRAVEL; GravelVein.MaxHeight = 127; GravelVein.NumNests = 20; GravelVein.NestSize = 32; diff --git a/src/Generating/DistortedHeightmap.cpp b/src/Generating/DistortedHeightmap.cpp index c18c402da..bf8995dcb 100644 --- a/src/Generating/DistortedHeightmap.cpp +++ b/src/Generating/DistortedHeightmap.cpp @@ -540,10 +540,11 @@ void cDistortedHeightmap::InitializeCompoGen(cIniFile & a_IniFile) int cDistortedHeightmap::GetHeightmapAt(NOISE_DATATYPE a_X, NOISE_DATATYPE a_Z) { - int ChunkX = (int)floor(a_X / (NOISE_DATATYPE)16); - int ChunkZ = (int)floor(a_Z / (NOISE_DATATYPE)16); - int RelX = (int)(a_X - (NOISE_DATATYPE)ChunkX * cChunkDef::Width); - int RelZ = (int)(a_Z - (NOISE_DATATYPE)ChunkZ * cChunkDef::Width); + int RelX = (int)std::floor(a_X); + int RelY = 0; + int RelZ = (int)std::floor(a_Z); + int ChunkX, ChunkZ; + cChunkDef::AbsoluteToRelative(RelX, RelY, RelZ, ChunkX, ChunkZ); // If we're withing the same chunk, return the pre-cached heightmap: if ((ChunkX == m_CurChunkX) && (ChunkZ == m_CurChunkZ)) diff --git a/src/Generating/DungeonRoomsFinisher.cpp b/src/Generating/DungeonRoomsFinisher.cpp index f213455d6..492bae129 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 != NULL) && (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 diff --git a/src/Generating/Trees.cpp b/src/Generating/Trees.cpp index 1b0f2dc14..7fd6d6f07 100644 --- a/src/Generating/Trees.cpp +++ b/src/Generating/Trees.cpp @@ -224,8 +224,6 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No case biMegaTaiga: case biMegaTaigaHills: case biExtremeHillsPlus: - case biSavanna: - case biSavannaPlateau: case biMesa: case biMesaPlateauF: case biMesaPlateau: @@ -241,8 +239,6 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No case biMegaSpruceTaiga: case biMegaSpruceTaigaHills: case biExtremeHillsPlusM: - case biSavannaM: - case biSavannaPlateauM: case biMesaBryce: case biMesaPlateauFM: case biMesaPlateauM: @@ -252,6 +248,15 @@ void GetTreeImageByBiome(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_No return; } + case biSavanna: + case biSavannaPlateau: + case biSavannaM: + case biSavannaPlateauM: + { + GetAcaciaTreeImage(a_BlockX, a_BlockY, a_BlockZ, a_Noise, a_Seq, a_LogBlocks, a_OtherBlocks); + return; + } + case biRoofedForest: case biRoofedForestM: { @@ -403,7 +408,72 @@ void GetBirchTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Nois void GetAcaciaTreeImage(int a_BlockX, int a_BlockY, int a_BlockZ, cNoise & a_Noise, int a_Seq, sSetBlockVector & a_LogBlocks, sSetBlockVector & a_OtherBlocks) { - // TODO + // Calculate a base height + int Height = 2 + (a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) / 11 % 3); + + // Create the trunk + for (int i = 0; i < Height; i++) + { + a_LogBlocks.push_back(sSetBlock(a_BlockX, a_BlockY + i, a_BlockZ, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + // Array with possible directions for a branch to go to. + const Vector3i AvailableDirections[] = + { + { -1, 1, 0 }, { 0, 1, -1 }, + { -1, 1, 1 }, { -1, 1, -1 }, + { 1, 1, 1 }, { 1, 1, -1 }, + { 1, 1, 0 }, { 0, 1, 1 }, + }; + + // Set the starting point of the branch + Vector3i BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + + // Get a direction for the trunk to go to. + Vector3i BranchDirection = AvailableDirections[a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 8]; + + // Calculate a height for the branch between 1 and 3 + int BranchHeight = a_Noise.IntNoise3DInt(a_BlockX, a_BlockY, a_BlockZ) % 3 + 1; + + // Place the logs of the branch. + for (int i = 0; i < BranchHeight; i++) + { + BranchPos = BranchPos + BranchDirection; + a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + // Add the leaves to the top of the branch + PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); + + // Choose if we have to add another branch + bool TwoTop = (a_Noise.IntNoise3D(a_BlockX, a_BlockY, a_BlockZ) < 0 ? true : false); + if (!TwoTop) + { + return; + } + + // Reset the starting point of the branch + BranchPos = Vector3i(a_BlockX, a_BlockY + Height - 1, a_BlockZ); + + // Invert the direction of the previous branch. + BranchDirection = Vector3d(-BranchDirection.x, 1, -BranchDirection.z); + + // Calculate a new height for the second branch + BranchHeight = a_Noise.IntNoise3DInt(a_BlockX * a_Seq, a_BlockY * a_Seq * 10, a_BlockZ * a_Seq) % 3 + 1; + + // Place the logs in the same way as the first branch + for (int i = 0; i < BranchHeight; i++) + { + BranchPos = BranchPos + BranchDirection; + a_LogBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y, BranchPos.z, E_BLOCK_NEW_LOG, E_META_NEW_LOG_ACACIA_WOOD)); + } + + // And add the leaves ontop of the second branch + PushCoordBlocks(BranchPos.x, BranchPos.y, BranchPos.z, a_OtherBlocks, BigO2, ARRAYCOUNT(BigO2), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + PushCoordBlocks(BranchPos.x, BranchPos.y + 1, BranchPos.z, a_OtherBlocks, BigO1, ARRAYCOUNT(BigO1), E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD); + a_OtherBlocks.push_back(sSetBlock(BranchPos.x, BranchPos.y + 1, BranchPos.z, E_BLOCK_NEW_LEAVES, E_META_NEW_LEAVES_ACACIA_WOOD)); } diff --git a/src/Globals.h b/src/Globals.h index 0926457da..b84607355 100644 --- a/src/Globals.h +++ b/src/Globals.h @@ -51,6 +51,9 @@ #define NORETURN __declspec(noreturn) + // Use non-standard defines in <cmath> + #define _USE_MATH_DEFINES + #elif defined(__GNUC__) // TODO: Can GCC explicitly mark classes as abstract (no instances can be created)? @@ -226,10 +229,10 @@ template class SizeChecker<UInt16, 2>; // CRT stuff: #include <sys/stat.h> -#include <assert.h> -#include <stdio.h> -#include <math.h> -#include <stdarg.h> +#include <cassert> +#include <cstdio> +#include <cmath> +#include <cstdarg> @@ -400,6 +403,30 @@ T Clamp(T a_Value, T a_Min, T a_Max) +/** Floors a value, then casts it to C (an int by default) */ +template <typename C = int, typename T> +typename std::enable_if<std::is_arithmetic<T>::value, C>::type FloorC(T a_Value) +{ + return static_cast<C>(std::floor(a_Value)); +} + +/** Ceils a value, then casts it to C (an int by default) */ +template <typename C = int, typename T> +typename std::enable_if<std::is_arithmetic<T>::value, C>::type CeilC(T a_Value) +{ + return static_cast<C>(std::ceil(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 #define TOLUA_TEMPLATE_BIND(x) #endif @@ -415,3 +442,4 @@ T Clamp(T a_Value, T a_Min, T a_Max) #include "BlockInfo.h" + diff --git a/src/ItemGrid.cpp b/src/ItemGrid.cpp index 2344dc0a5..0bd44bb0d 100644 --- a/src/ItemGrid.cpp +++ b/src/ItemGrid.cpp @@ -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/Mobs/CMakeLists.txt b/src/Mobs/CMakeLists.txt index 2c092c15f..bbbb9287a 100644 --- a/src/Mobs/CMakeLists.txt +++ b/src/Mobs/CMakeLists.txt @@ -54,6 +54,7 @@ SET (HDRS IronGolem.h MagmaCube.h Monster.h + MonsterTypes.h Mooshroom.h Ocelot.h PassiveAggressiveMonster.h diff --git a/src/Mobs/Monster.cpp b/src/Mobs/Monster.cpp index 12ca6bbbe..73dbcb3c3 100644 --- a/src/Mobs/Monster.cpp +++ b/src/Mobs/Monster.cpp @@ -62,6 +62,16 @@ static const struct +eMonsterType StringToMobType(const AString & a_MobString) +{ + LOGWARNING("%s: Function is obsolete, use cMonster::StringToMobType() instead", __FUNCTION__); + return cMonster::StringToMobType(a_MobString); +} + + + + + //////////////////////////////////////////////////////////////////////////////// // cMonster: diff --git a/src/Mobs/Monster.h b/src/Mobs/Monster.h index a1f9c4a5b..9fd67d67c 100644 --- a/src/Mobs/Monster.h +++ b/src/Mobs/Monster.h @@ -25,9 +25,6 @@ class cMonster : typedef cPawn super; public: - // Deprecated - typedef eMonsterType eType; - enum eFamily { mfHostile = 0, // Spider, Zombies ... diff --git a/src/Mobs/MonsterTypes.h b/src/Mobs/MonsterTypes.h index 7a73e99f4..852eb3446 100644 --- a/src/Mobs/MonsterTypes.h +++ b/src/Mobs/MonsterTypes.h @@ -37,5 +37,18 @@ enum eMonsterType mtZombie = E_META_SPAWN_EGG_ZOMBIE, mtZombiePigman = E_META_SPAWN_EGG_ZOMBIE_PIGMAN, } ; + + + + + +/** Translates a mob string ("ocelot") to mobtype (mtOcelot). +OBSOLETE, use cMonster::StringToMobType() instead. +Implemented in Monster.cpp. */ +extern eMonsterType StringToMobType(const AString & a_MobString); + // tolua_end + + + diff --git a/src/OSSupport/CMakeLists.txt b/src/OSSupport/CMakeLists.txt index a42fcbed4..429949c59 100644 --- a/src/OSSupport/CMakeLists.txt +++ b/src/OSSupport/CMakeLists.txt @@ -39,6 +39,6 @@ if(NOT MSVC) add_library(OSSupport ${SRCS} ${HDRS}) if(UNIX) - target_link_libraries(OSSupport pthread) + target_link_libraries(OSSupport pthread rt) endif() endif() diff --git a/src/OSSupport/Event.cpp b/src/OSSupport/Event.cpp index 74f823216..7cf8a826c 100644 --- a/src/OSSupport/Event.cpp +++ b/src/OSSupport/Event.cpp @@ -102,6 +102,53 @@ void cEvent::Wait(void) +bool cEvent::Wait(int a_TimeoutMSec) +{ + #ifdef _WIN32 + DWORD res = WaitForSingleObject(m_Event, (DWORD)a_TimeoutMSec); + switch (res) + { + case WAIT_OBJECT_0: return true; // Regular event signalled + case WAIT_TIMEOUT: return false; // Regular event timeout + default: + { + LOGWARN("cEvent: waiting for the event failed: %u, GLE = %u. Continuing, but server may be unstable.", (unsigned)res, (unsigned)GetLastError()); + return false; + } + } + #else + // Get the current time: + timespec timeout; + if (clock_gettime(CLOCK_REALTIME, &timeout) == -1) + { + LOGWARN("cEvent: Getting current time failed: %i, err = %s. Continuing, but the server may be unstable.", errno, GetOSErrorString(errno).c_str()); + return false; + } + + // Add the specified timeout: + timeout.tv_sec += a_TimeoutMSec / 1000; + timeout.tv_nsec += (a_TimeoutMSec % 1000) * 1000000; // 1 msec = 1000000 usec + + // Wait with timeout: + int res = sem_timedwait(m_Event, &timeout); + switch (res) + { + case 0: return true; // Regular event signalled + case ETIMEDOUT: return false; // Regular even timeout + default: + { + AString error = GetOSErrorString(errno); + LOGWARN("cEvent: waiting for the event failed: %i, err = %s. Continuing, but server may be unstable.", res, error.c_str()); + return false; + } + } + #endif +} + + + + + void cEvent::Set(void) { #ifdef _WIN32 diff --git a/src/OSSupport/Event.h b/src/OSSupport/Event.h index 71f418c0c..e2fa65a05 100644 --- a/src/OSSupport/Event.h +++ b/src/OSSupport/Event.h @@ -24,6 +24,10 @@ public: void Wait(void); void Set (void); + + /** Waits for the event until either it is signalled, or the (relative) timeout is passed. + Returns true if the event was signalled, false if the timeout was hit or there was an error. */ + bool Wait(int a_TimeoutMSec); private: diff --git a/src/Protocol/MojangAPI.cpp b/src/Protocol/MojangAPI.cpp index 28da83c31..a4b4dbd3b 100644 --- a/src/Protocol/MojangAPI.cpp +++ b/src/Protocol/MojangAPI.cpp @@ -11,6 +11,8 @@ #include "json/json.h" #include "PolarSSL++/BlockingSslClientSocket.h" #include "../RankManager.h" +#include "../OSSupport/IsThread.h" +#include "../Root.h" @@ -152,6 +154,41 @@ cMojangAPI::sProfile::sProfile( //////////////////////////////////////////////////////////////////////////////// +// cMojangAPI::cUpdateThread: + +class cMojangAPI::cUpdateThread : + public cIsThread +{ + typedef cIsThread super; +public: + cUpdateThread() : + super("cMojangAPI::cUpdateThread") + { + } + + ~cUpdateThread() + { + m_evtNotify.Set(); + Stop(); + } + +protected: + cEvent m_evtNotify; + + virtual void Execute(void) override + { + do + { + cRoot::Get()->GetMojangAPI().Update(); + } while (!m_evtNotify.Wait(60 * 60 * 1000)); // Repeat every 60 minutes + } +} ; + + + + + +//////////////////////////////////////////////////////////////////////////////// // cMojangAPI: cMojangAPI::cMojangAPI(void) : @@ -159,7 +196,8 @@ 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(NULL), + m_UpdateThread(new cUpdateThread()) { } @@ -176,13 +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(); + if (a_ShouldAuth) + { + m_UpdateThread->Start(); + } } @@ -465,21 +507,7 @@ void cMojangAPI::LoadCachesFromDisk(void) db.exec("CREATE TABLE IF NOT EXISTS PlayerNameToUUID (PlayerName, UUID, DateTime)"); db.exec("CREATE TABLE IF NOT EXISTS UUIDToProfile (UUID, PlayerName, Textures, TexturesSignature, DateTime)"); - // Clean up old entries: - { - SQLite::Statement stmt(db, "DELETE FROM PlayerNameToUUID WHERE DateTime < ?"); - Int64 LimitDateTime = time(NULL) - MAX_AGE; - stmt.bind(1, LimitDateTime); - stmt.exec(); - } - { - SQLite::Statement stmt(db, "DELETE FROM UUIDToProfile WHERE DateTime < ?"); - Int64 LimitDateTime = time(NULL) - MAX_AGE; - stmt.bind(1, LimitDateTime); - stmt.exec(); - } - - // Retrieve all remaining entries: + // Retrieve all entries: { SQLite::Statement stmt(db, "SELECT PlayerName, UUID, DateTime FROM PlayerNameToUUID"); while (stmt.executeStep()) @@ -596,18 +624,27 @@ void cMojangAPI::CacheNamesToUUIDs(const AStringVector & a_PlayerNames) } // for itr - a_PlayerNames[] } // Lock(m_CSNameToUUID) - while (!NamesToQuery.empty()) + QueryNamesToUUIDs(NamesToQuery); +} + + + + + +void cMojangAPI::QueryNamesToUUIDs(AStringVector & a_NamesToQuery) +{ + while (!a_NamesToQuery.empty()) { // Create the request body - a JSON containing up to MAX_PER_QUERY playernames: Json::Value root; int Count = 0; - AStringVector::iterator itr = NamesToQuery.begin(), end = NamesToQuery.end(); + AStringVector::iterator itr = a_NamesToQuery.begin(), end = a_NamesToQuery.end(); for (; (itr != end) && (Count < MAX_PER_QUERY); ++itr, ++Count) { Json::Value req(*itr); root.append(req); } // for itr - a_PlayerNames[] - NamesToQuery.erase(NamesToQuery.begin(), itr); + a_NamesToQuery.erase(a_NamesToQuery.begin(), itr); Json::FastWriter Writer; AString RequestBody = Writer.write(root); @@ -705,12 +742,22 @@ void cMojangAPI::CacheUUIDToProfile(const AString & a_UUID) // Check if already present: { + cCSLock Lock(m_CSUUIDToProfile); if (m_UUIDToProfile.find(a_UUID) != m_UUIDToProfile.end()) { return; } } + QueryUUIDToProfile(a_UUID); +} + + + + + +void cMojangAPI::QueryUUIDToProfile(const AString & a_UUID) +{ // Create the request address: AString Address = m_UUIDToProfileAddress; ReplaceString(Address, "%UUID%", a_UUID); @@ -817,3 +864,51 @@ void cMojangAPI::NotifyNameUUID(const AString & a_PlayerName, const AString & a_ + +void cMojangAPI::Update(void) +{ + Int64 LimitDateTime = time(NULL) - MAX_AGE; + + // Re-query all playernames that are stale: + AStringVector PlayerNames; + { + cCSLock Lock(m_CSNameToUUID); + for (cProfileMap::const_iterator itr = m_NameToUUID.begin(), end = m_NameToUUID.end(); itr != end; ++itr) + { + if (itr->second.m_DateTime < LimitDateTime) + { + PlayerNames.push_back(itr->first); + } + } // for itr - m_NameToUUID[] + } + if (!PlayerNames.empty()) + { + LOG("cMojangAPI: Updating name-to-uuid cache for %u names", (unsigned)PlayerNames.size()); + QueryNamesToUUIDs(PlayerNames); + } + + // Re-query all profiles that are stale: + AStringVector ProfileUUIDs; + { + cCSLock Lock(m_CSUUIDToProfile); + for (cProfileMap::const_iterator itr = m_UUIDToProfile.begin(), end = m_UUIDToProfile.end(); itr != end; ++itr) + { + if (itr->second.m_DateTime < LimitDateTime) + { + ProfileUUIDs.push_back(itr->first); + } + } // for itr - m_UUIDToProfile[] + } + if (!ProfileUUIDs.empty()) + { + LOG("cMojangAPI: Updating uuid-to-profile cache for %u uuids", (unsigned)ProfileUUIDs.size()); + for (AStringVector::const_iterator itr = ProfileUUIDs.begin(), end = ProfileUUIDs.end(); itr != end; ++itr) + { + QueryUUIDToProfile(*itr); + } + } +} + + + + diff --git a/src/Protocol/MojangAPI.h b/src/Protocol/MojangAPI.h index 252d32543..393fd4baa 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. @@ -93,6 +93,10 @@ public: void SetRankManager(cRankManager * a_RankManager) { m_RankMgr = a_RankManager; } protected: + /** The thread that periodically checks for stale data and re-queries it from the server. */ + class cUpdateThread; + + /** Holds data for a single player profile. */ struct sProfile { @@ -177,6 +181,9 @@ protected: /** Protects m_RankMgr agains simultaneous multi-threaded access. */ cCriticalSection m_CSRankMgr; + + /** The thread that periodically updates the stale data in the DB from the Mojang servers. */ + SharedPtr<cUpdateThread> m_UpdateThread; /** Loads the caches from a disk storage. */ @@ -189,15 +196,29 @@ protected: Names that are not valid are not added into the cache. ASSUMEs that a_PlayerNames contains lowercased player names. */ void CacheNamesToUUIDs(const AStringVector & a_PlayerNames); + + /** Queries all the specified names and stores them into the m_PlayerNameToUUID cache. + Names that are not valid are not added into the cache. + ASSUMEs that a_PlayerNames contans lowercased player names. + For performance reasons takes a non-const reference and modifies the list given to it, until empty. */ + void QueryNamesToUUIDs(AStringVector & a_PlayerNames); /** Makes sure the specified UUID is in the m_UUIDToProfile cache. If missing, downloads it from Mojang API servers. UUIDs that are not valid will not be added into the cache. ASSUMEs that a_UUID is a lowercased short UUID. */ void CacheUUIDToProfile(const AString & a_UUID); + /** Queries the specified UUID's profile and stores it in the m_UUIDToProfile cache. If already present, updates the cache entry. + UUIDs that are not valid will not be added into the cache. + ASSUMEs that a_UUID is a lowercased short UUID. */ + void QueryUUIDToProfile(const AString & a_UUID); + /** Called for each name-uuid pairing that is discovered. If assigned, notifies the m_RankManager of the event. */ void NotifyNameUUID(const AString & a_PlayerName, const AString & a_PlayerUUID); + + /** Updates the stale values in the DB from the Mojang servers. Called from the cUpdateThread, blocks on the HTTPS API calls. */ + void Update(void); } ; // tolua_export diff --git a/src/Protocol/ProtocolRecognizer.cpp b/src/Protocol/ProtocolRecognizer.cpp index 0b829ac9e..0c1e83b67 100644 --- a/src/Protocol/ProtocolRecognizer.cpp +++ b/src/Protocol/ProtocolRecognizer.cpp @@ -905,6 +905,7 @@ bool cProtocolRecognizer::TryRecognizeLengthedProtocol(UInt32 a_PacketLengthRema { return false; } + m_Client->SetProtocolVersion(ProtocolVersion); switch (ProtocolVersion) { case PROTO_VERSION_1_7_2: diff --git a/src/Protocol/ProtocolRecognizer.h b/src/Protocol/ProtocolRecognizer.h index f60df4158..dcf653e75 100644 --- a/src/Protocol/ProtocolRecognizer.h +++ b/src/Protocol/ProtocolRecognizer.h @@ -134,7 +134,7 @@ protected: /// Tries to recognize protocol based on m_Buffer contents; returns true if recognized bool TryRecognizeProtocol(void); - /** Tries to recognize a protocol in the leghted family (1.7+), based on m_Buffer; returns true if recognized. + /** Tries to recognize a protocol in the lengthed family (1.7+), based on m_Buffer; returns true if recognized. The packet length and type have already been read, type is 0 The number of bytes remaining in the packet is passed as a_PacketLengthRemaining **/ diff --git a/src/Root.cpp b/src/Root.cpp index b866e2369..02455518c 100644 --- a/src/Root.cpp +++ b/src/Root.cpp @@ -142,8 +142,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..."); diff --git a/src/Server.cpp b/src/Server.cpp index 969ffd693..8e5755a75 100644 --- a/src/Server.cpp +++ b/src/Server.cpp @@ -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; @@ -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); } 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/Simulator/FireSimulator.cpp b/src/Simulator/FireSimulator.cpp index 7ae84af7b..d3deee74a 100644 --- a/src/Simulator/FireSimulator.cpp +++ b/src/Simulator/FireSimulator.cpp @@ -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; } @@ -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/UI/SlotArea.cpp b/src/UI/SlotArea.cpp index 999bed989..88d9f44fc 100644 --- a/src/UI/SlotArea.cpp +++ b/src/UI/SlotArea.cpp @@ -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; } diff --git a/src/Vector3.h b/src/Vector3.h index 1dcb38f64..1854e42e3 100644 --- a/src/Vector3.h +++ b/src/Vector3.h @@ -3,8 +3,6 @@ -#define _USE_MATH_DEFINES // Enable non-standard math defines (MSVC) -#include <math.h> #include <list> #include <vector> @@ -29,9 +27,9 @@ public: // Hardcoded copy constructors (tolua++ does not support function templates .. yet) - Vector3(const Vector3<float> & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} - Vector3(const Vector3<double> & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} - Vector3(const Vector3<int> & a_Rhs) : x((T) a_Rhs.x), y((T) a_Rhs.y), z((T) a_Rhs.z) {} + Vector3(const Vector3<float> & a_Rhs) : x(static_cast<T>(a_Rhs.x)), y(static_cast<T>(a_Rhs.y)), z(static_cast<T>(a_Rhs.z)) {} + Vector3(const Vector3<double> & a_Rhs) : x(static_cast<T>(a_Rhs.x)), y(static_cast<T>(a_Rhs.y)), z(static_cast<T>(a_Rhs.z)) {} + Vector3(const Vector3<int> & a_Rhs) : x(static_cast<T>(a_Rhs.x)), y(static_cast<T>(a_Rhs.y)), z(static_cast<T>(a_Rhs.z)) {} // tolua_end @@ -53,9 +51,9 @@ public: { double Len = 1.0 / Length(); - x = (T)(x * Len); - y = (T)(y * Len); - z = (T)(z * Len); + x = static_cast<T>(x * Len); + y = static_cast<T>(y * Len); + z = static_cast<T>(z * Len); } inline Vector3<T> NormalizeCopy(void) const @@ -63,9 +61,9 @@ public: double Len = 1.0 / Length(); return Vector3<T>( - (T)(x * Len), - (T)(y * Len), - (T)(z * Len) + static_cast<T>(x * Len), + static_cast<T>(y * Len), + static_cast<T>(z * Len) ); } @@ -74,15 +72,15 @@ public: double Len = 1.0 / Length(); a_Rhs.Set( - (T)(x * Len), - (T)(y * Len), - (T)(z * Len) + static_cast<T>(x * Len), + static_cast<T>(y * Len), + static_cast<T>(z * Len) ); } inline double Length(void) const { - return sqrt((double)(x * x + y * y + z * z)); + return sqrt(static_cast<double>(x * x + y * y + z * z)); } inline double SqrLength(void) const @@ -138,9 +136,9 @@ public: inline Vector3<int> Floor(void) const { return Vector3<int>( - (int)floor(x), - (int)floor(y), - (int)floor(z) + FloorC(x), + FloorC(y), + FloorC(z) ); } diff --git a/src/World.cpp b/src/World.cpp index a3c804b44..1f9361386 100644 --- a/src/World.cpp +++ b/src/World.cpp @@ -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_SimulatorManager(), + m_SandSimulator(), m_WaterSimulator(NULL), - m_LavaSimulator(NULL), - m_FireSimulator(NULL), + m_LavaSimulator(nullptr), + m_FireSimulator(), m_RedstoneSimulator(NULL), 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,11 +303,8 @@ 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; 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[] } @@ -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); } @@ -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)); } @@ -3633,7 +3640,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 +3651,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..bb43d7fba 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 : @@ -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. @@ -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 @@ -861,7 +861,8 @@ private: } }; - 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; |