From fd5d54fdd36414c9e128f4dce95dec7ba12c790d Mon Sep 17 00:00:00 2001 From: Beats Date: Sun, 28 Jul 2024 13:46:02 -0300 Subject: [PATCH 01/34] init --- src/items/functions/item/item_parse.cpp | 1 - src/items/items.cpp | 2 +- src/lua/callbacks/event_callback.cpp | 316 ++++++----- src/lua/callbacks/event_callback.hpp | 82 +-- src/lua/callbacks/events_callbacks.cpp | 4 +- src/lua/callbacks/events_callbacks.hpp | 2 +- src/lua/creature/actions.cpp | 38 +- src/lua/creature/actions.hpp | 36 +- src/lua/creature/creatureevent.cpp | 94 +-- src/lua/creature/creatureevent.hpp | 34 +- src/lua/creature/events.cpp | 270 ++++----- src/lua/creature/events.hpp | 66 +-- src/lua/creature/movement.cpp | 81 +-- src/lua/creature/movement.hpp | 47 +- src/lua/creature/raids.cpp | 8 +- src/lua/creature/raids.hpp | 10 +- src/lua/creature/talkaction.cpp | 10 +- src/lua/creature/talkaction.hpp | 10 +- .../functions/core/game/game_functions.cpp | 23 +- .../functions/core/game/global_functions.cpp | 2 +- .../functions/core/game/zone_functions.cpp | 14 +- .../creatures/combat/combat_functions.cpp | 2 +- .../creatures/combat/condition_functions.cpp | 2 +- .../creatures/combat/spell_functions.cpp | 4 +- .../creatures/monster/monster_functions.cpp | 12 +- .../monster/monster_spell_functions.cpp | 46 +- .../monster/monster_spell_functions.hpp | 2 +- .../monster/monster_type_functions.cpp | 180 +++--- .../functions/creatures/npc/npc_functions.cpp | 68 +-- .../creatures/player/guild_functions.cpp | 24 +- .../creatures/player/mount_functions.cpp | 8 +- .../creatures/player/party_functions.cpp | 40 +- .../creatures/player/player_functions.cpp | 536 +++++++++--------- .../creatures/player/vocation_functions.cpp | 48 +- src/lua/functions/events/action_functions.cpp | 20 +- .../events/creature_event_functions.cpp | 8 +- .../events/event_callback_functions.cpp | 6 +- .../events/global_event_functions.cpp | 11 +- .../functions/events/move_event_functions.cpp | 24 +- .../events/talk_action_functions.cpp | 21 +- .../functions/items/container_functions.cpp | 42 +- src/lua/functions/items/item_functions.cpp | 122 ++-- src/lua/functions/items/weapon_functions.cpp | 1 - src/lua/functions/lua_functions_loader.cpp | 22 +- src/lua/functions/lua_functions_loader.hpp | 8 +- src/lua/functions/map/house_functions.cpp | 34 +- src/lua/functions/map/position_functions.cpp | 4 +- src/lua/functions/map/position_functions.hpp | 2 +- src/lua/functions/map/teleport_functions.cpp | 6 +- src/lua/functions/map/tile_functions.cpp | 108 ++-- src/lua/global/baseevents.cpp | 6 +- src/lua/global/baseevents.hpp | 6 +- src/lua/global/globalevent.cpp | 16 +- src/lua/global/globalevent.hpp | 6 +- src/lua/modules/modules.cpp | 72 +-- src/lua/modules/modules.hpp | 22 +- src/lua/scripts/lua_environment.hpp | 6 +- src/lua/scripts/script_environment.cpp | 24 +- src/lua/scripts/script_environment.hpp | 18 +- src/lua/scripts/scripts.cpp | 2 +- src/server/network/protocol/protocolgame.cpp | 2 +- 61 files changed, 1357 insertions(+), 1384 deletions(-) diff --git a/src/items/functions/item/item_parse.cpp b/src/items/functions/item/item_parse.cpp index 9b63b9aee0e..41b35403bca 100644 --- a/src/items/functions/item/item_parse.cpp +++ b/src/items/functions/item/item_parse.cpp @@ -1031,7 +1031,6 @@ void ItemParse::createAndRegisterScript(ItemType &itemType, pugi::xml_node attri moveevent = std::make_shared(&g_moveEvents().getScriptInterface()); moveevent->setItemId(itemType.id); moveevent->setEventType(eventType); - moveevent->setFromXML(true); if (eventType == MOVE_EVENT_EQUIP) { moveevent->equipFunction = moveevent->EquipItem; diff --git a/src/items/items.cpp b/src/items/items.cpp index 2d4020c5416..ea07b2354a3 100644 --- a/src/items/items.cpp +++ b/src/items/items.cpp @@ -25,7 +25,7 @@ void Items::clear() { ladders.clear(); dummys.clear(); nameToItems.clear(); - g_moveEvents().clear(true); + g_moveEvents().clear(); g_weapons().clear(true); } diff --git a/src/lua/callbacks/event_callback.cpp b/src/lua/callbacks/event_callback.cpp index 38e7654d8d5..950d4764338 100644 --- a/src/lua/callbacks/event_callback.cpp +++ b/src/lua/callbacks/event_callback.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "lua/callbacks/event_callback.hpp" @@ -47,15 +49,15 @@ void EventCallback::setType(EventCallback_t type) { // Lua functions // Creature -bool EventCallback::creatureOnChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::creatureOnChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::creatureOnChangeOutfit - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -69,8 +71,8 @@ bool EventCallback::creatureOnChangeOutfit(std::shared_ptr creature, c return getScriptInterface()->callFunction(2); } -ReturnValue EventCallback::creatureOnAreaCombat(std::shared_ptr creature, std::shared_ptr tile, bool aggressive) const { - if (!getScriptInterface()->reserveScriptEnv()) { +ReturnValue EventCallback::creatureOnAreaCombat(const std::shared_ptr &creature, const std::shared_ptr &tile, bool aggressive) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::creatureOnAreaCombat - " "Creature {} on tile position {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -78,7 +80,7 @@ ReturnValue EventCallback::creatureOnAreaCombat(std::shared_ptr creatu return RETURNVALUE_NOTPOSSIBLE; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -97,7 +99,7 @@ ReturnValue EventCallback::creatureOnAreaCombat(std::shared_ptr creatu LuaScriptInterface::pushBoolean(L, aggressive); ReturnValue returnValue; - if (getScriptInterface()->protectedCall(L, 3, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 3, 1) != 0) { returnValue = RETURNVALUE_NOTPOSSIBLE; LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { @@ -105,12 +107,12 @@ ReturnValue EventCallback::creatureOnAreaCombat(std::shared_ptr creatu lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return returnValue; } -ReturnValue EventCallback::creatureOnTargetCombat(std::shared_ptr creature, std::shared_ptr target) const { - if (!getScriptInterface()->reserveScriptEnv()) { +ReturnValue EventCallback::creatureOnTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::creatureOnTargetCombat - " "Creature {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -118,7 +120,7 @@ ReturnValue EventCallback::creatureOnTargetCombat(std::shared_ptr crea return RETURNVALUE_NOTPOSSIBLE; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -135,7 +137,7 @@ ReturnValue EventCallback::creatureOnTargetCombat(std::shared_ptr crea LuaScriptInterface::setCreatureMetatable(L, -1, target); ReturnValue returnValue; - if (getScriptInterface()->protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { returnValue = RETURNVALUE_NOTPOSSIBLE; LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { @@ -143,12 +145,12 @@ ReturnValue EventCallback::creatureOnTargetCombat(std::shared_ptr crea lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return returnValue; } -void EventCallback::creatureOnHear(std::shared_ptr creature, std::shared_ptr speaker, const std::string &words, SpeakClasses type) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::creatureOnHear(const std::shared_ptr &creature, const std::shared_ptr &speaker, const std::string &words, SpeakClasses type) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::creatureOnHear - " "Creature {} speaker {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -156,7 +158,7 @@ void EventCallback::creatureOnHear(std::shared_ptr creature, std::shar return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -174,8 +176,8 @@ void EventCallback::creatureOnHear(std::shared_ptr creature, std::shar getScriptInterface()->callVoidFunction(4); } -void EventCallback::creatureOnDrainHealth(std::shared_ptr creature, std::shared_ptr attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::creatureOnDrainHealth(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::creatureOnDrainHealth - " "Creature {} attacker {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -183,7 +185,7 @@ void EventCallback::creatureOnDrainHealth(std::shared_ptr creature, st return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -210,7 +212,7 @@ void EventCallback::creatureOnDrainHealth(std::shared_ptr creature, st lua_pushnumber(L, colorPrimary); lua_pushnumber(L, colorSecondary); - if (getScriptInterface()->protectedCall(L, 8, 6) != 0) { + if (LuaScriptInterface::protectedCall(L, 8, 6) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { typePrimary = LuaScriptInterface::getNumber(L, -6); @@ -222,12 +224,12 @@ void EventCallback::creatureOnDrainHealth(std::shared_ptr creature, st lua_pop(L, 6); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Party -bool EventCallback::partyOnJoin(std::shared_ptr party, std::shared_ptr player) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::partyOnJoin(std::shared_ptr party, const std::shared_ptr &player) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::partyOnJoin - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -235,13 +237,13 @@ bool EventCallback::partyOnJoin(std::shared_ptr party, std::shared_ptrgetScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, party); + LuaScriptInterface::pushUserdata(L, std::move(party)); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata(L, player); @@ -250,8 +252,8 @@ bool EventCallback::partyOnJoin(std::shared_ptr party, std::shared_ptrcallFunction(2); } -bool EventCallback::partyOnLeave(std::shared_ptr party, std::shared_ptr player) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::partyOnLeave(std::shared_ptr party, const std::shared_ptr &player) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::partyOnLeave - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -259,13 +261,13 @@ bool EventCallback::partyOnLeave(std::shared_ptr party, std::shared_ptr

getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, party); + LuaScriptInterface::pushUserdata(L, std::move(party)); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata(L, player); @@ -274,15 +276,15 @@ bool EventCallback::partyOnLeave(std::shared_ptr party, std::shared_ptr

callFunction(2); } -bool EventCallback::partyOnDisband(std::shared_ptr party) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::partyOnDisband(const std::shared_ptr &party) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::partyOnDisband - Party leader {}] Call stack " "overflow. Too many lua script calls being nested.", party->getLeader() ? party->getLeader()->getName() : "unknown"); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -294,13 +296,13 @@ bool EventCallback::partyOnDisband(std::shared_ptr party) const { return getScriptInterface()->callFunction(1); } -void EventCallback::partyOnShareExperience(std::shared_ptr party, uint64_t &exp) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::partyOnShareExperience(const std::shared_ptr &party, uint64_t &exp) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Party leader {}. Call stack overflow. Too many lua script calls being nested.", party->getLeader() ? party->getLeader()->getName() : "unknown"); return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -311,19 +313,19 @@ void EventCallback::partyOnShareExperience(std::shared_ptr party, uint64_ lua_pushnumber(L, exp); - if (getScriptInterface()->protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Player -bool EventCallback::playerOnBrowseField(std::shared_ptr player, const Position &position) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnBrowseField(const std::shared_ptr &player, const Position &position) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnBrowseField - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -331,7 +333,7 @@ bool EventCallback::playerOnBrowseField(std::shared_ptr player, const Po return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -345,8 +347,8 @@ bool EventCallback::playerOnBrowseField(std::shared_ptr player, const Po return getScriptInterface()->callFunction(2); } -void EventCallback::playerOnLook(std::shared_ptr player, const Position &position, std::shared_ptr thing, uint8_t stackpos, int32_t lookDistance) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnLook(const std::shared_ptr &player, const Position &position, const std::shared_ptr &thing, uint8_t stackpos, int32_t lookDistance) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLook - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -354,7 +356,7 @@ void EventCallback::playerOnLook(std::shared_ptr player, const Position return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -379,8 +381,8 @@ void EventCallback::playerOnLook(std::shared_ptr player, const Position getScriptInterface()->callVoidFunction(4); } -void EventCallback::playerOnLookInBattleList(std::shared_ptr player, std::shared_ptr creature, int32_t lookDistance) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLookInBattleList - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -388,7 +390,7 @@ void EventCallback::playerOnLookInBattleList(std::shared_ptr player, std return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -405,8 +407,8 @@ void EventCallback::playerOnLookInBattleList(std::shared_ptr player, std getScriptInterface()->callVoidFunction(3); } -void EventCallback::playerOnLookInTrade(std::shared_ptr player, std::shared_ptr partner, std::shared_ptr item, int32_t lookDistance) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLookInTrade - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -414,7 +416,7 @@ void EventCallback::playerOnLookInTrade(std::shared_ptr player, std::sha return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -423,7 +425,7 @@ void EventCallback::playerOnLookInTrade(std::shared_ptr player, std::sha LuaScriptInterface::pushUserdata(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, partner); + LuaScriptInterface::pushUserdata(L, std::move(partner)); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, item); @@ -434,8 +436,8 @@ void EventCallback::playerOnLookInTrade(std::shared_ptr player, std::sha getScriptInterface()->callVoidFunction(4); } -bool EventCallback::playerOnLookInShop(std::shared_ptr player, const ItemType* itemType, uint8_t count) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLookInShop - " "Player {} itemType {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -443,7 +445,7 @@ bool EventCallback::playerOnLookInShop(std::shared_ptr player, const Ite return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -460,8 +462,8 @@ bool EventCallback::playerOnLookInShop(std::shared_ptr player, const Ite return getScriptInterface()->callFunction(3); } -void EventCallback::playerOnRemoveCount(std::shared_ptr player, std::shared_ptr item) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnRemoveCount(const std::shared_ptr &player, const std::shared_ptr &item) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnMove - " "Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -469,7 +471,7 @@ void EventCallback::playerOnRemoveCount(std::shared_ptr player, std::sha return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -484,20 +486,20 @@ void EventCallback::playerOnRemoveCount(std::shared_ptr player, std::sha getScriptInterface()->callFunction(2); } -bool EventCallback::playerOnMoveItem(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPos, const Position &toPos, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { +bool EventCallback::playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPos, const Position &toPos, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { if (!getScriptInterface()) { g_logger().error("script interface nullptr"); return false; } - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Action::executeUse - Player {}, on item {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), item->getName()); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -513,14 +515,14 @@ bool EventCallback::playerOnMoveItem(std::shared_ptr player, std::shared LuaScriptInterface::pushPosition(L, fromPos); LuaScriptInterface::pushPosition(L, toPos); - LuaScriptInterface::pushCylinder(L, fromCylinder); - LuaScriptInterface::pushCylinder(L, toCylinder); + LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); + LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); return getScriptInterface()->callFunction(7); } -void EventCallback::playerOnItemMoved(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnItemMoved - " "Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -528,7 +530,7 @@ void EventCallback::playerOnItemMoved(std::shared_ptr player, std::share return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -544,14 +546,14 @@ void EventCallback::playerOnItemMoved(std::shared_ptr player, std::share LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, fromCylinder); - LuaScriptInterface::pushCylinder(L, toCylinder); + LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); + LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); getScriptInterface()->callVoidFunction(7); } -void EventCallback::playerOnChangeZone(std::shared_ptr player, ZoneType_t zone) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnChangeZone - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -559,7 +561,7 @@ void EventCallback::playerOnChangeZone(std::shared_ptr player, ZoneType_ return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -572,8 +574,8 @@ void EventCallback::playerOnChangeZone(std::shared_ptr player, ZoneType_ getScriptInterface()->callVoidFunction(2); } -bool EventCallback::playerOnMoveCreature(std::shared_ptr player, std::shared_ptr creature, const Position &fromPosition, const Position &toPosition) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnMoveCreature - " "Player {} creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -581,7 +583,7 @@ bool EventCallback::playerOnMoveCreature(std::shared_ptr player, std::sh return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -599,8 +601,8 @@ bool EventCallback::playerOnMoveCreature(std::shared_ptr player, std::sh return getScriptInterface()->callFunction(4); } -void EventCallback::playerOnReportRuleViolation(std::shared_ptr player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnReportRuleViolation - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -608,7 +610,7 @@ void EventCallback::playerOnReportRuleViolation(std::shared_ptr player, return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -628,8 +630,8 @@ void EventCallback::playerOnReportRuleViolation(std::shared_ptr player, getScriptInterface()->callVoidFunction(6); } -void EventCallback::playerOnReportBug(std::shared_ptr player, const std::string &message, const Position &position, uint8_t category) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnReportBug(const std::shared_ptr &player, const std::string &message, const Position &position, uint8_t category) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnReportBug - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -637,7 +639,7 @@ void EventCallback::playerOnReportBug(std::shared_ptr player, const std: return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -653,8 +655,8 @@ void EventCallback::playerOnReportBug(std::shared_ptr player, const std: getScriptInterface()->callFunction(4); } -bool EventCallback::playerOnTurn(std::shared_ptr player, Direction direction) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnTurn(const std::shared_ptr &player, Direction direction) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnTurn - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -662,7 +664,7 @@ bool EventCallback::playerOnTurn(std::shared_ptr player, Direction direc return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -676,8 +678,8 @@ bool EventCallback::playerOnTurn(std::shared_ptr player, Direction direc return getScriptInterface()->callFunction(2); } -bool EventCallback::playerOnTradeRequest(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnTradeRequest(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnTradeRequest - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -685,7 +687,7 @@ bool EventCallback::playerOnTradeRequest(std::shared_ptr player, std::sh return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -703,8 +705,8 @@ bool EventCallback::playerOnTradeRequest(std::shared_ptr player, std::sh return getScriptInterface()->callFunction(3); } -bool EventCallback::playerOnTradeAccept(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, std::shared_ptr targetItem) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnTradeAccept(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, const std::shared_ptr &targetItem) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnTradeAccept - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -712,7 +714,7 @@ bool EventCallback::playerOnTradeAccept(std::shared_ptr player, std::sha return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -733,8 +735,8 @@ bool EventCallback::playerOnTradeAccept(std::shared_ptr player, std::sha return getScriptInterface()->callFunction(4); } -void EventCallback::playerOnGainExperience(std::shared_ptr player, std::shared_ptr target, uint64_t &exp, uint64_t rawExp) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnGainExperience(const std::shared_ptr &player, const std::shared_ptr &target, uint64_t &exp, uint64_t rawExp) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnGainExperience - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -742,7 +744,7 @@ void EventCallback::playerOnGainExperience(std::shared_ptr player, std:: return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -761,18 +763,18 @@ void EventCallback::playerOnGainExperience(std::shared_ptr player, std:: lua_pushnumber(L, exp); lua_pushnumber(L, rawExp); - if (getScriptInterface()->protectedCall(L, 4, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 4, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void EventCallback::playerOnLoseExperience(std::shared_ptr player, uint64_t &exp) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnLoseExperience(const std::shared_ptr &player, uint64_t &exp) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLoseExperience - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -780,7 +782,7 @@ void EventCallback::playerOnLoseExperience(std::shared_ptr player, uint6 return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -791,18 +793,18 @@ void EventCallback::playerOnLoseExperience(std::shared_ptr player, uint6 lua_pushnumber(L, exp); - if (getScriptInterface()->protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void EventCallback::playerOnGainSkillTries(std::shared_ptr player, skills_t skill, uint64_t &tries) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnGainSkillTries(const std::shared_ptr &player, skills_t skill, uint64_t &tries) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnGainSkillTries - " "Player {} skill {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -810,7 +812,7 @@ void EventCallback::playerOnGainSkillTries(std::shared_ptr player, skill return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -822,18 +824,18 @@ void EventCallback::playerOnGainSkillTries(std::shared_ptr player, skill lua_pushnumber(L, skill); lua_pushnumber(L, tries); - if (getScriptInterface()->protectedCall(L, 3, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 3, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { tries = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void EventCallback::playerOnCombat(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, CombatDamage &damage) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnCombat - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -841,7 +843,7 @@ void EventCallback::playerOnCombat(std::shared_ptr player, std::shared_p return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -866,7 +868,7 @@ void EventCallback::playerOnCombat(std::shared_ptr player, std::shared_p LuaScriptInterface::pushCombatDamage(L, damage); - if (getScriptInterface()->protectedCall(L, 8, 4) != 0) { + if (LuaScriptInterface::protectedCall(L, 8, 4) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { damage.primary.value = std::abs(LuaScriptInterface::getNumber(L, -4)); @@ -891,11 +893,11 @@ void EventCallback::playerOnCombat(std::shared_ptr player, std::shared_p } } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void EventCallback::playerOnRequestQuestLog(std::shared_ptr player) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnRequestQuestLog(const std::shared_ptr &player) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnRequestQuestLog - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -903,7 +905,7 @@ void EventCallback::playerOnRequestQuestLog(std::shared_ptr player) cons return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -915,8 +917,8 @@ void EventCallback::playerOnRequestQuestLog(std::shared_ptr player) cons getScriptInterface()->callVoidFunction(1); } -void EventCallback::playerOnRequestQuestLine(std::shared_ptr player, uint16_t questId) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnRequestQuestLine - " "Player {} questId {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -924,7 +926,7 @@ void EventCallback::playerOnRequestQuestLine(std::shared_ptr player, uin return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -938,19 +940,19 @@ void EventCallback::playerOnRequestQuestLine(std::shared_ptr player, uin getScriptInterface()->callVoidFunction(2); } -void EventCallback::playerOnInventoryUpdate(std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool equip) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[{}] Call stack overflow", __FUNCTION__); return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushUserdata(L, std::move(player)); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, item); @@ -962,19 +964,19 @@ void EventCallback::playerOnInventoryUpdate(std::shared_ptr player, std: getScriptInterface()->callVoidFunction(4); } -bool EventCallback::playerOnRotateItem(std::shared_ptr player, std::shared_ptr item, const Position &position) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::playerOnRotateItem(std::shared_ptr player, const std::shared_ptr &item, const Position &position) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[{}] Call stack overflow", __FUNCTION__); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushUserdata(L, std::move(player)); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, item); @@ -985,8 +987,8 @@ bool EventCallback::playerOnRotateItem(std::shared_ptr player, std::shar return getScriptInterface()->callFunction(3); } -void EventCallback::playerOnWalk(std::shared_ptr player, Direction &dir) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnWalk(const std::shared_ptr &player, Direction &dir) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::eventOnWalk - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -994,7 +996,7 @@ void EventCallback::playerOnWalk(std::shared_ptr player, Direction &dir) return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -1008,8 +1010,8 @@ void EventCallback::playerOnWalk(std::shared_ptr player, Direction &dir) getScriptInterface()->callVoidFunction(2); } -void EventCallback::playerOnStorageUpdate(std::shared_ptr player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::playerOnStorageUpdate(const std::shared_ptr &player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::eventOnStorageUpdate - " "Player {} key {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1017,7 +1019,7 @@ void EventCallback::playerOnStorageUpdate(std::shared_ptr player, const return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -1035,8 +1037,8 @@ void EventCallback::playerOnStorageUpdate(std::shared_ptr player, const } // Monster -void EventCallback::monsterOnDropLoot(std::shared_ptr monster, std::shared_ptr corpse) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::monsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::monsterOnDropLoot - " "Monster corpse {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1044,13 +1046,13 @@ void EventCallback::monsterOnDropLoot(std::shared_ptr monster, std::sha return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushUserdata(L, std::move(monster)); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata(L, corpse); @@ -1059,8 +1061,8 @@ void EventCallback::monsterOnDropLoot(std::shared_ptr monster, std::sha return getScriptInterface()->callVoidFunction(2); } -void EventCallback::monsterPostDropLoot(std::shared_ptr monster, std::shared_ptr corpse) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::monsterPostDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::monsterPostDropLoot - " "Monster corpse {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1068,13 +1070,13 @@ void EventCallback::monsterPostDropLoot(std::shared_ptr monster, std::s return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushUserdata(L, std::move(monster)); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata(L, corpse); @@ -1084,7 +1086,7 @@ void EventCallback::monsterPostDropLoot(std::shared_ptr monster, std::s } void EventCallback::monsterOnSpawn(std::shared_ptr monster, const Position &position) const { - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" ". Call stack overflow. Too many lua script calls being nested.", @@ -1092,28 +1094,28 @@ void EventCallback::monsterOnSpawn(std::shared_ptr monster, const Posit return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushUserdata(L, std::move(monster)); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushPosition(L, position); - if (getScriptInterface()->protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Npc void EventCallback::npcOnSpawn(std::shared_ptr npc, const Position &position) const { - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" ". Call stack overflow. Too many lua script calls being nested.", @@ -1121,27 +1123,27 @@ void EventCallback::npcOnSpawn(std::shared_ptr npc, const Position &positio return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata(L, npc); + LuaScriptInterface::pushUserdata(L, std::move(npc)); LuaScriptInterface::setMetatable(L, -1, "Npc"); LuaScriptInterface::pushPosition(L, position); - if (getScriptInterface()->protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { lua_pop(L, 1); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -bool EventCallback::zoneBeforeCreatureEnter(std::shared_ptr zone, std::shared_ptr creature) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::zoneBeforeCreatureEnter(const std::shared_ptr &zone, const std::shared_ptr &creature) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::zoneBeforeCreatureEnter - " "Zone {} Creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1149,7 +1151,7 @@ bool EventCallback::zoneBeforeCreatureEnter(std::shared_ptr zone, std::sha return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -1164,8 +1166,8 @@ bool EventCallback::zoneBeforeCreatureEnter(std::shared_ptr zone, std::sha return getScriptInterface()->callFunction(2); } -bool EventCallback::zoneBeforeCreatureLeave(std::shared_ptr zone, std::shared_ptr creature) const { - if (!getScriptInterface()->reserveScriptEnv()) { +bool EventCallback::zoneBeforeCreatureLeave(const std::shared_ptr &zone, const std::shared_ptr &creature) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::zoneBeforeCreatureLeave - " "Zone {} Creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1173,7 +1175,7 @@ bool EventCallback::zoneBeforeCreatureLeave(std::shared_ptr zone, std::sha return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -1188,8 +1190,8 @@ bool EventCallback::zoneBeforeCreatureLeave(std::shared_ptr zone, std::sha return getScriptInterface()->callFunction(2); } -void EventCallback::zoneAfterCreatureEnter(std::shared_ptr zone, std::shared_ptr creature) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::zoneAfterCreatureEnter(const std::shared_ptr &zone, const std::shared_ptr &creature) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::zoneAfterCreatureEnter - " "Zone {} Creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1197,7 +1199,7 @@ void EventCallback::zoneAfterCreatureEnter(std::shared_ptr zone, std::shar return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -1212,8 +1214,8 @@ void EventCallback::zoneAfterCreatureEnter(std::shared_ptr zone, std::shar getScriptInterface()->callVoidFunction(2); } -void EventCallback::zoneAfterCreatureLeave(std::shared_ptr zone, std::shared_ptr creature) const { - if (!getScriptInterface()->reserveScriptEnv()) { +void EventCallback::zoneAfterCreatureLeave(const std::shared_ptr &zone, const std::shared_ptr &creature) const { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::zoneAfterCreatureLeave - " "Zone {} Creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1221,7 +1223,7 @@ void EventCallback::zoneAfterCreatureLeave(std::shared_ptr zone, std::shar return; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); diff --git a/src/lua/callbacks/event_callback.hpp b/src/lua/callbacks/event_callback.hpp index 9141235a028..3558341035e 100644 --- a/src/lua/callbacks/event_callback.hpp +++ b/src/lua/callbacks/event_callback.hpp @@ -53,7 +53,7 @@ class EventCallback : public Script { * @brief Sets a new script type name. * @param newName The new name to set for the script type. */ - void setScriptTypeName(const std::string_view newName); + void setScriptTypeName(std::string_view newName); /** * @brief Retrieves the type of the event callback. @@ -79,58 +79,58 @@ class EventCallback : public Script { */ // Creature - bool creatureOnChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit) const; - ReturnValue creatureOnAreaCombat(std::shared_ptr creature, std::shared_ptr tile, bool aggressive) const; - ReturnValue creatureOnTargetCombat(std::shared_ptr creature, std::shared_ptr target) const; - void creatureOnHear(std::shared_ptr creature, std::shared_ptr speaker, const std::string &words, SpeakClasses type) const; - void creatureOnDrainHealth(std::shared_ptr creature, std::shared_ptr attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) const; + bool creatureOnChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) const; + ReturnValue creatureOnAreaCombat(const std::shared_ptr &creature, const std::shared_ptr &tile, bool aggressive) const; + ReturnValue creatureOnTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const; + void creatureOnHear(const std::shared_ptr &creature, const std::shared_ptr &speaker, const std::string &words, SpeakClasses type) const; + void creatureOnDrainHealth(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) const; // Party - bool partyOnJoin(std::shared_ptr party, std::shared_ptr player) const; - bool partyOnLeave(std::shared_ptr party, std::shared_ptr player) const; - bool partyOnDisband(std::shared_ptr party) const; - void partyOnShareExperience(std::shared_ptr party, uint64_t &exp) const; + bool partyOnJoin(std::shared_ptr party, const std::shared_ptr &player) const; + bool partyOnLeave(std::shared_ptr party, const std::shared_ptr &player) const; + bool partyOnDisband(const std::shared_ptr &party) const; + void partyOnShareExperience(const std::shared_ptr &party, uint64_t &exp) const; // Player - bool playerOnBrowseField(std::shared_ptr player, const Position &position) const; - void playerOnLook(std::shared_ptr player, const Position &position, std::shared_ptr thing, uint8_t stackpos, int32_t lookDistance) const; - void playerOnLookInBattleList(std::shared_ptr player, std::shared_ptr creature, int32_t lookDistance) const; - void playerOnLookInTrade(std::shared_ptr player, std::shared_ptr partner, std::shared_ptr item, int32_t lookDistance) const; - bool playerOnLookInShop(std::shared_ptr player, const ItemType* itemType, uint8_t count) const; - bool playerOnMoveItem(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; - void playerOnItemMoved(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; - void playerOnChangeZone(std::shared_ptr player, ZoneType_t zone) const; - bool playerOnMoveCreature(std::shared_ptr player, std::shared_ptr creature, const Position &fromPosition, const Position &toPosition) const; - void playerOnReportRuleViolation(std::shared_ptr player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) const; - void playerOnReportBug(std::shared_ptr player, const std::string &message, const Position &position, uint8_t category) const; - bool playerOnTurn(std::shared_ptr player, Direction direction) const; - bool playerOnTradeRequest(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const; - bool playerOnTradeAccept(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, std::shared_ptr targetItem) const; - void playerOnGainExperience(std::shared_ptr player, std::shared_ptr target, uint64_t &exp, uint64_t rawExp) const; - void playerOnLoseExperience(std::shared_ptr player, uint64_t &exp) const; - void playerOnGainSkillTries(std::shared_ptr player, skills_t skill, uint64_t &tries) const; - void playerOnRemoveCount(std::shared_ptr player, std::shared_ptr item) const; - void playerOnRequestQuestLog(std::shared_ptr player) const; - void playerOnRequestQuestLine(std::shared_ptr player, uint16_t questId) const; - void playerOnStorageUpdate(std::shared_ptr player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime) const; - void playerOnCombat(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, CombatDamage &damage) const; - void playerOnInventoryUpdate(std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool equip) const; - bool playerOnRotateItem(std::shared_ptr player, std::shared_ptr item, const Position &position) const; - void playerOnWalk(std::shared_ptr player, Direction &dir) const; + bool playerOnBrowseField(const std::shared_ptr &player, const Position &position) const; + void playerOnLook(const std::shared_ptr &player, const Position &position, const std::shared_ptr &thing, uint8_t stackpos, int32_t lookDistance) const; + void playerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance) const; + void playerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance) const; + bool playerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count) const; + bool playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; + void playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; + void playerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone) const; + bool playerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition) const; + void playerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) const; + void playerOnReportBug(const std::shared_ptr &player, const std::string &message, const Position &position, uint8_t category) const; + bool playerOnTurn(const std::shared_ptr &player, Direction direction) const; + bool playerOnTradeRequest(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item) const; + bool playerOnTradeAccept(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, const std::shared_ptr &targetItem) const; + void playerOnGainExperience(const std::shared_ptr &player, const std::shared_ptr &target, uint64_t &exp, uint64_t rawExp) const; + void playerOnLoseExperience(const std::shared_ptr &player, uint64_t &exp) const; + void playerOnGainSkillTries(const std::shared_ptr &player, skills_t skill, uint64_t &tries) const; + void playerOnRemoveCount(const std::shared_ptr &player, const std::shared_ptr &item) const; + void playerOnRequestQuestLog(const std::shared_ptr &player) const; + void playerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId) const; + void playerOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime) const; + void playerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage) const; + void playerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) const; + bool playerOnRotateItem(std::shared_ptr player, const std::shared_ptr &item, const Position &position) const; + void playerOnWalk(const std::shared_ptr &player, Direction &dir) const; // Monster - void monsterOnDropLoot(std::shared_ptr monster, std::shared_ptr corpse) const; - void monsterPostDropLoot(std::shared_ptr monster, std::shared_ptr corpse) const; + void monsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse) const; + void monsterPostDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse) const; void monsterOnSpawn(std::shared_ptr monster, const Position &position) const; // Npc void npcOnSpawn(std::shared_ptr npc, const Position &position) const; // Zone - bool zoneBeforeCreatureEnter(std::shared_ptr zone, std::shared_ptr creature) const; - bool zoneBeforeCreatureLeave(std::shared_ptr zone, std::shared_ptr creature) const; - void zoneAfterCreatureEnter(std::shared_ptr zone, std::shared_ptr creature) const; - void zoneAfterCreatureLeave(std::shared_ptr zone, std::shared_ptr creature) const; + bool zoneBeforeCreatureEnter(const std::shared_ptr &zone, const std::shared_ptr &creature) const; + bool zoneBeforeCreatureLeave(const std::shared_ptr &zone, const std::shared_ptr &creature) const; + void zoneAfterCreatureEnter(const std::shared_ptr &zone, const std::shared_ptr &creature) const; + void zoneAfterCreatureLeave(const std::shared_ptr &zone, const std::shared_ptr &creature) const; /** * @note here end the lua binder functions } diff --git a/src/lua/callbacks/events_callbacks.cpp b/src/lua/callbacks/events_callbacks.cpp index 4a1830f80fb..d8ab997d416 100644 --- a/src/lua/callbacks/events_callbacks.cpp +++ b/src/lua/callbacks/events_callbacks.cpp @@ -28,7 +28,7 @@ EventsCallbacks &EventsCallbacks::getInstance() { return inject(); } -void EventsCallbacks::addCallback(const std::shared_ptr callback) { +void EventsCallbacks::addCallback(const std::shared_ptr &callback) { m_callbacks.push_back(callback); } @@ -38,7 +38,7 @@ std::vector> EventsCallbacks::getCallbacks() cons std::vector> EventsCallbacks::getCallbacksByType(EventCallback_t type) const { std::vector> eventCallbacks; - for (auto callback : getCallbacks()) { + for (const auto &callback : getCallbacks()) { if (callback->getType() != type) { continue; } diff --git a/src/lua/callbacks/events_callbacks.hpp b/src/lua/callbacks/events_callbacks.hpp index f71103047e6..ecfe9cf635d 100644 --- a/src/lua/callbacks/events_callbacks.hpp +++ b/src/lua/callbacks/events_callbacks.hpp @@ -49,7 +49,7 @@ class EventsCallbacks { * @brief Adds a new event callback to the list. * @param callback Pointer to the EventCallback object to add. */ - void addCallback(const std::shared_ptr callback); + void addCallback(const std::shared_ptr &callback); /** * @brief Gets all registered event callbacks. diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index 9e16ee7b33e..ab92e6d029b 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "lua/creature/actions.hpp" @@ -27,7 +29,7 @@ void Actions::clear() { actionPositionMap.clear(); } -bool Actions::registerLuaItemEvent(const std::shared_ptr action) { +bool Actions::registerLuaItemEvent(const std::shared_ptr &action) { auto itemIdVector = action->getItemIdsVector(); if (itemIdVector.empty()) { return false; @@ -60,7 +62,7 @@ bool Actions::registerLuaItemEvent(const std::shared_ptr action) { return !itemIdVector.empty(); } -bool Actions::registerLuaUniqueEvent(const std::shared_ptr action) { +bool Actions::registerLuaUniqueEvent(const std::shared_ptr &action) { auto uniqueIdVector = action->getUniqueIdsVector(); if (uniqueIdVector.empty()) { return false; @@ -91,7 +93,7 @@ bool Actions::registerLuaUniqueEvent(const std::shared_ptr action) { return !uniqueIdVector.empty(); } -bool Actions::registerLuaActionEvent(const std::shared_ptr action) { +bool Actions::registerLuaActionEvent(const std::shared_ptr &action) { auto actionIdVector = action->getActionIdsVector(); if (actionIdVector.empty()) { return false; @@ -122,7 +124,7 @@ bool Actions::registerLuaActionEvent(const std::shared_ptr action) { return !actionIdVector.empty(); } -bool Actions::registerLuaPositionEvent(const std::shared_ptr action) { +bool Actions::registerLuaPositionEvent(const std::shared_ptr &action) { auto positionVector = action->getPositionsVector(); if (positionVector.empty()) { return false; @@ -151,7 +153,7 @@ bool Actions::registerLuaPositionEvent(const std::shared_ptr action) { return !positionVector.empty(); } -bool Actions::registerLuaEvent(const std::shared_ptr action) { +bool Actions::registerLuaEvent(const std::shared_ptr &action) { // Call all register lua events if (registerLuaItemEvent(action) || registerLuaUniqueEvent(action) || registerLuaActionEvent(action) || registerLuaPositionEvent(action)) { return true; @@ -167,7 +169,7 @@ bool Actions::registerLuaEvent(const std::shared_ptr action) { return false; } -ReturnValue Actions::canUse(std::shared_ptr player, const Position &pos) { +ReturnValue Actions::canUse(const std::shared_ptr &player, const Position &pos) { if (pos.x != 0xFFFF) { const Position &playerPos = player->getPosition(); if (playerPos.z != pos.z) { @@ -181,15 +183,15 @@ ReturnValue Actions::canUse(std::shared_ptr player, const Position &pos) return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUse(std::shared_ptr player, const Position &pos, std::shared_ptr item) { +ReturnValue Actions::canUse(std::shared_ptr player, const Position &pos, const std::shared_ptr &item) { const std::shared_ptr action = getAction(item); if (action != nullptr) { - return action->canExecuteAction(player, pos); + return action->canExecuteAction(std::move(player), pos); } return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUseFar(std::shared_ptr creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) { +ReturnValue Actions::canUseFar(const std::shared_ptr &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) { if (toPos.x == 0xFFFF) { return RETURNVALUE_NOERROR; } @@ -210,7 +212,7 @@ ReturnValue Actions::canUseFar(std::shared_ptr creature, const Positio return RETURNVALUE_NOERROR; } -std::shared_ptr Actions::getAction(std::shared_ptr item) { +std::shared_ptr Actions::getAction(const std::shared_ptr &item) { if (item->hasAttribute(ItemAttribute_t::UNIQUEID)) { auto it = uniqueItemMap.find(item->getAttribute(ItemAttribute_t::UNIQUEID)); if (it != uniqueItemMap.end()) { @@ -248,7 +250,7 @@ std::shared_ptr Actions::getAction(std::shared_ptr item) { return g_spells().getRuneSpell(item->getID()); } -ReturnValue Actions::internalUseItem(std::shared_ptr player, const Position &pos, uint8_t index, std::shared_ptr item, bool isHotkey) { +ReturnValue Actions::internalUseItem(const std::shared_ptr &player, const Position &pos, uint8_t index, const std::shared_ptr &item, bool isHotkey) { if (std::shared_ptr door = item->getDoor()) { if (!door->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; @@ -388,7 +390,7 @@ ReturnValue Actions::internalUseItem(std::shared_ptr player, const Posit return RETURNVALUE_CANNOTUSETHISOBJECT; } -bool Actions::useItem(std::shared_ptr player, const Position &pos, uint8_t index, std::shared_ptr item, bool isHotkey) { +bool Actions::useItem(const std::shared_ptr &player, const Position &pos, uint8_t index, const std::shared_ptr &item, bool isHotkey) { const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { @@ -420,7 +422,7 @@ bool Actions::useItem(std::shared_ptr player, const Position &pos, uint8 return true; } -bool Actions::useItemEx(std::shared_ptr player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, std::shared_ptr item, bool isHotkey, std::shared_ptr creature /* = nullptr*/) { +bool Actions::useItemEx(const std::shared_ptr &player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, const std::shared_ptr &item, bool isHotkey, const std::shared_ptr &creature /* = nullptr*/) { const ItemType &it = Item::items[item->getID()]; if (it.isRune() || it.type == ITEM_TYPE_POTION) { if (player->walkExhausted()) { @@ -472,7 +474,7 @@ bool Actions::useItemEx(std::shared_ptr player, const Position &fromPos, return true; } -void Actions::showUseHotkeyMessage(std::shared_ptr player, std::shared_ptr item, uint32_t count) { +void Actions::showUseHotkeyMessage(const std::shared_ptr &player, const std::shared_ptr &item, uint32_t count) { std::ostringstream ss; const ItemType &it = Item::items[item->getID()]; @@ -508,19 +510,19 @@ std::shared_ptr Action::getTarget(std::shared_ptr player, std::sh if (targetCreature != nullptr) { return targetCreature; } - return g_game().internalGetThing(player, toPosition, toStackPos, 0, STACKPOS_USETARGET); + return g_game().internalGetThing(std::move(player), toPosition, toStackPos, 0, STACKPOS_USETARGET); } bool Action::executeUse(std::shared_ptr player, std::shared_ptr item, const Position &fromPosition, std::shared_ptr target, const Position &toPosition, bool isHotkey) { // onUse(player, item, fromPosition, target, toPosition, isHotkey) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Action::executeUse - Player {}, on item {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), item->getName()); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -533,7 +535,7 @@ bool Action::executeUse(std::shared_ptr player, std::shared_ptr it LuaScriptInterface::pushThing(L, item); LuaScriptInterface::pushPosition(L, fromPosition); - LuaScriptInterface::pushThing(L, target); + LuaScriptInterface::pushThing(L, std::move(target)); LuaScriptInterface::pushPosition(L, toPosition); LuaScriptInterface::pushBoolean(L, isHotkey); diff --git a/src/lua/creature/actions.hpp b/src/lua/creature/actions.hpp index 81a7754a5b1..b29e8b794db 100644 --- a/src/lua/creature/actions.hpp +++ b/src/lua/creature/actions.hpp @@ -143,18 +143,18 @@ class Actions final : public Scripts { return inject(); } - bool useItem(std::shared_ptr player, const Position &pos, uint8_t index, std::shared_ptr item, bool isHotkey); - bool useItemEx(std::shared_ptr player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, std::shared_ptr item, bool isHotkey, std::shared_ptr creature = nullptr); - - ReturnValue canUse(std::shared_ptr player, const Position &pos); - ReturnValue canUse(std::shared_ptr player, const Position &pos, std::shared_ptr item); - ReturnValue canUseFar(std::shared_ptr creature, const Position &toPos, bool checkLineOfSight, bool checkFloor); - - bool registerLuaItemEvent(const std::shared_ptr action); - bool registerLuaUniqueEvent(const std::shared_ptr action); - bool registerLuaActionEvent(const std::shared_ptr action); - bool registerLuaPositionEvent(const std::shared_ptr action); - bool registerLuaEvent(const std::shared_ptr action); + bool useItem(const std::shared_ptr &player, const Position &pos, uint8_t index, const std::shared_ptr &item, bool isHotkey); + bool useItemEx(const std::shared_ptr &player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, const std::shared_ptr &item, bool isHotkey, const std::shared_ptr &creature = nullptr); + + ReturnValue canUse(const std::shared_ptr &player, const Position &pos); + ReturnValue canUse(std::shared_ptr player, const Position &pos, const std::shared_ptr &item); + ReturnValue canUseFar(const std::shared_ptr &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor); + + bool registerLuaItemEvent(const std::shared_ptr &action); + bool registerLuaUniqueEvent(const std::shared_ptr &action); + bool registerLuaActionEvent(const std::shared_ptr &action); + bool registerLuaPositionEvent(const std::shared_ptr &action); + bool registerLuaEvent(const std::shared_ptr &action); // Clear maps for reloading void clear(); @@ -183,7 +183,7 @@ class Actions final : public Scripts { return false; } - void setItemId(uint16_t itemId, const std::shared_ptr action) { + void setItemId(uint16_t itemId, const std::shared_ptr &action) { useItemMap.try_emplace(itemId, action); } @@ -195,7 +195,7 @@ class Actions final : public Scripts { return false; } - void setUniqueId(uint16_t uniqueId, const std::shared_ptr action) { + void setUniqueId(uint16_t uniqueId, const std::shared_ptr &action) { uniqueItemMap.try_emplace(uniqueId, action); } @@ -207,12 +207,12 @@ class Actions final : public Scripts { return false; } - void setActionId(uint16_t actionId, const std::shared_ptr action) { + void setActionId(uint16_t actionId, const std::shared_ptr &action) { actionItemMap.try_emplace(actionId, action); } - ReturnValue internalUseItem(std::shared_ptr player, const Position &pos, uint8_t index, std::shared_ptr item, bool isHotkey); - static void showUseHotkeyMessage(std::shared_ptr player, std::shared_ptr item, uint32_t count); + ReturnValue internalUseItem(const std::shared_ptr &player, const Position &pos, uint8_t index, const std::shared_ptr &item, bool isHotkey); + static void showUseHotkeyMessage(const std::shared_ptr &player, const std::shared_ptr &item, uint32_t count); using ActionUseMap = std::map>; ActionUseMap useItemMap; @@ -220,7 +220,7 @@ class Actions final : public Scripts { ActionUseMap actionItemMap; std::map> actionPositionMap; - std::shared_ptr getAction(std::shared_ptr item); + std::shared_ptr getAction(const std::shared_ptr &item); }; constexpr auto g_actions = Actions::getInstance; diff --git a/src/lua/creature/creatureevent.cpp b/src/lua/creature/creatureevent.cpp index 09dbdf086ce..7d6f620862c 100644 --- a/src/lua/creature/creatureevent.cpp +++ b/src/lua/creature/creatureevent.cpp @@ -19,7 +19,7 @@ void CreatureEvents::clear() { } } -bool CreatureEvents::registerLuaEvent(const std::shared_ptr creatureEvent) { +bool CreatureEvents::registerLuaEvent(const std::shared_ptr &creatureEvent) { if (creatureEvent->getEventType() == CREATURE_EVENT_NONE) { g_logger().error( "[{}] - Trying to register event without type for script: {}", @@ -29,7 +29,7 @@ bool CreatureEvents::registerLuaEvent(const std::shared_ptr creat return false; } - const std::shared_ptr oldEvent = getEventByName(creatureEvent->getName(), false); + const auto &oldEvent = getEventByName(creatureEvent->getName(), false); if (oldEvent) { // if there was an event with the same that is not loaded //(happens when realoading), it is reused @@ -55,7 +55,7 @@ std::shared_ptr CreatureEvents::getEventByName(const std::string return nullptr; } -bool CreatureEvents::playerLogin(std::shared_ptr player) const { +bool CreatureEvents::playerLogin(const std::shared_ptr &player) const { // fire global event if is registered for (const auto &it : creatureEvents) { if (it.second->getEventType() == CREATURE_EVENT_LOGIN) { @@ -67,7 +67,7 @@ bool CreatureEvents::playerLogin(std::shared_ptr player) const { return true; } -bool CreatureEvents::playerLogout(std::shared_ptr player) const { +bool CreatureEvents::playerLogout(const std::shared_ptr &player) const { // fire global event if is registered for (const auto &it : creatureEvents) { if (it.second->getEventType() == CREATURE_EVENT_LOGOUT) { @@ -80,7 +80,7 @@ bool CreatureEvents::playerLogout(std::shared_ptr player) const { } bool CreatureEvents::playerAdvance( - std::shared_ptr player, + const std::shared_ptr &player, skills_t skill, uint32_t oldLevel, uint32_t newLevel @@ -151,11 +151,11 @@ std::string CreatureEvent::getScriptTypeName() const { case CREATURE_EVENT_NONE: default: - return std::string(); + return {}; } } -void CreatureEvent::copyEvent(const std::shared_ptr creatureEvent) { +void CreatureEvent::copyEvent(const std::shared_ptr &creatureEvent) { setScriptId(creatureEvent->getScriptId()); setScriptInterface(creatureEvent->getScriptInterface()); setLoadedCallback(creatureEvent->isLoadedCallback()); @@ -169,16 +169,16 @@ void CreatureEvent::clearEvent() { loaded = false; } -bool CreatureEvent::executeOnLogin(std::shared_ptr player) const { +bool CreatureEvent::executeOnLogin(const std::shared_ptr &player) const { // onLogin(player) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnLogin - Player {} event {}]" "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -189,16 +189,16 @@ bool CreatureEvent::executeOnLogin(std::shared_ptr player) const { return getScriptInterface()->callFunction(1); } -bool CreatureEvent::executeOnLogout(std::shared_ptr player) const { +bool CreatureEvent::executeOnLogout(const std::shared_ptr &player) const { // onLogout(player) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnLogout - Player {} event {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -209,16 +209,16 @@ bool CreatureEvent::executeOnLogout(std::shared_ptr player) const { return getScriptInterface()->callFunction(1); } -bool CreatureEvent::executeOnThink(std::shared_ptr creature, uint32_t interval) const { +bool CreatureEvent::executeOnThink(const std::shared_ptr &creature, uint32_t interval) const { // onThink(creature, interval) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnThink - Creature {} event {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -231,16 +231,16 @@ bool CreatureEvent::executeOnThink(std::shared_ptr creature, uint32_t return getScriptInterface()->callFunction(2); } -bool CreatureEvent::executeOnPrepareDeath(std::shared_ptr creature, std::shared_ptr killer) const { +bool CreatureEvent::executeOnPrepareDeath(const std::shared_ptr &creature, const std::shared_ptr &killer) const { // onPrepareDeath(creature, killer) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnPrepareDeath - Creature {} killer {}" " event {}] Call stack overflow. Too many lua script calls being nested.", creature->getName(), killer->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -260,16 +260,16 @@ bool CreatureEvent::executeOnPrepareDeath(std::shared_ptr creature, st return getScriptInterface()->callFunction(2); } -bool CreatureEvent::executeOnDeath(std::shared_ptr creature, std::shared_ptr corpse, std::shared_ptr killer, std::shared_ptr mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const { +bool CreatureEvent::executeOnDeath(const std::shared_ptr &creature, const std::shared_ptr &corpse, const std::shared_ptr &killer, const std::shared_ptr &mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const { // onDeath(creature, corpse, lasthitkiller, mostdamagekiller, lasthitunjustified, mostdamageunjustified) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnDeath - Creature {} killer {} event {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), killer->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -300,16 +300,16 @@ bool CreatureEvent::executeOnDeath(std::shared_ptr creature, std::shar return getScriptInterface()->callFunction(6); } -bool CreatureEvent::executeAdvance(std::shared_ptr player, skills_t skill, uint32_t oldLevel, uint32_t newLevel) const { +bool CreatureEvent::executeAdvance(const std::shared_ptr &player, skills_t skill, uint32_t oldLevel, uint32_t newLevel) const { // onAdvance(player, skill, oldLevel, newLevel) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeAdvance - Player {} event {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -327,19 +327,19 @@ bool CreatureEvent::executeAdvance(std::shared_ptr player, skills_t skil /** * @deprecated Prefer using registered onDeath events instead for better performance. */ -void CreatureEvent::executeOnKill(std::shared_ptr creature, std::shared_ptr target, bool lastHit) const { +void CreatureEvent::executeOnKill(const std::shared_ptr &creature, const std::shared_ptr &target, bool lastHit) const { // onKill(creature, target, lastHit) g_logger().warn("[CreatureEvent::executeOnKill - Creature {} target {} event {}] " "Deprecated use of onKill event. Use registered onDeath events instead for better performance.", creature->getName(), target->getName(), getName()); - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeOnKill - Creature {} target {} event {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), target->getName(), getName()); return; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -353,9 +353,9 @@ void CreatureEvent::executeOnKill(std::shared_ptr creature, std::share getScriptInterface()->callVoidFunction(3); } -void CreatureEvent::executeModalWindow(std::shared_ptr player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const { +void CreatureEvent::executeModalWindow(const std::shared_ptr &player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const { // onModalWindow(player, modalWindowId, buttonId, choiceId) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeModalWindow - " "Player {} modaw window id {} event {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -363,7 +363,7 @@ void CreatureEvent::executeModalWindow(std::shared_ptr player, uint32_t return; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -379,16 +379,16 @@ void CreatureEvent::executeModalWindow(std::shared_ptr player, uint32_t getScriptInterface()->callVoidFunction(4); } -bool CreatureEvent::executeTextEdit(std::shared_ptr player, std::shared_ptr item, const std::string &text) const { +bool CreatureEvent::executeTextEdit(const std::shared_ptr &player, const std::shared_ptr &item, const std::string &text) const { // onTextEdit(player, item, text) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeTextEdit - Player {} event {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -403,9 +403,9 @@ bool CreatureEvent::executeTextEdit(std::shared_ptr player, std::shared_ return getScriptInterface()->callFunction(3); } -void CreatureEvent::executeHealthChange(std::shared_ptr creature, std::shared_ptr attacker, CombatDamage &damage) const { +void CreatureEvent::executeHealthChange(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatDamage &damage) const { // onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeHealthChange - " "Creature {} attacker {} event {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -413,7 +413,7 @@ void CreatureEvent::executeHealthChange(std::shared_ptr creature, std: return; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -430,7 +430,7 @@ void CreatureEvent::executeHealthChange(std::shared_ptr creature, std: LuaScriptInterface::pushCombatDamage(L, damage); - if (getScriptInterface()->protectedCall(L, 7, 4) != 0) { + if (LuaScriptInterface::protectedCall(L, 7, 4) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { damage.primary.value = std::abs(LuaScriptInterface::getNumber(L, -4)); @@ -445,12 +445,12 @@ void CreatureEvent::executeHealthChange(std::shared_ptr creature, std: } } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void CreatureEvent::executeManaChange(std::shared_ptr creature, std::shared_ptr attacker, CombatDamage &damage) const { +void CreatureEvent::executeManaChange(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatDamage &damage) const { // onManaChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeManaChange - " "Creature {} attacker {} event {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -458,7 +458,7 @@ void CreatureEvent::executeManaChange(std::shared_ptr creature, std::s return; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -475,7 +475,7 @@ void CreatureEvent::executeManaChange(std::shared_ptr creature, std::s LuaScriptInterface::pushCombatDamage(L, damage); - if (getScriptInterface()->protectedCall(L, 7, 4) != 0) { + if (LuaScriptInterface::protectedCall(L, 7, 4) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { damage.primary.value = LuaScriptInterface::getNumber(L, -4); @@ -485,12 +485,12 @@ void CreatureEvent::executeManaChange(std::shared_ptr creature, std::s lua_pop(L, 4); } - getScriptInterface()->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void CreatureEvent::executeExtendedOpcode(std::shared_ptr player, uint8_t opcode, const std::string &buffer) const { +void CreatureEvent::executeExtendedOpcode(const std::shared_ptr &player, uint8_t opcode, const std::string &buffer) const { // onExtendedOpcode(player, opcode, buffer) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CreatureEvent::executeExtendedOpcode - " "Player {} event {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -498,7 +498,7 @@ void CreatureEvent::executeExtendedOpcode(std::shared_ptr player, uint8_ return; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); diff --git a/src/lua/creature/creatureevent.hpp b/src/lua/creature/creatureevent.hpp index 8a208343e11..a8bc8c02953 100644 --- a/src/lua/creature/creatureevent.hpp +++ b/src/lua/creature/creatureevent.hpp @@ -40,21 +40,21 @@ class CreatureEvent final : public Script { } void clearEvent(); - void copyEvent(const std::shared_ptr creatureEvent); + void copyEvent(const std::shared_ptr &creatureEvent); // scripting - bool executeOnLogin(std::shared_ptr player) const; - bool executeOnLogout(std::shared_ptr player) const; - bool executeOnThink(std::shared_ptr creature, uint32_t interval) const; - bool executeOnPrepareDeath(std::shared_ptr creature, std::shared_ptr killer) const; - bool executeOnDeath(std::shared_ptr creature, std::shared_ptr corpse, std::shared_ptr killer, std::shared_ptr mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const; - void executeOnKill(std::shared_ptr creature, std::shared_ptr target, bool lastHit) const; - bool executeAdvance(std::shared_ptr player, skills_t, uint32_t, uint32_t) const; - void executeModalWindow(std::shared_ptr player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const; - bool executeTextEdit(std::shared_ptr player, std::shared_ptr item, const std::string &text) const; - void executeHealthChange(std::shared_ptr creature, std::shared_ptr attacker, CombatDamage &damage) const; - void executeManaChange(std::shared_ptr creature, std::shared_ptr attacker, CombatDamage &damage) const; - void executeExtendedOpcode(std::shared_ptr player, uint8_t opcode, const std::string &buffer) const; + bool executeOnLogin(const std::shared_ptr &player) const; + bool executeOnLogout(const std::shared_ptr &player) const; + bool executeOnThink(const std::shared_ptr &creature, uint32_t interval) const; + bool executeOnPrepareDeath(const std::shared_ptr &creature, const std::shared_ptr &killer) const; + bool executeOnDeath(const std::shared_ptr &creature, const std::shared_ptr &corpse, const std::shared_ptr &killer, const std::shared_ptr &mostDamageKiller, bool lastHitUnjustified, bool mostDamageUnjustified) const; + void executeOnKill(const std::shared_ptr &creature, const std::shared_ptr &target, bool lastHit) const; + bool executeAdvance(const std::shared_ptr &player, skills_t, uint32_t, uint32_t) const; + void executeModalWindow(const std::shared_ptr &player, uint32_t modalWindowId, uint8_t buttonId, uint8_t choiceId) const; + bool executeTextEdit(const std::shared_ptr &player, const std::shared_ptr &item, const std::string &text) const; + void executeHealthChange(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatDamage &damage) const; + void executeManaChange(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatDamage &damage) const; + void executeExtendedOpcode(const std::shared_ptr &player, uint8_t opcode, const std::string &buffer) const; // private: @@ -78,13 +78,13 @@ class CreatureEvents final : public Scripts { } // global events - bool playerLogin(std::shared_ptr player) const; - bool playerLogout(std::shared_ptr player) const; - bool playerAdvance(std::shared_ptr player, skills_t, uint32_t, uint32_t) const; + bool playerLogin(const std::shared_ptr &player) const; + bool playerLogout(const std::shared_ptr &player) const; + bool playerAdvance(const std::shared_ptr &player, skills_t, uint32_t, uint32_t) const; std::shared_ptr getEventByName(const std::string &name, bool forceLoaded = true); - bool registerLuaEvent(const std::shared_ptr event); + bool registerLuaEvent(const std::shared_ptr &event); void removeInvalidEvents(); void clear(); diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 8bdd53465b3..78bd8ede9bc 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "lua/creature/events.hpp" @@ -156,7 +158,7 @@ void Events::eventMonsterOnSpawn(std::shared_ptr monster, const Positio return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" ". Call stack overflow. Too many lua script calls being nested.", @@ -164,23 +166,23 @@ void Events::eventMonsterOnSpawn(std::shared_ptr monster, const Positio return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.monsterOnSpawn, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnSpawn); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushUserdata(L, std::move(monster)); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushPosition(L, position); - if (scriptInterface.protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Npc @@ -190,7 +192,7 @@ void Events::eventNpcOnSpawn(std::shared_ptr npc, const Position &position) return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" ". Call stack overflow. Too many lua script calls being nested.", @@ -198,40 +200,40 @@ void Events::eventNpcOnSpawn(std::shared_ptr npc, const Position &position) return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.npcOnSpawn, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.npcOnSpawn); - LuaScriptInterface::pushUserdata(L, npc); + LuaScriptInterface::pushUserdata(L, std::move(npc)); LuaScriptInterface::setMetatable(L, -1, "Npc"); LuaScriptInterface::pushPosition(L, position); - if (scriptInterface.protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Creature -bool Events::eventCreatureOnChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit) { +bool Events::eventCreatureOnChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) { // Creature:onChangeOutfit(outfit) or Creature.onChangeOutfit(self, outfit) if (info.creatureOnChangeOutfit == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventCreatureOnChangeOutfit - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.creatureOnChangeOutfit, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -245,13 +247,13 @@ bool Events::eventCreatureOnChangeOutfit(std::shared_ptr creature, con return scriptInterface.callFunction(2); } -ReturnValue Events::eventCreatureOnAreaCombat(std::shared_ptr creature, std::shared_ptr tile, bool aggressive) { +ReturnValue Events::eventCreatureOnAreaCombat(const std::shared_ptr &creature, const std::shared_ptr &tile, bool aggressive) { // Creature:onAreaCombat(tile, aggressive) or Creature.onAreaCombat(self, tile, aggressive) if (info.creatureOnAreaCombat == -1) { return RETURNVALUE_NOERROR; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventCreatureOnAreaCombat - " "Creature {} on tile position {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -259,7 +261,7 @@ ReturnValue Events::eventCreatureOnAreaCombat(std::shared_ptr creature return RETURNVALUE_NOTPOSSIBLE; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.creatureOnAreaCombat, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -278,7 +280,7 @@ ReturnValue Events::eventCreatureOnAreaCombat(std::shared_ptr creature LuaScriptInterface::pushBoolean(L, aggressive); ReturnValue returnValue; - if (scriptInterface.protectedCall(L, 3, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 3, 1) != 0) { returnValue = RETURNVALUE_NOTPOSSIBLE; LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { @@ -286,17 +288,17 @@ ReturnValue Events::eventCreatureOnAreaCombat(std::shared_ptr creature lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return returnValue; } -ReturnValue Events::eventCreatureOnTargetCombat(std::shared_ptr creature, std::shared_ptr target) { +ReturnValue Events::eventCreatureOnTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target) { // Creature:onTargetCombat(target) or Creature.onTargetCombat(self, target) if (info.creatureOnTargetCombat == -1) { return RETURNVALUE_NOERROR; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventCreatureOnTargetCombat - " "Creature {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -304,7 +306,7 @@ ReturnValue Events::eventCreatureOnTargetCombat(std::shared_ptr creatu return RETURNVALUE_NOTPOSSIBLE; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.creatureOnTargetCombat, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -321,7 +323,7 @@ ReturnValue Events::eventCreatureOnTargetCombat(std::shared_ptr creatu LuaScriptInterface::setCreatureMetatable(L, -1, target); ReturnValue returnValue; - if (scriptInterface.protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { returnValue = RETURNVALUE_NOTPOSSIBLE; LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { @@ -329,17 +331,17 @@ ReturnValue Events::eventCreatureOnTargetCombat(std::shared_ptr creatu lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return returnValue; } -void Events::eventCreatureOnHear(std::shared_ptr creature, std::shared_ptr speaker, const std::string &words, SpeakClasses type) { +void Events::eventCreatureOnHear(const std::shared_ptr &creature, const std::shared_ptr &speaker, const std::string &words, SpeakClasses type) { // Creature:onHear(speaker, words, type) if (info.creatureOnHear == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventCreatureOnHear - " "Creature {} speaker {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -347,7 +349,7 @@ void Events::eventCreatureOnHear(std::shared_ptr creature, std::shared return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.creatureOnHear, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -365,12 +367,12 @@ void Events::eventCreatureOnHear(std::shared_ptr creature, std::shared scriptInterface.callVoidFunction(4); } -void Events::eventCreatureOnDrainHealth(std::shared_ptr creature, std::shared_ptr attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) { +void Events::eventCreatureOnDrainHealth(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) { if (info.creatureOnDrainHealth == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventCreatureOnDrainHealth - " "Creature {} attacker {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -378,7 +380,7 @@ void Events::eventCreatureOnDrainHealth(std::shared_ptr creature, std: return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.creatureOnDrainHealth, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -405,7 +407,7 @@ void Events::eventCreatureOnDrainHealth(std::shared_ptr creature, std: lua_pushnumber(L, colorPrimary); lua_pushnumber(L, colorSecondary); - if (scriptInterface.protectedCall(L, 8, 6) != 0) { + if (LuaScriptInterface::protectedCall(L, 8, 6) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { typePrimary = LuaScriptInterface::getNumber(L, -6); @@ -417,17 +419,17 @@ void Events::eventCreatureOnDrainHealth(std::shared_ptr creature, std: lua_pop(L, 6); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Party -bool Events::eventPartyOnJoin(std::shared_ptr party, std::shared_ptr player) { +bool Events::eventPartyOnJoin(std::shared_ptr party, const std::shared_ptr &player) { // Party:onJoin(player) or Party.onJoin(self, player) if (info.partyOnJoin == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPartyOnJoin - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -435,13 +437,13 @@ bool Events::eventPartyOnJoin(std::shared_ptr party, std::shared_ptrsetScriptId(info.partyOnJoin, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.partyOnJoin); - LuaScriptInterface::pushUserdata(L, party); + LuaScriptInterface::pushUserdata(L, std::move(party)); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata(L, player); @@ -450,13 +452,13 @@ bool Events::eventPartyOnJoin(std::shared_ptr party, std::shared_ptr party, std::shared_ptr player) { +bool Events::eventPartyOnLeave(std::shared_ptr party, const std::shared_ptr &player) { // Party:onLeave(player) or Party.onLeave(self, player) if (info.partyOnLeave == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPartyOnLeave - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -464,13 +466,13 @@ bool Events::eventPartyOnLeave(std::shared_ptr party, std::shared_ptrsetScriptId(info.partyOnLeave, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.partyOnLeave); - LuaScriptInterface::pushUserdata(L, party); + LuaScriptInterface::pushUserdata(L, std::move(party)); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata(L, player); @@ -479,20 +481,20 @@ bool Events::eventPartyOnLeave(std::shared_ptr party, std::shared_ptr party) { +bool Events::eventPartyOnDisband(const std::shared_ptr &party) { // Party:onDisband() or Party.onDisband(self) if (info.partyOnDisband == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPartyOnDisband - Party leader {}] Call stack " "overflow. Too many lua script calls being nested.", party->getLeader() ? party->getLeader()->getName() : "unknown"); return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.partyOnDisband, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -504,18 +506,18 @@ bool Events::eventPartyOnDisband(std::shared_ptr party) { return scriptInterface.callFunction(1); } -void Events::eventPartyOnShareExperience(std::shared_ptr party, uint64_t &exp) { +void Events::eventPartyOnShareExperience(const std::shared_ptr &party, uint64_t &exp) { // Party:onShareExperience(exp) or Party.onShareExperience(self, exp) if (info.partyOnShareExperience == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Party leader {}. Call stack overflow. Too many lua script calls being nested.", party->getLeader() ? party->getLeader()->getName() : "unknown"); return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.partyOnShareExperience, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -526,24 +528,24 @@ void Events::eventPartyOnShareExperience(std::shared_ptr party, uint64_t lua_pushnumber(L, exp); - if (scriptInterface.protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } // Player -bool Events::eventPlayerOnBrowseField(std::shared_ptr player, const Position &position) { +bool Events::eventPlayerOnBrowseField(const std::shared_ptr &player, const Position &position) { // Player:onBrowseField(position) or Player.onBrowseField(self, position) if (info.playerOnBrowseField == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnBrowseField - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -551,7 +553,7 @@ bool Events::eventPlayerOnBrowseField(std::shared_ptr player, const Posi return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnBrowseField, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -565,13 +567,13 @@ bool Events::eventPlayerOnBrowseField(std::shared_ptr player, const Posi return scriptInterface.callFunction(2); } -void Events::eventPlayerOnLook(std::shared_ptr player, const Position &position, std::shared_ptr thing, uint8_t stackpos, int32_t lookDistance) { +void Events::eventPlayerOnLook(const std::shared_ptr &player, const Position &position, const std::shared_ptr &thing, uint8_t stackpos, int32_t lookDistance) { // Player:onLook(thing, position, distance) or Player.onLook(self, thing, position, distance) if (info.playerOnLook == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnLook - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -579,7 +581,7 @@ void Events::eventPlayerOnLook(std::shared_ptr player, const Position &p return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnLook, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -604,13 +606,13 @@ void Events::eventPlayerOnLook(std::shared_ptr player, const Position &p scriptInterface.callVoidFunction(4); } -void Events::eventPlayerOnLookInBattleList(std::shared_ptr player, std::shared_ptr creature, int32_t lookDistance) { +void Events::eventPlayerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance) { // Player:onLookInBattleList(creature, position, distance) or Player.onLookInBattleList(self, creature, position, distance) if (info.playerOnLookInBattleList == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnLookInBattleList - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -618,7 +620,7 @@ void Events::eventPlayerOnLookInBattleList(std::shared_ptr player, std:: return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnLookInBattleList, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -635,13 +637,13 @@ void Events::eventPlayerOnLookInBattleList(std::shared_ptr player, std:: scriptInterface.callVoidFunction(3); } -void Events::eventPlayerOnLookInTrade(std::shared_ptr player, std::shared_ptr partner, std::shared_ptr item, int32_t lookDistance) { +void Events::eventPlayerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance) { // Player:onLookInTrade(partner, item, distance) or Player.onLookInTrade(self, partner, item, distance) if (info.playerOnLookInTrade == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnLookInTrade - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -649,7 +651,7 @@ void Events::eventPlayerOnLookInTrade(std::shared_ptr player, std::share return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnLookInTrade, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -658,7 +660,7 @@ void Events::eventPlayerOnLookInTrade(std::shared_ptr player, std::share LuaScriptInterface::pushUserdata(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata(L, partner); + LuaScriptInterface::pushUserdata(L, std::move(partner)); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, item); @@ -669,13 +671,13 @@ void Events::eventPlayerOnLookInTrade(std::shared_ptr player, std::share scriptInterface.callVoidFunction(4); } -bool Events::eventPlayerOnLookInShop(std::shared_ptr player, const ItemType* itemType, uint8_t count) { +bool Events::eventPlayerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count) { // Player:onLookInShop(itemType, count) or Player.onLookInShop(self, itemType, count) if (info.playerOnLookInShop == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnLookInShop - " "Player {} itemType {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -683,7 +685,7 @@ bool Events::eventPlayerOnLookInShop(std::shared_ptr player, const ItemT return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnLookInShop, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -700,13 +702,13 @@ bool Events::eventPlayerOnLookInShop(std::shared_ptr player, const ItemT return scriptInterface.callFunction(3); } -bool Events::eventPlayerOnRemoveCount(std::shared_ptr player, std::shared_ptr item) { +bool Events::eventPlayerOnRemoveCount(const std::shared_ptr &player, const std::shared_ptr &item) { // Player:onMove() if (info.playerOnRemoveCount == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnMove - " "Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -714,7 +716,7 @@ bool Events::eventPlayerOnRemoveCount(std::shared_ptr player, std::share return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnRemoveCount, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -729,13 +731,13 @@ bool Events::eventPlayerOnRemoveCount(std::shared_ptr player, std::share return scriptInterface.callFunction(2); } -bool Events::eventPlayerOnMoveItem(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { +bool Events::eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { // Player:onMoveItem(item, count, fromPosition, toPosition) or Player.onMoveItem(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnMoveItem == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnMoveItem - " "Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -743,7 +745,7 @@ bool Events::eventPlayerOnMoveItem(std::shared_ptr player, std::shared_p return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnMoveItem, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -759,19 +761,19 @@ bool Events::eventPlayerOnMoveItem(std::shared_ptr player, std::shared_p LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, fromCylinder); - LuaScriptInterface::pushCylinder(L, toCylinder); + LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); + LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); return scriptInterface.callFunction(7); } -void Events::eventPlayerOnItemMoved(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { +void Events::eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { // Player:onItemMoved(item, count, fromPosition, toPosition) or Player.onItemMoved(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnItemMoved == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnItemMoved - " "Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -779,7 +781,7 @@ void Events::eventPlayerOnItemMoved(std::shared_ptr player, std::shared_ return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnItemMoved, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -795,19 +797,19 @@ void Events::eventPlayerOnItemMoved(std::shared_ptr player, std::shared_ LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, fromCylinder); - LuaScriptInterface::pushCylinder(L, toCylinder); + LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); + LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); scriptInterface.callVoidFunction(7); } -void Events::eventPlayerOnChangeZone(std::shared_ptr player, ZoneType_t zone) { +void Events::eventPlayerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone) { // Player:onChangeZone(zone) if (info.playerOnChangeZone == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnChangeZone - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -815,7 +817,7 @@ void Events::eventPlayerOnChangeZone(std::shared_ptr player, ZoneType_t return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnChangeZone, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -828,13 +830,13 @@ void Events::eventPlayerOnChangeZone(std::shared_ptr player, ZoneType_t scriptInterface.callVoidFunction(2); } -bool Events::eventPlayerOnMoveCreature(std::shared_ptr player, std::shared_ptr creature, const Position &fromPosition, const Position &toPosition) { +bool Events::eventPlayerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition) { // Player:onMoveCreature(creature, fromPosition, toPosition) or Player.onMoveCreature(self, creature, fromPosition, toPosition) if (info.playerOnMoveCreature == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnMoveCreature - " "Player {} creature {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -842,7 +844,7 @@ bool Events::eventPlayerOnMoveCreature(std::shared_ptr player, std::shar return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnMoveCreature, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -860,13 +862,13 @@ bool Events::eventPlayerOnMoveCreature(std::shared_ptr player, std::shar return scriptInterface.callFunction(4); } -void Events::eventPlayerOnReportRuleViolation(std::shared_ptr player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { +void Events::eventPlayerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { // Player:onReportRuleViolation(targetName, reportType, reportReason, comment, translation) if (info.playerOnReportRuleViolation == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnReportRuleViolation - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -874,7 +876,7 @@ void Events::eventPlayerOnReportRuleViolation(std::shared_ptr player, co return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnReportRuleViolation, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -894,13 +896,13 @@ void Events::eventPlayerOnReportRuleViolation(std::shared_ptr player, co scriptInterface.callVoidFunction(6); } -bool Events::eventPlayerOnReportBug(std::shared_ptr player, const std::string &message, const Position &position, uint8_t category) { +bool Events::eventPlayerOnReportBug(const std::shared_ptr &player, const std::string &message, const Position &position, uint8_t category) { // Player:onReportBug(message, position, category) if (info.playerOnReportBug == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnReportBug - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -908,7 +910,7 @@ bool Events::eventPlayerOnReportBug(std::shared_ptr player, const std::s return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnReportBug, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -924,13 +926,13 @@ bool Events::eventPlayerOnReportBug(std::shared_ptr player, const std::s return scriptInterface.callFunction(4); } -bool Events::eventPlayerOnTurn(std::shared_ptr player, Direction direction) { +bool Events::eventPlayerOnTurn(const std::shared_ptr &player, Direction direction) { // Player:onTurn(direction) or Player.onTurn(self, direction) if (info.playerOnTurn == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnTurn - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -938,7 +940,7 @@ bool Events::eventPlayerOnTurn(std::shared_ptr player, Direction directi return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnTurn, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -952,13 +954,13 @@ bool Events::eventPlayerOnTurn(std::shared_ptr player, Direction directi return scriptInterface.callFunction(2); } -bool Events::eventPlayerOnTradeRequest(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) { +bool Events::eventPlayerOnTradeRequest(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item) { // Player:onTradeRequest(target, item) if (info.playerOnTradeRequest == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnTradeRequest - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -966,7 +968,7 @@ bool Events::eventPlayerOnTradeRequest(std::shared_ptr player, std::shar return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnTradeRequest, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -984,13 +986,13 @@ bool Events::eventPlayerOnTradeRequest(std::shared_ptr player, std::shar return scriptInterface.callFunction(3); } -bool Events::eventPlayerOnTradeAccept(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, std::shared_ptr targetItem) { +bool Events::eventPlayerOnTradeAccept(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, const std::shared_ptr &targetItem) { // Player:onTradeAccept(target, item, targetItem) if (info.playerOnTradeAccept == -1) { return true; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnTradeAccept - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -998,7 +1000,7 @@ bool Events::eventPlayerOnTradeAccept(std::shared_ptr player, std::share return false; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnTradeAccept, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1019,14 +1021,14 @@ bool Events::eventPlayerOnTradeAccept(std::shared_ptr player, std::share return scriptInterface.callFunction(4); } -void Events::eventPlayerOnGainExperience(std::shared_ptr player, std::shared_ptr target, uint64_t &exp, uint64_t rawExp) { +void Events::eventPlayerOnGainExperience(const std::shared_ptr &player, const std::shared_ptr &target, uint64_t &exp, uint64_t rawExp) { // Player:onGainExperience(target, exp, rawExp) // rawExp gives the original exp which is not multiplied if (info.playerOnGainExperience == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnGainExperience - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1034,7 +1036,7 @@ void Events::eventPlayerOnGainExperience(std::shared_ptr player, std::sh return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnGainExperience, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1053,23 +1055,23 @@ void Events::eventPlayerOnGainExperience(std::shared_ptr player, std::sh lua_pushnumber(L, exp); lua_pushnumber(L, rawExp); - if (scriptInterface.protectedCall(L, 4, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 4, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void Events::eventPlayerOnLoseExperience(std::shared_ptr player, uint64_t &exp) { +void Events::eventPlayerOnLoseExperience(const std::shared_ptr &player, uint64_t &exp) { // Player:onLoseExperience(exp) if (info.playerOnLoseExperience == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnLoseExperience - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1077,7 +1079,7 @@ void Events::eventPlayerOnLoseExperience(std::shared_ptr player, uint64_ return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnLoseExperience, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1088,23 +1090,23 @@ void Events::eventPlayerOnLoseExperience(std::shared_ptr player, uint64_ lua_pushnumber(L, exp); - if (scriptInterface.protectedCall(L, 2, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 2, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { exp = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void Events::eventPlayerOnGainSkillTries(std::shared_ptr player, skills_t skill, uint64_t &tries) { +void Events::eventPlayerOnGainSkillTries(const std::shared_ptr &player, skills_t skill, uint64_t &tries) { // Player:onGainSkillTries(skill, tries) if (info.playerOnGainSkillTries == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnGainSkillTries - " "Player {} skill {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1112,7 +1114,7 @@ void Events::eventPlayerOnGainSkillTries(std::shared_ptr player, skills_ return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnGainSkillTries, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1124,23 +1126,23 @@ void Events::eventPlayerOnGainSkillTries(std::shared_ptr player, skills_ lua_pushnumber(L, skill); lua_pushnumber(L, tries); - if (scriptInterface.protectedCall(L, 3, 1) != 0) { + if (LuaScriptInterface::protectedCall(L, 3, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { tries = LuaScriptInterface::getNumber(L, -1); lua_pop(L, 1); } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void Events::eventPlayerOnCombat(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, CombatDamage &damage) { +void Events::eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage) { // Player:onCombat(target, item, primaryDamage, primaryType, secondaryDamage, secondaryType) if (info.playerOnCombat == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnCombat - " "Player {} target {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1148,7 +1150,7 @@ void Events::eventPlayerOnCombat(std::shared_ptr player, std::shared_ptr return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnCombat, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1173,7 +1175,7 @@ void Events::eventPlayerOnCombat(std::shared_ptr player, std::shared_ptr LuaScriptInterface::pushCombatDamage(L, damage); - if (scriptInterface.protectedCall(L, 8, 4) != 0) { + if (LuaScriptInterface::protectedCall(L, 8, 4) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { damage.primary.value = std::abs(LuaScriptInterface::getNumber(L, -4)); @@ -1188,16 +1190,16 @@ void Events::eventPlayerOnCombat(std::shared_ptr player, std::shared_ptr } } - scriptInterface.resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -void Events::eventPlayerOnRequestQuestLog(std::shared_ptr player) { +void Events::eventPlayerOnRequestQuestLog(const std::shared_ptr &player) { // Player:onRequestQuestLog() if (info.playerOnRequestQuestLog == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnRequestQuestLog - " "Player {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1205,7 +1207,7 @@ void Events::eventPlayerOnRequestQuestLog(std::shared_ptr player) { return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnRequestQuestLog, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1217,13 +1219,13 @@ void Events::eventPlayerOnRequestQuestLog(std::shared_ptr player) { scriptInterface.callVoidFunction(1); } -void Events::eventPlayerOnRequestQuestLine(std::shared_ptr player, uint16_t questId) { +void Events::eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId) { // Player::onRequestQuestLine() if (info.playerOnRequestQuestLine == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventPlayerOnRequestQuestLine - " "Player {} questId {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1231,7 +1233,7 @@ void Events::eventPlayerOnRequestQuestLine(std::shared_ptr player, uint1 return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnRequestQuestLine, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1245,24 +1247,24 @@ void Events::eventPlayerOnRequestQuestLine(std::shared_ptr player, uint1 scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool equip) { +void Events::eventPlayerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[{}] Call stack overflow", __FUNCTION__); return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnInventoryUpdate, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnInventoryUpdate); - LuaScriptInterface::pushUserdata(L, player); + LuaScriptInterface::pushUserdata(L, std::move(player)); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata(L, item); @@ -1274,13 +1276,13 @@ void Events::eventPlayerOnInventoryUpdate(std::shared_ptr player, std::s scriptInterface.callVoidFunction(4); } -void Events::eventOnStorageUpdate(std::shared_ptr player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime) { +void Events::eventOnStorageUpdate(const std::shared_ptr &player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime) { // Player::onStorageUpdate(key, value, oldValue, currentTime) if (info.playerOnStorageUpdate == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventOnStorageUpdate - " "Player {} key {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1288,7 +1290,7 @@ void Events::eventOnStorageUpdate(std::shared_ptr player, const uint32_t return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.playerOnStorageUpdate, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); @@ -1306,13 +1308,13 @@ void Events::eventOnStorageUpdate(std::shared_ptr player, const uint32_t } // Monster -void Events::eventMonsterOnDropLoot(std::shared_ptr monster, std::shared_ptr corpse) { +void Events::eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse) { // Monster:onDropLoot(corpse) if (info.monsterOnDropLoot == -1) { return; } - if (!scriptInterface.reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Events::eventMonsterOnDropLoot - " "Monster corpse {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -1320,13 +1322,13 @@ void Events::eventMonsterOnDropLoot(std::shared_ptr monster, std::share return; } - ScriptEnvironment* env = scriptInterface.getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(info.monsterOnDropLoot, &scriptInterface); lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnDropLoot); - LuaScriptInterface::pushUserdata(L, monster); + LuaScriptInterface::pushUserdata(L, std::move(monster)); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata(L, corpse); diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index 1ec6d4ba81c..88dbf1f812b 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -81,45 +81,45 @@ class Events { } // Creature - bool eventCreatureOnChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit); - ReturnValue eventCreatureOnAreaCombat(std::shared_ptr creature, std::shared_ptr tile, bool aggressive); - ReturnValue eventCreatureOnTargetCombat(std::shared_ptr creature, std::shared_ptr target); - void eventCreatureOnHear(std::shared_ptr creature, std::shared_ptr speaker, const std::string &words, SpeakClasses type); - void eventCreatureOnDrainHealth(std::shared_ptr creature, std::shared_ptr attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary); + bool eventCreatureOnChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit); + ReturnValue eventCreatureOnAreaCombat(const std::shared_ptr &creature, const std::shared_ptr &tile, bool aggressive); + ReturnValue eventCreatureOnTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target); + void eventCreatureOnHear(const std::shared_ptr &creature, const std::shared_ptr &speaker, const std::string &words, SpeakClasses type); + void eventCreatureOnDrainHealth(const std::shared_ptr &creature, const std::shared_ptr &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary); // Party - bool eventPartyOnJoin(std::shared_ptr party, std::shared_ptr player); - bool eventPartyOnLeave(std::shared_ptr party, std::shared_ptr player); - bool eventPartyOnDisband(std::shared_ptr party); - void eventPartyOnShareExperience(std::shared_ptr party, uint64_t &exp); + bool eventPartyOnJoin(std::shared_ptr party, const std::shared_ptr &player); + bool eventPartyOnLeave(std::shared_ptr party, const std::shared_ptr &player); + bool eventPartyOnDisband(const std::shared_ptr &party); + void eventPartyOnShareExperience(const std::shared_ptr &party, uint64_t &exp); // Player - bool eventPlayerOnBrowseField(std::shared_ptr player, const Position &position); - void eventPlayerOnLook(std::shared_ptr player, const Position &position, std::shared_ptr thing, uint8_t stackpos, int32_t lookDistance); - void eventPlayerOnLookInBattleList(std::shared_ptr player, std::shared_ptr creature, int32_t lookDistance); - void eventPlayerOnLookInTrade(std::shared_ptr player, std::shared_ptr partner, std::shared_ptr item, int32_t lookDistance); - bool eventPlayerOnLookInShop(std::shared_ptr player, const ItemType* itemType, uint8_t count); - bool eventPlayerOnMoveItem(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); - void eventPlayerOnItemMoved(std::shared_ptr player, std::shared_ptr item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); - void eventPlayerOnChangeZone(std::shared_ptr player, ZoneType_t zone); - bool eventPlayerOnMoveCreature(std::shared_ptr player, std::shared_ptr creature, const Position &fromPosition, const Position &toPosition); - void eventPlayerOnReportRuleViolation(std::shared_ptr player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); - bool eventPlayerOnReportBug(std::shared_ptr player, const std::string &message, const Position &position, uint8_t category); - bool eventPlayerOnTurn(std::shared_ptr player, Direction direction); - bool eventPlayerOnTradeRequest(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item); - bool eventPlayerOnTradeAccept(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, std::shared_ptr targetItem); - void eventPlayerOnGainExperience(std::shared_ptr player, std::shared_ptr target, uint64_t &exp, uint64_t rawExp); - void eventPlayerOnLoseExperience(std::shared_ptr player, uint64_t &exp); - void eventPlayerOnGainSkillTries(std::shared_ptr player, skills_t skill, uint64_t &tries); - bool eventPlayerOnRemoveCount(std::shared_ptr player, std::shared_ptr item); - void eventPlayerOnRequestQuestLog(std::shared_ptr player); - void eventPlayerOnRequestQuestLine(std::shared_ptr player, uint16_t questId); - void eventOnStorageUpdate(std::shared_ptr player, const uint32_t key, const int32_t value, int32_t oldValue, uint64_t currentTime); - void eventPlayerOnCombat(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, CombatDamage &damage); - void eventPlayerOnInventoryUpdate(std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool equip); + bool eventPlayerOnBrowseField(const std::shared_ptr &player, const Position &position); + void eventPlayerOnLook(const std::shared_ptr &player, const Position &position, const std::shared_ptr &thing, uint8_t stackpos, int32_t lookDistance); + void eventPlayerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance); + void eventPlayerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance); + bool eventPlayerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count); + bool eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); + void eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); + void eventPlayerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone); + bool eventPlayerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition); + void eventPlayerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); + bool eventPlayerOnReportBug(const std::shared_ptr &player, const std::string &message, const Position &position, uint8_t category); + bool eventPlayerOnTurn(const std::shared_ptr &player, Direction direction); + bool eventPlayerOnTradeRequest(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item); + bool eventPlayerOnTradeAccept(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, const std::shared_ptr &targetItem); + void eventPlayerOnGainExperience(const std::shared_ptr &player, const std::shared_ptr &target, uint64_t &exp, uint64_t rawExp); + void eventPlayerOnLoseExperience(const std::shared_ptr &player, uint64_t &exp); + void eventPlayerOnGainSkillTries(const std::shared_ptr &player, skills_t skill, uint64_t &tries); + bool eventPlayerOnRemoveCount(const std::shared_ptr &player, const std::shared_ptr &item); + void eventPlayerOnRequestQuestLog(const std::shared_ptr &player); + void eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId); + void eventOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime); + void eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage); + void eventPlayerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip); // Monster - void eventMonsterOnDropLoot(std::shared_ptr monster, std::shared_ptr corpse); + void eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse); void eventMonsterOnSpawn(std::shared_ptr monster, const Position &position); // Monster diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index b75ff31c661..653a4bf568a 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -15,39 +15,14 @@ #include "lua/callbacks/events_callbacks.hpp" #include "lua/creature/movement.hpp" -void MoveEvents::clear(bool isFromXML /*= false*/) { - if (isFromXML) { - int numRemoved = 0; - for (auto &pair : itemIdMap) { - MoveEventList &moveEventList = pair.second; - - for (int moveEventType = 0; moveEventType < MOVE_EVENT_LAST; ++moveEventType) { - auto &eventList = moveEventList.moveEvent[moveEventType]; - - eventList.remove_if([&](const std::shared_ptr &moveEvent) { - bool removed = moveEvent && moveEvent->isFromXML(); - if (removed) { - g_logger().debug("MoveEvent with id '{}' is from XML and will be removed.", pair.first); - ++numRemoved; - } - return removed; - }); - } - } - - if (numRemoved > 0) { - g_logger().debug("Removed '{}' MoveEvent from XML.", numRemoved); - } - return; - } - +void MoveEvents::clear() { uniqueIdMap.clear(); actionIdMap.clear(); itemIdMap.clear(); positionsMap.clear(); } -bool MoveEvents::registerLuaItemEvent(const std::shared_ptr moveEvent) { +bool MoveEvents::registerLuaItemEvent(const std::shared_ptr &moveEvent) { auto itemIdVector = moveEvent->getItemIdsVector(); if (itemIdVector.empty()) { return false; @@ -73,7 +48,7 @@ bool MoveEvents::registerLuaItemEvent(const std::shared_ptr moveEvent return !itemIdVector.empty(); } -bool MoveEvents::registerLuaActionEvent(const std::shared_ptr moveEvent) { +bool MoveEvents::registerLuaActionEvent(const std::shared_ptr &moveEvent) { auto actionIdVector = moveEvent->getActionIdsVector(); if (actionIdVector.empty()) { return false; @@ -92,7 +67,7 @@ bool MoveEvents::registerLuaActionEvent(const std::shared_ptr moveEve return !actionIdVector.empty(); } -bool MoveEvents::registerLuaUniqueEvent(const std::shared_ptr moveEvent) { +bool MoveEvents::registerLuaUniqueEvent(const std::shared_ptr &moveEvent) { auto uniqueIdVector = moveEvent->getUniqueIdsVector(); if (uniqueIdVector.empty()) { return false; @@ -111,7 +86,7 @@ bool MoveEvents::registerLuaUniqueEvent(const std::shared_ptr moveEve return !uniqueIdVector.empty(); } -bool MoveEvents::registerLuaPositionEvent(const std::shared_ptr moveEvent) { +bool MoveEvents::registerLuaPositionEvent(const std::shared_ptr &moveEvent) { auto positionVector = moveEvent->getPositionsVector(); if (positionVector.empty()) { return false; @@ -130,7 +105,7 @@ bool MoveEvents::registerLuaPositionEvent(const std::shared_ptr moveE return !positionVector.empty(); } -bool MoveEvents::registerLuaEvent(const std::shared_ptr moveEvent) { +bool MoveEvents::registerLuaEvent(const std::shared_ptr &moveEvent) { // Check if event is correct if (registerLuaItemEvent(moveEvent) || registerLuaUniqueEvent(moveEvent) @@ -147,7 +122,7 @@ bool MoveEvents::registerLuaEvent(const std::shared_ptr moveEvent) { } } -bool MoveEvents::registerEvent(const std::shared_ptr moveEvent, int32_t id, std::map &moveListMap) const { +bool MoveEvents::registerEvent(const std::shared_ptr &moveEvent, int32_t id, std::map &moveListMap) const { auto it = moveListMap.find(id); if (it == moveListMap.end()) { MoveEventList moveEventList; @@ -167,7 +142,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr moveEvent, int32 return false; } } - moveEventList.push_back(moveEvent); + moveEventList.emplace_back(moveEvent); return true; } } @@ -211,7 +186,7 @@ std::shared_ptr MoveEvents::getEvent(const std::shared_ptr &ite } if (item->hasAttribute(ItemAttribute_t::ACTIONID)) { - std::map::iterator it = actionIdMap.find(item->getAttribute(ItemAttribute_t::ACTIONID)); + const auto &it = actionIdMap.find(item->getAttribute(ItemAttribute_t::ACTIONID)); if (it != actionIdMap.end()) { std::list> moveEventList = it->second.moveEvent[eventType]; for (const auto &moveEvent : moveEventList) { @@ -222,7 +197,7 @@ std::shared_ptr MoveEvents::getEvent(const std::shared_ptr &ite } } - auto it = itemIdMap.find(item->getID()); + const auto &it = itemIdMap.find(item->getID()); if (it != itemIdMap.end()) { std::list> &moveEventList = it->second.moveEvent[eventType]; for (const auto &moveEvent : moveEventList) { @@ -266,7 +241,7 @@ std::shared_ptr MoveEvents::getEvent(const std::shared_ptr &ite return nullptr; } -bool MoveEvents::registerEvent(const std::shared_ptr moveEvent, const Position &position, std::map &moveListMap) const { +bool MoveEvents::registerEvent(const std::shared_ptr &moveEvent, const Position &position, std::map &moveListMap) const { auto it = moveListMap.find(position); if (it == moveListMap.end()) { MoveEventList moveEventList; @@ -430,11 +405,11 @@ std::string MoveEvent::getScriptTypeName() const { __FUNCTION__, getScriptInterface()->getLoadingScriptName() ); - return std::string(); + return {}; } } -uint32_t MoveEvent::StepInField(std::shared_ptr creature, std::shared_ptr item, const Position &) { +uint32_t MoveEvent::StepInField(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &) { if (creature == nullptr) { g_logger().error("[MoveEvent::StepInField] - Creature is nullptr"); return 0; @@ -454,11 +429,11 @@ uint32_t MoveEvent::StepInField(std::shared_ptr creature, std::shared_ return LUA_ERROR_ITEM_NOT_FOUND; } -uint32_t MoveEvent::StepOutField(std::shared_ptr, std::shared_ptr, const Position &) { +uint32_t MoveEvent::StepOutField(const std::shared_ptr &, const std::shared_ptr &, const Position &) { return 1; } -uint32_t MoveEvent::AddItemField(std::shared_ptr item, std::shared_ptr, const Position &) { +uint32_t MoveEvent::AddItemField(const std::shared_ptr &item, const std::shared_ptr &, const Position &) { if (item == nullptr) { g_logger().error("[MoveEvent::AddItemField] - Item is nullptr"); return 0; @@ -488,11 +463,11 @@ uint32_t MoveEvent::AddItemField(std::shared_ptr item, std::shared_ptr, std::shared_ptr, const Position &) { +uint32_t MoveEvent::RemoveItemField(const std::shared_ptr &, const std::shared_ptr &, const Position &) { return 1; } -uint32_t MoveEvent::EquipItem(const std::shared_ptr moveEvent, std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool isCheck) { +uint32_t MoveEvent::EquipItem(const std::shared_ptr &moveEvent, const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool isCheck) { if (player == nullptr) { g_logger().error("[MoveEvent::EquipItem] - Player is nullptr"); return 0; @@ -613,7 +588,7 @@ uint32_t MoveEvent::EquipItem(const std::shared_ptr moveEvent, std::s return 1; } -uint32_t MoveEvent::DeEquipItem(const std::shared_ptr MoveEvent, std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool) { +uint32_t MoveEvent::DeEquipItem(const std::shared_ptr &, const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool) { if (player == nullptr) { g_logger().error("[MoveEvent::EquipItem] - Player is nullptr"); return 0; @@ -698,7 +673,7 @@ void MoveEvent::setEventType(MoveEvent_t type) { eventType = type; } -uint32_t MoveEvent::fireStepEvent(const std::shared_ptr &creature, std::shared_ptr item, const Position &pos) const { +uint32_t MoveEvent::fireStepEvent(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos) const { if (isLoadedCallback()) { return executeStep(creature, item, pos); } else { @@ -706,7 +681,7 @@ uint32_t MoveEvent::fireStepEvent(const std::shared_ptr &creature, std } } -bool MoveEvent::executeStep(const std::shared_ptr &creature, std::shared_ptr item, const Position &pos) const { +bool MoveEvent::executeStep(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos) const { // onStepIn(creature, item, pos, fromPosition) // onStepOut(creature, item, pos, fromPosition) @@ -724,7 +699,7 @@ bool MoveEvent::executeStep(const std::shared_ptr &creature, std::shar return false; } - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { if (item != nullptr) { g_logger().error("[MoveEvent::executeStep - Creature {} item {}, position {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -737,7 +712,7 @@ bool MoveEvent::executeStep(const std::shared_ptr &creature, std::shar return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -768,14 +743,14 @@ uint32_t MoveEvent::fireEquip(const std::shared_ptr &player, const std:: bool MoveEvent::executeEquip(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t onSlot, bool isCheck) const { // onEquip(player, item, slot, isCheck) // onDeEquip(player, item, slot, isCheck) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[MoveEvent::executeEquip - Player {} item {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), item->getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -801,7 +776,7 @@ uint32_t MoveEvent::fireAddRemItem(const std::shared_ptr &item, const std: bool MoveEvent::executeAddRemItem(const std::shared_ptr &item, const std::shared_ptr &fromTile, const Position &pos) const { // onAddItem(moveitem, tileitem, pos) // onRemoveItem(moveitem, tileitem, pos) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[MoveEvent::executeAddRemItem - " "Item {} item on tile x: {} y: {} z: {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -809,7 +784,7 @@ bool MoveEvent::executeAddRemItem(const std::shared_ptr &item, const std:: return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -833,7 +808,7 @@ uint32_t MoveEvent::fireAddRemItem(const std::shared_ptr &item, const Posi bool MoveEvent::executeAddRemItem(const std::shared_ptr &item, const Position &pos) const { // onaddItem(moveitem, pos) // onRemoveItem(moveitem, pos) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[MoveEvent::executeAddRemItem - " "Item {} item on tile x: {} y: {} z: {}] " "Call stack overflow. Too many lua script calls being nested.", @@ -841,7 +816,7 @@ bool MoveEvent::executeAddRemItem(const std::shared_ptr &item, const Posit return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); diff --git a/src/lua/creature/movement.hpp b/src/lua/creature/movement.hpp index b8168f58521..3f3a72a85e6 100644 --- a/src/lua/creature/movement.hpp +++ b/src/lua/creature/movement.hpp @@ -107,19 +107,16 @@ class MoveEvents final : public Scripts { std::shared_ptr getEvent(const std::shared_ptr &item, MoveEvent_t eventType); - bool registerLuaItemEvent(const std::shared_ptr moveEvent); - bool registerLuaActionEvent(const std::shared_ptr moveEvent); - bool registerLuaUniqueEvent(const std::shared_ptr moveEvent); - bool registerLuaPositionEvent(const std::shared_ptr moveEvent); - bool registerLuaEvent(const std::shared_ptr event); - void clear(bool isFromXML = false); + bool registerLuaItemEvent(const std::shared_ptr &moveEvent); + bool registerLuaActionEvent(const std::shared_ptr &moveEvent); + bool registerLuaUniqueEvent(const std::shared_ptr &moveEvent); + bool registerLuaPositionEvent(const std::shared_ptr &moveEvent); + bool registerLuaEvent(const std::shared_ptr &event); + void clear(); private: - void clearMap(std::map &map) const; - void clearPosMap(std::map &map); - - bool registerEvent(const std::shared_ptr moveEvent, int32_t id, std::map &moveListMap) const; - bool registerEvent(const std::shared_ptr moveEvent, const Position &position, std::map &moveListMap) const; + bool registerEvent(const std::shared_ptr &moveEvent, int32_t id, std::map &moveListMap) const; + bool registerEvent(const std::shared_ptr &moveEvent, const Position &position, std::map &moveListMap) const; std::shared_ptr getEvent(const std::shared_ptr &tile, MoveEvent_t eventType); std::shared_ptr getEvent(const std::shared_ptr &item, MoveEvent_t eventType, Slots_t slot); @@ -139,7 +136,7 @@ class MoveEvent final : public Script, public SharedObject { MoveEvent_t getEventType() const; void setEventType(MoveEvent_t type); - uint32_t fireStepEvent(const std::shared_ptr &creature, std::shared_ptr item, const Position &pos) const; + uint32_t fireStepEvent(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos) const; uint32_t fireAddRemItem(const std::shared_ptr &item, const std::shared_ptr &tileItem, const Position &pos) const; uint32_t fireAddRemItem(const std::shared_ptr &item, const Position &pos) const; uint32_t fireEquip(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool isCheck); @@ -149,7 +146,7 @@ class MoveEvent final : public Script, public SharedObject { } // Scripting to lua interface - bool executeStep(const std::shared_ptr &creature, std::shared_ptr item, const Position &pos) const; + bool executeStep(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos) const; bool executeEquip(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool isCheck) const; bool executeAddRemItem(const std::shared_ptr &item, const std::shared_ptr &tileItem, const Position &pos) const; // No have tile item @@ -178,7 +175,7 @@ class MoveEvent final : public Script, public SharedObject { const std::map &getVocEquipMap() const { return vocEquipMap; } - void addVocEquipMap(std::string vocName) { + void addVocEquipMap(const std::string &vocName) { uint16_t vocationId = g_vocations().getVocationId(vocName); if (vocationId != 65535) { vocEquipMap[vocationId] = true; @@ -242,22 +239,14 @@ class MoveEvent final : public Script, public SharedObject { wieldInfo |= info; } - static uint32_t StepInField(std::shared_ptr creature, std::shared_ptr item, const Position &pos); - static uint32_t StepOutField(std::shared_ptr creature, std::shared_ptr item, const Position &pos); - - static uint32_t AddItemField(std::shared_ptr item, std::shared_ptr tileItem, const Position &pos); - static uint32_t RemoveItemField(std::shared_ptr item, std::shared_ptr tileItem, const Position &pos); - - static uint32_t EquipItem(const std::shared_ptr moveEvent, std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool boolean); - static uint32_t DeEquipItem(const std::shared_ptr moveEvent, std::shared_ptr player, std::shared_ptr item, Slots_t slot, bool boolean); + static uint32_t StepInField(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos); + static uint32_t StepOutField(const std::shared_ptr &creature, const std::shared_ptr &item, const Position &pos); - void setFromXML(bool newFromXML) { - m_fromXML = newFromXML; - } + static uint32_t AddItemField(const std::shared_ptr &item, const std::shared_ptr &tileItem, const Position &pos); + static uint32_t RemoveItemField(const std::shared_ptr &item, const std::shared_ptr &tileItem, const Position &pos); - bool isFromXML() const { - return m_fromXML; - } + static uint32_t EquipItem(const std::shared_ptr &moveEvent, const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool boolean); + static uint32_t DeEquipItem(const std::shared_ptr &, const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool boolean); private: std::string getScriptTypeName() const override; @@ -298,8 +287,6 @@ class MoveEvent final : public Script, public SharedObject { std::map vocEquipMap; bool tileItem = false; - bool m_fromXML = false; - std::vector itemIdVector; std::vector actionIdVector; std::vector uniqueIdVector; diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index 8064bf52b81..fe5f218e373 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -208,7 +208,7 @@ bool Raid::loadFromXml(const std::string &filename) { } // sort by delay time - std::sort(raidEvents.begin(), raidEvents.end(), [](const std::shared_ptr lhs, const std::shared_ptr rhs) { + std::sort(raidEvents.begin(), raidEvents.end(), [](const std::shared_ptr &lhs, const std::shared_ptr &rhs) { return lhs->getDelay() < rhs->getDelay(); }); @@ -229,7 +229,7 @@ void Raid::startRaid() { } } -void Raid::executeRaidEvent(const std::shared_ptr raidEvent) { +void Raid::executeRaidEvent(const std::shared_ptr &raidEvent) { if (raidEvent->executeEvent()) { nextEvent++; const auto newRaidEvent = getNextRaidEvent(); @@ -593,14 +593,14 @@ std::string ScriptEvent::getScriptEventName() const { bool ScriptEvent::executeEvent() { // onRaid() - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - Script with name {} " "Call stack overflow. Too many lua script calls being nested.", __FUNCTION__, getScriptName()); return false; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(scriptId, scriptInterface); scriptInterface->pushFunction(scriptId); diff --git a/src/lua/creature/raids.hpp b/src/lua/creature/raids.hpp index 0266641edda..b7c9a368827 100644 --- a/src/lua/creature/raids.hpp +++ b/src/lua/creature/raids.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "utils/utils_definitions.hpp" #include "declarations.hpp" #include "game/movement/position.hpp" @@ -56,7 +58,7 @@ class Raids { std::shared_ptr getRunning() { return running; } - void setRunning(const std::shared_ptr newRunning) { + void setRunning(const std::shared_ptr &newRunning) { running = newRunning; } @@ -100,7 +102,7 @@ class Raid { void startRaid(); - void executeRaidEvent(const std::shared_ptr raidEvent); + void executeRaidEvent(const std::shared_ptr &raidEvent); void resetRaid(); std::shared_ptr getNextRaidEvent(); @@ -150,7 +152,7 @@ class RaidEvent { } private: - uint32_t delay; + uint32_t delay {}; }; class AnnounceEvent final : public RaidEvent { @@ -202,7 +204,7 @@ class ScriptEvent final : public RaidEvent, public Event { return scriptName; } void setScriptName(std::string name) { - scriptName = name; + scriptName = std::move(name); } bool executeEvent() override; diff --git a/src/lua/creature/talkaction.cpp b/src/lua/creature/talkaction.cpp index c1b8c028ddc..02b21ae7e6d 100644 --- a/src/lua/creature/talkaction.cpp +++ b/src/lua/creature/talkaction.cpp @@ -25,7 +25,7 @@ bool TalkActions::registerLuaEvent(const TalkAction_ptr &talkAction) { return inserted; } -bool TalkActions::checkWord(std::shared_ptr player, SpeakClasses type, const std::string &words, const std::string_view &word, const TalkAction_ptr &talkActionPtr) const { +bool TalkActions::checkWord(const std::shared_ptr &player, SpeakClasses type, const std::string &words, const std::string_view &word, const TalkAction_ptr &talkActionPtr) const { auto spacePos = std::ranges::find_if(words.begin(), words.end(), ::isspace); std::string firstWord = words.substr(0, spacePos - words.begin()); @@ -61,7 +61,7 @@ bool TalkActions::checkWord(std::shared_ptr player, SpeakClasses type, c return talkActionPtr->executeSay(player, words, param, type); } -TalkActionResult_t TalkActions::checkPlayerCanSayTalkAction(std::shared_ptr player, SpeakClasses type, const std::string &words) const { +TalkActionResult_t TalkActions::checkPlayerCanSayTalkAction(const std::shared_ptr &player, SpeakClasses type, const std::string &words) const { for (const auto &[talkactionWords, talkActionPtr] : talkActions) { if (talkactionWords.find(',') != std::string::npos) { auto wordsList = split(talkactionWords); @@ -79,16 +79,16 @@ TalkActionResult_t TalkActions::checkPlayerCanSayTalkAction(std::shared_ptr player, const std::string &words, const std::string ¶m, SpeakClasses type) const { +bool TalkAction::executeSay(const std::shared_ptr &player, const std::string &words, const std::string ¶m, SpeakClasses type) const { // onSay(player, words, param, type) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[TalkAction::executeSay - Player {} words {}] " "Call stack overflow. Too many lua script calls being nested. Script name {}", player->getName(), getWords(), getScriptInterface()->getLoadingScriptName()); return false; } - ScriptEnvironment* scriptEnvironment = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* scriptEnvironment = LuaScriptInterface::getScriptEnv(); scriptEnvironment->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); diff --git a/src/lua/creature/talkaction.hpp b/src/lua/creature/talkaction.hpp index d4fd6165459..7b74c94b6b1 100644 --- a/src/lua/creature/talkaction.hpp +++ b/src/lua/creature/talkaction.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "account/account.hpp" #include "lua/global/baseevents.hpp" #include "utils/utils_definitions.hpp" @@ -48,11 +50,11 @@ class TalkAction : public Script { return separator; } void setSeparator(std::string sep) { - separator = sep; + separator = std::move(sep); } // scripting - bool executeSay(std::shared_ptr player, const std::string &words, const std::string ¶m, SpeakClasses type) const; + bool executeSay(const std::shared_ptr &player, const std::string &words, const std::string ¶m, SpeakClasses type) const; // void setGroupType(uint8_t newGroupType); @@ -82,8 +84,8 @@ class TalkActions final : public Scripts { return inject(); } - bool checkWord(std::shared_ptr player, SpeakClasses type, const std::string &words, const std::string_view &word, const TalkAction_ptr &talkActionPtr) const; - TalkActionResult_t checkPlayerCanSayTalkAction(std::shared_ptr player, SpeakClasses type, const std::string &words) const; + bool checkWord(const std::shared_ptr &player, SpeakClasses type, const std::string &words, const std::string_view &word, const TalkAction_ptr &talkActionPtr) const; + TalkActionResult_t checkPlayerCanSayTalkAction(const std::shared_ptr &player, SpeakClasses type, const std::string &words) const; bool registerLuaEvent(const TalkAction_ptr &talkAction); void clear(); diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index 83ecd091850..bfb1d3b6cb9 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -29,7 +29,6 @@ #include "creatures/players/achievement/player_achievement.hpp" #include "creatures/players/cyclopedia/player_badge.hpp" #include "creatures/players/cyclopedia/player_cyclopedia.hpp" -#include "creatures/players/cyclopedia/player_title.hpp" #include "map/spectators.hpp" // Game @@ -108,7 +107,7 @@ int GameFunctions::luaGameGetSpectators(lua_State* L) { lua_createtable(L, spectators.size(), 0); int index = 0; - for (std::shared_ptr creature : spectators) { + for (const auto &creature : spectators) { pushUserdata(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); @@ -130,7 +129,7 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { if (lua_gettop(L) <= 2) { std::map mtype_list = g_game().getBestiaryList(); - for (auto ita : mtype_list) { + for (const auto &ita : mtype_list) { if (name) { pushString(L, ita.second); } else { @@ -141,7 +140,7 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { } else { if (isNumber(L, 2)) { std::map tmplist = g_iobestiary().findRaceByName("CANARY", false, getNumber(L, 2)); - for (auto itb : tmplist) { + for (const auto &itb : tmplist) { if (name) { pushString(L, itb.second); } else { @@ -151,7 +150,7 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { } } else { std::map tmplist = g_iobestiary().findRaceByName(getString(L, 2)); - for (auto itc : tmplist) { + for (const auto &itc : tmplist) { if (name) { pushString(L, itc.second); } else { @@ -240,7 +239,7 @@ int GameFunctions::luaGameGetTowns(lua_State* L) { lua_createtable(L, towns.size(), 0); int index = 0; - for (auto townEntry : towns) { + for (const auto &townEntry : towns) { pushUserdata(L, townEntry.second); setMetatable(L, -1, "Town"); lua_rawseti(L, -2, ++index); @@ -254,7 +253,7 @@ int GameFunctions::luaGameGetHouses(lua_State* L) { lua_createtable(L, houses.size(), 0); int index = 0; - for (auto houseEntry : houses) { + for (const auto &houseEntry : houses) { pushUserdata(L, houseEntry.second); setMetatable(L, -1, "House"); lua_rawseti(L, -2, ++index); @@ -354,7 +353,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { } if (position.x != 0) { - std::shared_ptr tile = g_game().map.getTile(position); + const auto &tile = g_game().map.getTile(position); if (!tile) { if (!hasTable) { lua_pushnil(L); @@ -402,7 +401,7 @@ int GameFunctions::luaGameCreateContainer(lua_State* L) { } } - std::shared_ptr container = Item::CreateItemAsContainer(id, size); + const auto &container = Item::CreateItemAsContainer(id, size); if (!container) { lua_pushnil(L); return 1; @@ -594,19 +593,19 @@ int GameFunctions::luaGameGetClientVersion(lua_State* L) { int GameFunctions::luaGameReload(lua_State* L) { // Game.reload(reloadType) Reload_t reloadType = getNumber(L, 1); - if (g_gameReload().getReloadNumber(reloadType) == g_gameReload().getReloadNumber(Reload_t::RELOAD_TYPE_NONE)) { + if (GameReload::getReloadNumber(reloadType) == GameReload::getReloadNumber(Reload_t::RELOAD_TYPE_NONE)) { reportErrorFunc("Reload type is none"); pushBoolean(L, false); return 0; } - if (g_gameReload().getReloadNumber(reloadType) >= g_gameReload().getReloadNumber(Reload_t::RELOAD_TYPE_LAST)) { + if (GameReload::getReloadNumber(reloadType) >= GameReload::getReloadNumber(Reload_t::RELOAD_TYPE_LAST)) { reportErrorFunc("Reload type not exist"); pushBoolean(L, false); return 0; } - pushBoolean(L, g_gameReload().init(reloadType)); + pushBoolean(L, GameReload::init(reloadType)); lua_gc(g_luaEnvironment().getLuaState(), LUA_GCCOLLECT, 0); return 1; } diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 6b5175b06cf..f5bb38cee66 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -586,7 +586,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaData_t type = getNumber(L, -1); if (type != LuaData_t::Unknown && type <= LuaData_t::Npc) { - indexes.push_back({ i, type }); + indexes.emplace_back(i, type); } lua_pop(globalState, 2); } diff --git a/src/lua/functions/core/game/zone_functions.cpp b/src/lua/functions/core/game/zone_functions.cpp index 5471d01895a..8ab6d4b9532 100644 --- a/src/lua/functions/core/game/zone_functions.cpp +++ b/src/lua/functions/core/game/zone_functions.cpp @@ -133,7 +133,7 @@ int ZoneFunctions::luaZoneGetCreatures(lua_State* L) { lua_createtable(L, static_cast(creatures.size()), 0); int index = 0; - for (auto creature : creatures) { + for (const auto &creature : creatures) { index++; pushUserdata(L, creature); setMetatable(L, -1, "Creature"); @@ -154,7 +154,7 @@ int ZoneFunctions::luaZoneGetPlayers(lua_State* L) { lua_createtable(L, static_cast(players.size()), 0); int index = 0; - for (auto player : players) { + for (const auto &player : players) { index++; pushUserdata(L, player); setMetatable(L, -1, "Player"); @@ -175,7 +175,7 @@ int ZoneFunctions::luaZoneGetMonsters(lua_State* L) { lua_createtable(L, static_cast(monsters.size()), 0); int index = 0; - for (auto monster : monsters) { + for (const auto &monster : monsters) { index++; pushUserdata(L, monster); setMetatable(L, -1, "Monster"); @@ -196,7 +196,7 @@ int ZoneFunctions::luaZoneGetNpcs(lua_State* L) { lua_createtable(L, static_cast(npcs.size()), 0); int index = 0; - for (auto npc : npcs) { + for (const auto &npc : npcs) { index++; pushUserdata(L, npc); setMetatable(L, -1, "Npc"); @@ -217,7 +217,7 @@ int ZoneFunctions::luaZoneGetItems(lua_State* L) { lua_createtable(L, static_cast(items.size()), 0); int index = 0; - for (auto item : items) { + for (const auto &item : items) { index++; pushUserdata(L, item); setMetatable(L, -1, "Item"); @@ -305,7 +305,7 @@ int ZoneFunctions::luaZoneGetByPosition(lua_State* L) { int index = 0; auto zones = tile->getZones(); lua_createtable(L, static_cast(zones.size()), 0); - for (auto zone : zones) { + for (const auto &zone : zones) { index++; pushUserdata(L, zone); setMetatable(L, -1, "Zone"); @@ -319,7 +319,7 @@ int ZoneFunctions::luaZoneGetAll(lua_State* L) { auto zones = Zone::getZones(); lua_createtable(L, static_cast(zones.size()), 0); int index = 0; - for (auto zone : zones) { + for (const auto &zone : zones) { index++; pushUserdata(L, zone); setMetatable(L, -1, "Zone"); diff --git a/src/lua/functions/creatures/combat/combat_functions.cpp b/src/lua/functions/creatures/combat/combat_functions.cpp index 3bba21d179c..c7a87a2a15c 100644 --- a/src/lua/functions/creatures/combat/combat_functions.cpp +++ b/src/lua/functions/creatures/combat/combat_functions.cpp @@ -89,7 +89,7 @@ int CombatFunctions::luaCombatSetArea(lua_State* L) { int CombatFunctions::luaCombatSetCondition(lua_State* L) { // combat:addCondition(condition) std::shared_ptr condition = getUserdataShared(L, 2); - Combat* combat = getUserdata(L, 1); + auto* combat = getUserdata(L, 1); if (combat && condition) { combat->addCondition(condition->clone()); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/combat/condition_functions.cpp b/src/lua/functions/creatures/combat/condition_functions.cpp index 27f21867f76..7f4098e701e 100644 --- a/src/lua/functions/creatures/combat/condition_functions.cpp +++ b/src/lua/functions/creatures/combat/condition_functions.cpp @@ -25,7 +25,7 @@ int ConditionFunctions::luaConditionCreate(lua_State* L) { uint32_t subId = getNumber(L, 4, 0); bool isPersistent = getBoolean(L, 5, false); - std::shared_ptr condition = Condition::createCondition(conditionId, conditionType, 0, 0, false, subId, isPersistent); + const auto &condition = Condition::createCondition(conditionId, conditionType, 0, 0, false, subId, isPersistent); if (condition) { pushUserdata(L, condition); setMetatable(L, -1, "Condition"); diff --git a/src/lua/functions/creatures/combat/spell_functions.cpp b/src/lua/functions/creatures/combat/spell_functions.cpp index a24407c1682..5703c8f2086 100644 --- a/src/lua/functions/creatures/combat/spell_functions.cpp +++ b/src/lua/functions/creatures/combat/spell_functions.cpp @@ -613,7 +613,7 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { if (getString(L, 2 + i).find(";") != std::string::npos) { std::vector vocList = explodeString(getString(L, 2 + i), ";"); int32_t vocationId = g_vocations().getVocationId(vocList[0]); - if (vocList.size() > 0) { + if (!vocList.empty()) { if (vocList[1] == "true") { spell->addVocMap(vocationId, true); } else { @@ -650,7 +650,7 @@ int SpellFunctions::luaSpellWords(lua_State* L) { pushString(L, spell->getSeparator()); return 2; } else { - std::string sep = ""; + std::string sep; if (lua_gettop(L) == 3) { sep = getString(L, 3); } diff --git a/src/lua/functions/creatures/monster/monster_functions.cpp b/src/lua/functions/creatures/monster/monster_functions.cpp index 5578477d6ba..4ba6ea412a8 100644 --- a/src/lua/functions/creatures/monster/monster_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_functions.cpp @@ -63,7 +63,7 @@ int MonsterFunctions::luaMonsterSetType(lua_State* L) { // monster:setType(name or raceid) std::shared_ptr monster = getUserdataShared(L, 1); if (monster) { - std::shared_ptr mType = nullptr; + std::shared_ptr mType; if (isNumber(L, 2)) { mType = g_monsters().getMonsterTypeByRaceId(getNumber(L, 2)); } else { @@ -283,7 +283,7 @@ int MonsterFunctions::luaMonsterGetTargetList(lua_State* L) { lua_createtable(L, targetList.size(), 0); int index = 0; - for (std::shared_ptr creature : targetList) { + for (const auto &creature : targetList) { pushUserdata(L, creature); setCreatureMetatable(L, -1, creature); lua_rawseti(L, -2, ++index); @@ -306,8 +306,8 @@ int MonsterFunctions::luaMonsterChangeTargetDistance(lua_State* L) { // monster:changeTargetDistance(distance[, duration = 12000]) std::shared_ptr monster = getUserdataShared(L, 1); if (monster) { - int32_t distance = getNumber(L, 2, 1); - uint32_t duration = getNumber(L, 3, 12000); + auto distance = getNumber(L, 2, 1); + auto duration = getNumber(L, 3, 12000); pushBoolean(L, monster->changeTargetDistance(distance, duration)); } else { lua_pushnil(L); @@ -342,7 +342,7 @@ int MonsterFunctions::luaMonsterSearchTarget(lua_State* L) { // monster:searchTarget([searchType = TARGETSEARCH_DEFAULT]) std::shared_ptr monster = getUserdataShared(L, 1); if (monster) { - TargetSearchType_t searchType = getNumber(L, 2, TARGETSEARCH_DEFAULT); + const auto &searchType = getNumber(L, 2, TARGETSEARCH_DEFAULT); pushBoolean(L, monster->searchTarget(searchType)); } else { lua_pushnil(L); @@ -458,7 +458,7 @@ int MonsterFunctions::luaMonsterGetForgeStack(lua_State* L) { int MonsterFunctions::luaMonsterSetForgeStack(lua_State* L) { // monster:setForgeStack(stack) - uint16_t stack = getNumber(L, 2, 0); + auto stack = getNumber(L, 2, 0); std::shared_ptr monster = getUserdataShared(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.cpp b/src/lua/functions/creatures/monster/monster_spell_functions.cpp index a20d57008d2..9d6116829f2 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.cpp @@ -21,7 +21,7 @@ int MonsterSpellFunctions::luaCreateMonsterSpell(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetType(lua_State* L) { // monsterSpell:setType(type) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->name = getString(L, 2); pushBoolean(L, true); @@ -33,7 +33,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetType(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetScriptName(lua_State* L) { // monsterSpell:setScriptName(name) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->scriptName = getString(L, 2); pushBoolean(L, true); @@ -45,7 +45,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetScriptName(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetChance(lua_State* L) { // monsterSpell:setChance(chance) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->chance = getNumber(L, 2); pushBoolean(L, true); @@ -57,7 +57,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetChance(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetInterval(lua_State* L) { // monsterSpell:setInterval(interval) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->interval = getNumber(L, 2); pushBoolean(L, true); @@ -69,7 +69,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetInterval(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetRange(lua_State* L) { // monsterSpell:setRange(range) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->range = getNumber(L, 2); pushBoolean(L, true); @@ -81,7 +81,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetRange(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatValue(lua_State* L) { // monsterSpell:setCombatValue(min, max) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->minCombatValue = getNumber(L, 2); spell->maxCombatValue = getNumber(L, 3); @@ -94,7 +94,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatValue(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatType(lua_State* L) { // monsterSpell:setCombatType(combatType_t) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->combatType = getNumber(L, 2); pushBoolean(L, true); @@ -106,7 +106,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatType(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetAttackValue(lua_State* L) { // monsterSpell:setAttackValue(attack, skill) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->attack = getNumber(L, 2); spell->skill = getNumber(L, 3); @@ -119,7 +119,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetAttackValue(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetNeedTarget(lua_State* L) { // monsterSpell:setNeedTarget(bool) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->needTarget = getBoolean(L, 2); pushBoolean(L, true); @@ -131,7 +131,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetNeedTarget(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatLength(lua_State* L) { // monsterSpell:setCombatLength(length) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->length = getNumber(L, 2); pushBoolean(L, true); @@ -143,7 +143,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatLength(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatSpread(lua_State* L) { // monsterSpell:setCombatSpread(spread) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->spread = getNumber(L, 2); pushBoolean(L, true); @@ -155,7 +155,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatSpread(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatRadius(lua_State* L) { // monsterSpell:setCombatRadius(radius) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->radius = getNumber(L, 2); pushBoolean(L, true); @@ -167,7 +167,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatRadius(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetConditionType(lua_State* L) { // monsterSpell:setConditionType(type) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { auto conditionType = getNumber(L, 2); if (conditionType == 254) { @@ -187,7 +187,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionType(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetConditionDamage(lua_State* L) { // monsterSpell:setConditionDamage(min, max, start) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->conditionMinDamage = getNumber(L, 2); spell->conditionMaxDamage = getNumber(L, 3); @@ -201,7 +201,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionDamage(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetConditionSpeedChange(lua_State* L) { // monsterSpell:setConditionSpeedChange(speed) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->speedChange = getNumber(L, 2); pushBoolean(L, true); @@ -213,7 +213,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionSpeedChange(lua_State* L) int MonsterSpellFunctions::luaMonsterSpellSetConditionDuration(lua_State* L) { // monsterSpell:setConditionDuration(duration) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->duration = getNumber(L, 2); pushBoolean(L, true); @@ -225,7 +225,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionDuration(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetConditionTickInterval(lua_State* L) { // monsterSpell:setConditionTickInterval(interval) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->tickInterval = getNumber(L, 2); pushBoolean(L, true); @@ -237,7 +237,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionTickInterval(lua_State* L) int MonsterSpellFunctions::luaMonsterSpellSetCombatShootEffect(lua_State* L) { // monsterSpell:setCombatShootEffect(effect) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->shoot = getNumber(L, 2); pushBoolean(L, true); @@ -249,7 +249,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatShootEffect(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetCombatEffect(lua_State* L) { // monsterSpell:setCombatEffect(effect) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->effect = getNumber(L, 2); pushBoolean(L, true); @@ -261,7 +261,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetCombatEffect(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetOutfitMonster(lua_State* L) { // monsterSpell:setOutfitMonster(effect) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->outfitMonster = getString(L, 2); pushBoolean(L, true); @@ -273,7 +273,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetOutfitMonster(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellSetOutfitItem(lua_State* L) { // monsterSpell:setOutfitItem(effect) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (spell) { spell->outfitItem = getNumber(L, 2); pushBoolean(L, true); @@ -285,7 +285,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetOutfitItem(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellCastSound(lua_State* L) { // get: monsterSpell:castSound() set: monsterSpell:castSound(sound) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast(spell->soundCastEffect)); } else { @@ -297,7 +297,7 @@ int MonsterSpellFunctions::luaMonsterSpellCastSound(lua_State* L) { int MonsterSpellFunctions::luaMonsterSpellImpactSound(lua_State* L) { // get: monsterSpell:impactSound() set: monsterSpell:impactSound(sound) - const auto spell = getUserdataShared(L, 1); + const auto &spell = getUserdataShared(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast(spell->soundImpactEffect)); } else { diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.hpp b/src/lua/functions/creatures/monster/monster_spell_functions.hpp index ad737ea9326..f5d64a3511e 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.hpp @@ -14,7 +14,7 @@ class MonsterSpellFunctions final : LuaScriptInterface { public: static void init(lua_State* L) { - registerClass(L, "MonsterSpell", "", MonsterSpellFunctions::luaCreateMonsterSpell); + registerSharedClass(L, "MonsterSpell", "", MonsterSpellFunctions::luaCreateMonsterSpell); registerMethod(L, "MonsterSpell", "setType", MonsterSpellFunctions::luaMonsterSpellSetType); registerMethod(L, "MonsterSpell", "setScriptName", MonsterSpellFunctions::luaMonsterSpellSetScriptName); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 757337bfe3c..7aa8ae926ec 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -43,7 +43,7 @@ void MonsterTypeFunctions::createMonsterTypeLootLuaTable(lua_State* L, const std int MonsterTypeFunctions::luaMonsterTypeCreate(lua_State* L) { // MonsterType(name or raceid) - std::shared_ptr monsterType = nullptr; + std::shared_ptr monsterType; if (isNumber(L, 2)) { monsterType = g_monsters().getMonsterTypeByRaceId(getNumber(L, 2)); } else { @@ -61,7 +61,7 @@ int MonsterTypeFunctions::luaMonsterTypeCreate(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsAttackable(lua_State* L) { // get: monsterType:isAttackable() set: monsterType:isAttackable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isAttackable); @@ -77,7 +77,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsAttackable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsConvinceable(lua_State* L) { // get: monsterType:isConvinceable() set: monsterType:isConvinceable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isConvinceable); @@ -93,7 +93,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsConvinceable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsSummonable(lua_State* L) { // get: monsterType:isSummonable() set: monsterType:isSummonable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isSummonable); @@ -141,7 +141,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsPreyable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsIllusionable(lua_State* L) { // get: monsterType:isIllusionable() set: monsterType:isIllusionable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isIllusionable); @@ -157,7 +157,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsIllusionable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsHostile(lua_State* L) { // get: monsterType:isHostile() set: monsterType:isHostile(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isHostile); @@ -173,7 +173,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsHostile(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeFamiliar(lua_State* L) { // get: monsterType:familiar() set: monsterType:familiar(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isFamiliar); @@ -189,7 +189,7 @@ int MonsterTypeFunctions::luaMonsterTypeFamiliar(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsRewardBoss(lua_State* L) { // get: monsterType:isRewardBoss() set: monsterType:isRewardBoss(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isRewardBoss); @@ -205,7 +205,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsRewardBoss(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsPushable(lua_State* L) { // get: monsterType:isPushable() set: monsterType:isPushable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.pushable); @@ -221,7 +221,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsPushable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsHealthHidden(lua_State* L) { // get: monsterType:isHealthHidden() set: monsterType:isHealthHidden(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.hiddenHealth); @@ -237,7 +237,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsHealthHidden(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsBlockable(lua_State* L) { // get: monsterType:isBlockable() set: monsterType:isBlockable(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isBlockable); @@ -253,7 +253,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsBlockable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsForgeCreature(lua_State* L) { // get: monsterType:isForgeCreature() set: monsterType:isForgeCreature(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -271,7 +271,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsForgeCreature(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanSpawn(lua_State* L) { // monsterType:canSpawn(pos) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); const Position &position = getPosition(L, 2); if (monsterType) { pushBoolean(L, monsterType->canSpawn(position)); @@ -283,7 +283,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanSpawn(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanPushItems(lua_State* L) { // get: monsterType:canPushItems() set: monsterType:canPushItems(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.canPushItems); @@ -299,7 +299,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanPushItems(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanPushCreatures(lua_State* L) { // get: monsterType:canPushCreatures() set: monsterType:canPushCreatures(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.canPushCreatures); @@ -315,7 +315,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanPushCreatures(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCritChance(lua_State* L) { // get: monsterType:critChance() set: monsterType:critChance(int) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 2) { monsterType->info.critChance = getNumber(L, 2); @@ -329,7 +329,7 @@ int MonsterTypeFunctions::luaMonsterTypeCritChance(lua_State* L) { int32_t MonsterTypeFunctions::luaMonsterTypeName(lua_State* L) { // get: monsterType:name() set: monsterType:name(name) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushString(L, monsterType->name); @@ -345,7 +345,7 @@ int32_t MonsterTypeFunctions::luaMonsterTypeName(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeNameDescription(lua_State* L) { // get: monsterType:nameDescription() set: monsterType:nameDescription(desc) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushString(L, monsterType->nameDescription); @@ -361,7 +361,7 @@ int MonsterTypeFunctions::luaMonsterTypeNameDescription(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypegetCorpseId(lua_State* L) { // monsterType:getCorpseId() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { lua_pushnumber(L, monsterType->info.lookcorpse); } else { @@ -372,7 +372,7 @@ int MonsterTypeFunctions::luaMonsterTypegetCorpseId(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeHealth(lua_State* L) { // get: monsterType:health() set: monsterType:health(health) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.health); @@ -388,7 +388,7 @@ int MonsterTypeFunctions::luaMonsterTypeHealth(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeMaxHealth(lua_State* L) { // get: monsterType:maxHealth() set: monsterType:maxHealth(health) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.healthMax); @@ -404,7 +404,7 @@ int MonsterTypeFunctions::luaMonsterTypeMaxHealth(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRunHealth(lua_State* L) { // get: monsterType:runHealth() set: monsterType:runHealth(health) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.runAwayHealth); @@ -420,7 +420,7 @@ int MonsterTypeFunctions::luaMonsterTypeRunHealth(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeExperience(lua_State* L) { // get: monsterType:experience() set: monsterType:experience(exp) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.experience); @@ -436,7 +436,7 @@ int MonsterTypeFunctions::luaMonsterTypeExperience(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeFaction(lua_State* L) { // get: monsterType:faction() set: monsterType:faction(faction) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.faction); @@ -452,7 +452,7 @@ int MonsterTypeFunctions::luaMonsterTypeFaction(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) { // get: monsterType:enemyFactions() set: monsterType:enemyFactions(enemyFaction) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_createtable(L, monsterType->info.enemyFactions.size(), 0); @@ -475,7 +475,7 @@ int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer(lua_State* L) { // get: monsterType:targetPreferPlayer() set: monsterType:targetPreferPlayer(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushboolean(L, monsterType->info.targetPreferPlayer); @@ -491,7 +491,7 @@ int MonsterTypeFunctions::luaMonsterTypeTargetPreferPlayer(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster(lua_State* L) { // get: monsterType:targetPreferMaster() set: monsterType:targetPreferMaster(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.faction); @@ -507,7 +507,7 @@ int MonsterTypeFunctions::luaMonsterTypeTargetPreferMaster(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRaceid(lua_State* L) { // get: monsterType:raceId() set: monsterType:raceId(id) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.raceid); @@ -524,7 +524,7 @@ int MonsterTypeFunctions::luaMonsterTypeRaceid(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiarytoKill(lua_State* L) { // get: monsterType:BestiarytoKill() set: monsterType:BestiarytoKill(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryToUnlock); @@ -540,7 +540,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiarytoKill(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryFirstUnlock(lua_State* L) { // get: monsterType:BestiaryFirstUnlock() set: monsterType:BestiaryFirstUnlock(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryFirstUnlock); @@ -556,7 +556,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryFirstUnlock(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiarySecondUnlock(lua_State* L) { // get: monsterType:BestiarySecondUnlock() set: monsterType:BestiarySecondUnlock(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiarySecondUnlock); @@ -572,7 +572,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiarySecondUnlock(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryCharmsPoints(lua_State* L) { // get: monsterType:BestiaryCharmsPoints() set: monsterType:BestiaryCharmsPoints(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryCharmsPoints); @@ -588,7 +588,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryCharmsPoints(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryStars(lua_State* L) { // get: monsterType:BestiaryStars() set: monsterType:BestiaryStars(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryStars); @@ -604,7 +604,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryStars(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryOccurrence(lua_State* L) { // get: monsterType:BestiaryOccurrence() set: monsterType:BestiaryOccurrence(value) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryOccurrence); @@ -620,7 +620,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryOccurrence(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryLocations(lua_State* L) { // get: monsterType:BestiaryLocations() set: monsterType:BestiaryLocations(string) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushString(L, monsterType->info.bestiaryLocations); @@ -636,7 +636,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryLocations(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryclass(lua_State* L) { // get: monsterType:Bestiaryclass() set: monsterType:Bestiaryclass(string) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushString(L, monsterType->info.bestiaryClass); @@ -652,7 +652,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryclass(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBestiaryrace(lua_State* L) { // get: monsterType:Bestiaryrace() set: monsterType:Bestiaryrace(raceid) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryRace); @@ -669,7 +669,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryrace(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCombatImmunities(lua_State* L) { // get: monsterType:combatImmunities() set: monsterType:combatImmunities(immunity) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -725,7 +725,7 @@ int MonsterTypeFunctions::luaMonsterTypeCombatImmunities(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeConditionImmunities(lua_State* L) { // get: monsterType:conditionImmunities() set: monsterType:conditionImmunities(immunity) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -783,7 +783,7 @@ int MonsterTypeFunctions::luaMonsterTypeConditionImmunities(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetAttackList(lua_State* L) { // monsterType:getAttackList() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -813,7 +813,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetAttackList(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { // monsterType:addAttack(monsterspell) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { const auto spell = getUserdataShared(L, 2); if (spell) { @@ -834,7 +834,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetDefenseList(lua_State* L) { // monsterType:getDefenseList() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -864,7 +864,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetDefenseList(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetTypeName(lua_State* L) { // monsterType:getTypeName() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { return 1; } @@ -875,7 +875,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetTypeName(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { // monsterType:addDefense(monsterspell) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { const auto spell = getUserdataShared(L, 2); if (spell) { @@ -896,7 +896,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddElement(lua_State* L) { // monsterType:addElement(type, percent) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { CombatType_t element = getNumber(L, 2); monsterType->info.elementMap[element] = getNumber(L, 3); @@ -909,7 +909,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddElement(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddReflect(lua_State* L) { // monsterType:addReflect(type, percent) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { CombatType_t element = getNumber(L, 2); monsterType->info.reflectMap[element] = getNumber(L, 3); @@ -922,7 +922,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddReflect(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddHealing(lua_State* L) { // monsterType:addHealing(type, percent) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { CombatType_t element = getNumber(L, 2); monsterType->info.healingMap[element] = getNumber(L, 3); @@ -935,7 +935,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddHealing(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetElementList(lua_State* L) { // monsterType:getElementList() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -951,7 +951,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetElementList(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddVoice(lua_State* L) { // monsterType:addVoice(sentence, interval, chance, yell) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { voiceBlock_t voice; voice.text = getString(L, 2); @@ -968,7 +968,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddVoice(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetVoices(lua_State* L) { // monsterType:getVoices() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -987,7 +987,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetVoices(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetLoot(lua_State* L) { // monsterType:getLoot() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -999,7 +999,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetLoot(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddLoot(lua_State* L) { // monsterType:addLoot(loot) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { const auto loot = getUserdataShared(L, 2); if (loot) { @@ -1016,7 +1016,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddLoot(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetCreatureEvents(lua_State* L) { // monsterType:getCreatureEvents() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -1033,7 +1033,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetCreatureEvents(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRegisterEvent(lua_State* L) { // monsterType:registerEvent(name) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { auto eventName = getString(L, 2); monsterType->info.scripts.insert(eventName); @@ -1055,7 +1055,7 @@ int MonsterTypeFunctions::luaMonsterTypeEventOnCallback(lua_State* L) { // monsterType:onDisappear(callback) // monsterType:onMove(callback) // monsterType:onSay(callback) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (monsterType->loadCallback(&g_scripts().getScriptInterface())) { pushBoolean(L, true); @@ -1082,7 +1082,7 @@ int MonsterTypeFunctions::luaMonsterTypeEventType(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetSummonList(lua_State* L) { // monsterType:getSummonList() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -1102,7 +1102,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetSummonList(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddSummon(lua_State* L) { // monsterType:addSummon(name, interval, chance[, count = 1]) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { summonBlock_t summon; summon.name = getString(L, 2); @@ -1119,7 +1119,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSummon(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeMaxSummons(lua_State* L) { // get: monsterType:maxSummons() set: monsterType:maxSummons(ammount) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.maxSummons); @@ -1135,7 +1135,7 @@ int MonsterTypeFunctions::luaMonsterTypeMaxSummons(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeArmor(lua_State* L) { // get: monsterType:armor() set: monsterType:armor(armor) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.armor); @@ -1151,7 +1151,7 @@ int MonsterTypeFunctions::luaMonsterTypeArmor(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeMitigation(lua_State* L) { // get: monsterType:mitigation() set: monsterType:mitigation(mitigation) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -1169,7 +1169,7 @@ int MonsterTypeFunctions::luaMonsterTypeMitigation(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeDefense(lua_State* L) { // get: monsterType:defense() set: monsterType:defense(defense) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.defense); @@ -1185,7 +1185,7 @@ int MonsterTypeFunctions::luaMonsterTypeDefense(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeOutfit(lua_State* L) { // get: monsterType:outfit() set: monsterType:outfit(outfit) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushOutfit(L, monsterType->info.outfit); @@ -1207,7 +1207,7 @@ int MonsterTypeFunctions::luaMonsterTypeOutfit(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRace(lua_State* L) { // get: monsterType:race() set: monsterType:race(race) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); std::string race = getString(L, 2); if (monsterType) { if (lua_gettop(L) == 1) { @@ -1242,7 +1242,7 @@ int MonsterTypeFunctions::luaMonsterTypeRace(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCorpseId(lua_State* L) { // get: monsterType:corpseId() set: monsterType:corpseId(id) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.lookcorpse); @@ -1258,7 +1258,7 @@ int MonsterTypeFunctions::luaMonsterTypeCorpseId(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeManaCost(lua_State* L) { // get: monsterType:manaCost() set: monsterType:manaCost(mana) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.manaCost); @@ -1274,7 +1274,7 @@ int MonsterTypeFunctions::luaMonsterTypeManaCost(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBaseSpeed(lua_State* L) { // monsterType:baseSpeed() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->getBaseSpeed()); @@ -1289,7 +1289,7 @@ int MonsterTypeFunctions::luaMonsterTypeBaseSpeed(lua_State* L) { } int MonsterTypeFunctions::luaMonsterTypeLight(lua_State* L) { // get: monsterType:light() set: monsterType:light(color, level) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -1309,7 +1309,7 @@ int MonsterTypeFunctions::luaMonsterTypeLight(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeStaticAttackChance(lua_State* L) { // get: monsterType:staticAttackChance() set: monsterType:staticAttackChance(chance) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.staticAttackChance); @@ -1325,7 +1325,7 @@ int MonsterTypeFunctions::luaMonsterTypeStaticAttackChance(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeTargetDistance(lua_State* L) { // get: monsterType:targetDistance() set: monsterType:targetDistance(distance) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.targetDistance); @@ -1341,7 +1341,7 @@ int MonsterTypeFunctions::luaMonsterTypeTargetDistance(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeYellChance(lua_State* L) { // get: monsterType:yellChance() set: monsterType:yellChance(chance) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { if (lua_gettop(L) == 1) { @@ -1362,7 +1362,7 @@ int MonsterTypeFunctions::luaMonsterTypeYellChance(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeYellSpeedTicks(lua_State* L) { // get: monsterType:yellSpeedTicks() set: monsterType:yellSpeedTicks(rate) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.yellSpeedTicks); @@ -1378,7 +1378,7 @@ int MonsterTypeFunctions::luaMonsterTypeYellSpeedTicks(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeChangeTargetChance(lua_State* L) { // monsterType:getChangeTargetChance() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.changeTargetChance); @@ -1394,7 +1394,7 @@ int MonsterTypeFunctions::luaMonsterTypeChangeTargetChance(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeChangeTargetSpeed(lua_State* L) { // get: monsterType:changeTargetSpeed() set: monsterType:changeTargetSpeed(speed) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.changeTargetSpeed); @@ -1410,7 +1410,7 @@ int MonsterTypeFunctions::luaMonsterTypeChangeTargetSpeed(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanWalkOnEnergy(lua_State* L) { // get: monsterType:canWalkOnEnergy() set: monsterType:canWalkOnEnergy(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.canWalkOnEnergy); @@ -1426,7 +1426,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanWalkOnEnergy(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanWalkOnFire(lua_State* L) { // get: monsterType:canWalkOnFire() set: monsterType:canWalkOnFire(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.canWalkOnFire); @@ -1442,7 +1442,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanWalkOnFire(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeCanWalkOnPoison(lua_State* L) { // get: monsterType:canWalkOnPoison() set: monsterType:canWalkOnPoison(bool) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.canWalkOnPoison); @@ -1458,7 +1458,7 @@ int MonsterTypeFunctions::luaMonsterTypeCanWalkOnPoison(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetNearest(lua_State* L) { // monsterType:strategiesTargetNearest() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.strategiesTargetNearest); @@ -1474,7 +1474,7 @@ int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetNearest(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetHealth(lua_State* L) { // monsterType:strategiesTargetHealth() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.strategiesTargetHealth); @@ -1490,7 +1490,7 @@ int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetHealth(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetDamage(lua_State* L) { // monsterType:strategiesTargetDamage() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.strategiesTargetDamage); @@ -1506,7 +1506,7 @@ int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetDamage(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetRandom(lua_State* L) { // monsterType:strategiesTargetRandom() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.strategiesTargetRandom); @@ -1526,7 +1526,7 @@ int MonsterTypeFunctions::luaMonsterTypeStrategiesTargetRandom(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRespawnTypePeriod(lua_State* L) { // monsterType:respawnTypePeriod() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.respawnType.period); @@ -1542,7 +1542,7 @@ int MonsterTypeFunctions::luaMonsterTypeRespawnTypePeriod(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeRespawnTypeIsUnderground(lua_State* L) { // monsterType:respawnTypeIsUnderground() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.respawnType.underground); @@ -1559,7 +1559,7 @@ int MonsterTypeFunctions::luaMonsterTypeRespawnTypeIsUnderground(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBossRace(lua_State* L) { // set: monsterType:bosstiaryRace(raceId, class) // get: monsterType:bosstiaryRace() = this return only class name - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -1586,7 +1586,7 @@ int MonsterTypeFunctions::luaMonsterTypeBossRace(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeBossRaceId(lua_State* L) { // set: monsterType:bossRaceId(raceId) // get: monsterType:bossRaceId() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_TYPE_NOT_FOUND)); @@ -1611,7 +1611,7 @@ int MonsterTypeFunctions::luaMonsterTypeBossRaceId(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeSoundChance(lua_State* L) { // get: monsterType:soundChance() set: monsterType:soundChance(chance) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1629,7 +1629,7 @@ int MonsterTypeFunctions::luaMonsterTypeSoundChance(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeSoundSpeedTicks(lua_State* L) { // get: monsterType:soundSpeedTicks() set: monsterType:soundSpeedTicks(ticks) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1647,7 +1647,7 @@ int MonsterTypeFunctions::luaMonsterTypeSoundSpeedTicks(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeAddSound(lua_State* L) { // monsterType:addSound(soundId) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1661,7 +1661,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSound(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeGetSounds(lua_State* L) { // monsterType:getSounds() - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { lua_pushnil(L); return 1; @@ -1680,7 +1680,7 @@ int MonsterTypeFunctions::luaMonsterTypeGetSounds(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypedeathSound(lua_State* L) { // get: monsterType:deathSound() set: monsterType:deathSound(sound) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1699,7 +1699,7 @@ int MonsterTypeFunctions::luaMonsterTypedeathSound(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeVariant(lua_State* L) { // get: monsterType:variant() set: monsterType:variant(variantName) - const auto monsterType = getUserdataShared(L, 1); + const auto &monsterType = getUserdataShared(L, 1); if (!monsterType) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/npc/npc_functions.cpp b/src/lua/functions/creatures/npc/npc_functions.cpp index 13e9b499abc..615a026190d 100644 --- a/src/lua/functions/creatures/npc/npc_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_functions.cpp @@ -53,7 +53,7 @@ int NpcFunctions::luaNpcIsNpc(lua_State* L) { int NpcFunctions::luaNpcSetMasterPos(lua_State* L) { // npc:setMasterPos(pos) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); @@ -68,7 +68,7 @@ int NpcFunctions::luaNpcSetMasterPos(lua_State* L) { int NpcFunctions::luaNpcGetCurrency(lua_State* L) { // npc:getCurrency() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -80,7 +80,7 @@ int NpcFunctions::luaNpcGetCurrency(lua_State* L) { int NpcFunctions::luaNpcSetCurrency(lua_State* L) { // npc:getCurrency() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); @@ -93,7 +93,7 @@ int NpcFunctions::luaNpcSetCurrency(lua_State* L) { int NpcFunctions::luaNpcGetSpeechBubble(lua_State* L) { // npc:getSpeechBubble() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -105,7 +105,7 @@ int NpcFunctions::luaNpcGetSpeechBubble(lua_State* L) { int NpcFunctions::luaNpcSetSpeechBubble(lua_State* L) { // npc:setSpeechBubble(speechBubble) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -117,7 +117,7 @@ int NpcFunctions::luaNpcSetSpeechBubble(lua_State* L) { int NpcFunctions::luaNpcGetName(lua_State* L) { // npc:getName() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -130,7 +130,7 @@ int NpcFunctions::luaNpcGetName(lua_State* L) { int NpcFunctions::luaNpcSetName(lua_State* L) { // npc:setName(name) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); const std::string &name = getString(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -143,7 +143,7 @@ int NpcFunctions::luaNpcSetName(lua_State* L) { int NpcFunctions::luaNpcPlace(lua_State* L) { // npc:place(position[, extended = false[, force = true]]) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -183,9 +183,9 @@ int NpcFunctions::luaNpcSay(lua_State* L) { bool ghost = getBoolean(L, 4, false); - SpeakClasses type = getNumber(L, 3, TALKTYPE_PRIVATE_NP); + const auto &type = getNumber(L, 3, TALKTYPE_PRIVATE_NP); const std::string &text = getString(L, 2); - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { lua_pushnil(L); return 1; @@ -210,7 +210,7 @@ int NpcFunctions::luaNpcSay(lua_State* L) { */ int NpcFunctions::luaNpcTurnToCreature(lua_State* L) { // npc:turnToCreature(creature, true) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); std::shared_ptr creature = getCreature(L, 2); if (!npc) { @@ -236,9 +236,9 @@ int NpcFunctions::luaNpcTurnToCreature(lua_State* L) { int NpcFunctions::luaNpcSetPlayerInteraction(lua_State* L) { // npc:setPlayerInteraction(creature, topic = 0) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); std::shared_ptr creature = getCreature(L, 2); - uint16_t topicId = getNumber(L, 3, 0); + auto topicId = getNumber(L, 3, 0); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -259,7 +259,7 @@ int NpcFunctions::luaNpcSetPlayerInteraction(lua_State* L) { int NpcFunctions::luaNpcRemovePlayerInteraction(lua_State* L) { // npc:removePlayerInteraction() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); std::shared_ptr creature = getCreature(L, 2); if (!npc) { @@ -281,7 +281,7 @@ int NpcFunctions::luaNpcRemovePlayerInteraction(lua_State* L) { int NpcFunctions::luaNpcIsInteractingWithPlayer(lua_State* L) { // npc:isInteractingWithPlayer(creature) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); std::shared_ptr creature = getCreature(L, 2); if (!npc) { @@ -302,9 +302,9 @@ int NpcFunctions::luaNpcIsInteractingWithPlayer(lua_State* L) { int NpcFunctions::luaNpcIsPlayerInteractingOnTopic(lua_State* L) { // npc:isPlayerInteractingOnTopic(creature, topicId = 0) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); std::shared_ptr creature = getCreature(L, 2); - uint32_t topicId = getNumber(L, 3, 0); + auto topicId = getNumber(L, 3, 0); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -324,9 +324,9 @@ int NpcFunctions::luaNpcIsPlayerInteractingOnTopic(lua_State* L) { int NpcFunctions::luaNpcIsInTalkRange(lua_State* L) { // npc:isInTalkRange(position[, range = 4]) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); const Position &position = getPosition(L, 2); - uint32_t range = getNumber(L, 3, 4); + auto range = getNumber(L, 3, 4); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -340,7 +340,7 @@ int NpcFunctions::luaNpcIsInTalkRange(lua_State* L) { int NpcFunctions::luaNpcOpenShopWindow(lua_State* L) { // npc:openShopWindow(player) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); @@ -417,7 +417,7 @@ int NpcFunctions::luaNpcCloseShopWindow(lua_State* L) { return 1; } - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -434,7 +434,7 @@ int NpcFunctions::luaNpcCloseShopWindow(lua_State* L) { int NpcFunctions::luaNpcIsMerchant(lua_State* L) { // npc:isMerchant() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); @@ -454,7 +454,7 @@ int NpcFunctions::luaNpcIsMerchant(lua_State* L) { int NpcFunctions::luaNpcGetShopItem(lua_State* L) { // npc:getShopItem(itemId) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -463,7 +463,7 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { auto playerGUID = getNumber(L, 2, 0); const auto &shopItems = npc->getShopItemVector(playerGUID); - for (ShopBlock shopBlock : shopItems) { + for (const ShopBlock &shopBlock : shopItems) { setField(L, "id", shopBlock.itemId); setField(L, "name", shopBlock.itemName); setField(L, "subType", shopBlock.itemSubType); @@ -479,7 +479,7 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { int NpcFunctions::luaNpcMove(lua_State* L) { // npc:move(direction) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (npc) { g_game().internalMoveCreature(npc, getNumber(L, 2)); } @@ -488,7 +488,7 @@ int NpcFunctions::luaNpcMove(lua_State* L) { int NpcFunctions::luaNpcTurn(lua_State* L) { // npc:turn(direction) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (npc) { g_game().internalCreatureTurn(npc, getNumber(L, 2)); } @@ -497,7 +497,7 @@ int NpcFunctions::luaNpcTurn(lua_State* L) { int NpcFunctions::luaNpcFollow(lua_State* L) { // npc:follow(player) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { pushBoolean(L, false); return 1; @@ -515,7 +515,7 @@ int NpcFunctions::luaNpcFollow(lua_State* L) { int NpcFunctions::luaNpcGetId(lua_State* L) { // npc:getId() - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); lua_pushnil(L); @@ -528,7 +528,7 @@ int NpcFunctions::luaNpcGetId(lua_State* L) { int NpcFunctions::luaNpcSellItem(lua_State* L) { // npc:sellItem(player, itemid, amount, subtype, actionid, ignoreCap, inBackpacks) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); @@ -542,10 +542,10 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { return 1; } - uint16_t itemId = getNumber(L, 3); + auto itemId = getNumber(L, 3); double amount = getNumber(L, 4); - uint16_t subType = getNumber(L, 5, 1); - uint16_t actionId = getNumber(L, 6, 0); + auto subType = getNumber(L, 5, 1); + auto actionId = getNumber(L, 6, 0); bool ignoreCap = getBoolean(L, 7, false); bool inBackpacks = getBoolean(L, 8, false); @@ -574,7 +574,7 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { uint64_t pricePerUnit = 0; const auto &shopVector = npc->getShopItemVector(player->getGUID()); - for (ShopBlock shopBlock : shopVector) { + for (const ShopBlock &shopBlock : shopVector) { if (itemId == shopBlock.itemId && shopBlock.itemBuyPrice != 0) { pricePerUnit = shopBlock.itemBuyPrice; break; @@ -646,7 +646,7 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) { // npc:getDistanceTo(uid) - std::shared_ptr npc = getUserdataShared(L, 1); + const auto &npc = getUserdataShared(L, 1); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/player/guild_functions.cpp b/src/lua/functions/creatures/player/guild_functions.cpp index 196f0f9d31e..55b74ad43c1 100644 --- a/src/lua/functions/creatures/player/guild_functions.cpp +++ b/src/lua/functions/creatures/player/guild_functions.cpp @@ -15,7 +15,7 @@ int GuildFunctions::luaGuildCreate(lua_State* L) { uint32_t id = getNumber(L, 2); - const auto guild = g_game().getGuild(id); + const auto &guild = g_game().getGuild(id); if (guild) { pushUserdata(L, guild); setMetatable(L, -1, "Guild"); @@ -26,7 +26,7 @@ int GuildFunctions::luaGuildCreate(lua_State* L) { } int GuildFunctions::luaGuildGetId(lua_State* L) { - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (guild) { lua_pushnumber(L, guild->getId()); } else { @@ -37,7 +37,7 @@ int GuildFunctions::luaGuildGetId(lua_State* L) { int GuildFunctions::luaGuildGetName(lua_State* L) { // guild:getName() - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -48,7 +48,7 @@ int GuildFunctions::luaGuildGetName(lua_State* L) { int GuildFunctions::luaGuildGetMembersOnline(lua_State* L) { // guild:getMembersOnline() - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -58,7 +58,7 @@ int GuildFunctions::luaGuildGetMembersOnline(lua_State* L) { lua_createtable(L, members.size(), 0); int index = 0; - for (std::shared_ptr player : members) { + for (const auto &player : members) { pushUserdata(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); @@ -68,7 +68,7 @@ int GuildFunctions::luaGuildGetMembersOnline(lua_State* L) { int GuildFunctions::luaGuildGetBankBalance(lua_State* L) { // guild:getBankBalance() - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -79,7 +79,7 @@ int GuildFunctions::luaGuildGetBankBalance(lua_State* L) { int GuildFunctions::luaGuildSetBankBalance(lua_State* L) { // guild:setBankBalance(bankBalance) - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -92,7 +92,7 @@ int GuildFunctions::luaGuildSetBankBalance(lua_State* L) { int GuildFunctions::luaGuildAddRank(lua_State* L) { // guild:addRank(id, name, level) - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -107,7 +107,7 @@ int GuildFunctions::luaGuildAddRank(lua_State* L) { int GuildFunctions::luaGuildGetRankById(lua_State* L) { // guild:getRankById(id) - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -128,7 +128,7 @@ int GuildFunctions::luaGuildGetRankById(lua_State* L) { int GuildFunctions::luaGuildGetRankByLevel(lua_State* L) { // guild:getRankByLevel(level) - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -149,7 +149,7 @@ int GuildFunctions::luaGuildGetRankByLevel(lua_State* L) { int GuildFunctions::luaGuildGetMotd(lua_State* L) { // guild:getMotd() - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; @@ -160,7 +160,7 @@ int GuildFunctions::luaGuildGetMotd(lua_State* L) { int GuildFunctions::luaGuildSetMotd(lua_State* L) { // guild:setMotd(motd) - const auto guild = getUserdataShared(L, 1); + const auto &guild = getUserdataShared(L, 1); if (!guild) { lua_pushnil(L); return 1; diff --git a/src/lua/functions/creatures/player/mount_functions.cpp b/src/lua/functions/creatures/player/mount_functions.cpp index 49b16db6caa..49f06a2b76a 100644 --- a/src/lua/functions/creatures/player/mount_functions.cpp +++ b/src/lua/functions/creatures/player/mount_functions.cpp @@ -37,7 +37,7 @@ int MountFunctions::luaCreateMount(lua_State* L) { int MountFunctions::luaMountGetName(lua_State* L) { // mount:getName() - const std::shared_ptr mount = getUserdataShared(L, 1); + const auto &mount = getUserdataShared(L, 1); if (mount) { pushString(L, mount->name); } else { @@ -49,7 +49,7 @@ int MountFunctions::luaMountGetName(lua_State* L) { int MountFunctions::luaMountGetId(lua_State* L) { // mount:getId() - const std::shared_ptr mount = getUserdataShared(L, 1); + const auto &mount = getUserdataShared(L, 1); if (mount) { lua_pushnumber(L, mount->id); } else { @@ -61,7 +61,7 @@ int MountFunctions::luaMountGetId(lua_State* L) { int MountFunctions::luaMountGetClientId(lua_State* L) { // mount:getClientId() - const std::shared_ptr mount = getUserdataShared(L, 1); + const auto &mount = getUserdataShared(L, 1); if (mount) { lua_pushnumber(L, mount->clientId); } else { @@ -73,7 +73,7 @@ int MountFunctions::luaMountGetClientId(lua_State* L) { int MountFunctions::luaMountGetSpeed(lua_State* L) { // mount:getSpeed() - const std::shared_ptr mount = getUserdataShared(L, 1); + const auto &mount = getUserdataShared(L, 1); if (mount) { lua_pushnumber(L, mount->speed); } else { diff --git a/src/lua/functions/creatures/player/party_functions.cpp b/src/lua/functions/creatures/player/party_functions.cpp index d739cde3ceb..fac7fa8e910 100644 --- a/src/lua/functions/creatures/player/party_functions.cpp +++ b/src/lua/functions/creatures/player/party_functions.cpp @@ -16,13 +16,13 @@ int32_t PartyFunctions::luaPartyCreate(lua_State* L) { // Party(userdata) - std::shared_ptr player = getUserdataShared(L, 2); + const auto &player = getUserdataShared(L, 2); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr party = player->getParty(); + auto party = player->getParty(); if (!party) { party = Party::create(player); g_game().updatePlayerShield(player); @@ -37,7 +37,7 @@ int32_t PartyFunctions::luaPartyCreate(lua_State* L) { int PartyFunctions::luaPartyDisband(lua_State* L) { // party:disband() - std::shared_ptr* partyPtr = getRawUserDataShared(L, 1); + auto* partyPtr = getRawUserDataShared(L, 1); if (partyPtr && *partyPtr) { std::shared_ptr &party = *partyPtr; party->disband(); @@ -51,13 +51,13 @@ int PartyFunctions::luaPartyDisband(lua_State* L) { int PartyFunctions::luaPartyGetLeader(lua_State* L) { // party:getLeader() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (!party) { lua_pushnil(L); return 1; } - std::shared_ptr leader = party->getLeader(); + const auto &leader = party->getLeader(); if (leader) { pushUserdata(L, leader); setMetatable(L, -1, "Player"); @@ -75,7 +75,7 @@ int PartyFunctions::luaPartySetLeader(lua_State* L) { return 1; } - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { pushBoolean(L, party->passPartyLeadership(player)); } else { @@ -86,7 +86,7 @@ int PartyFunctions::luaPartySetLeader(lua_State* L) { int PartyFunctions::luaPartyGetMembers(lua_State* L) { // party:getMembers() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (!party) { lua_pushnil(L); return 1; @@ -94,7 +94,7 @@ int PartyFunctions::luaPartyGetMembers(lua_State* L) { int index = 0; lua_createtable(L, party->getMemberCount(), 0); - for (std::shared_ptr player : party->getMembers()) { + for (const auto &player : party->getMembers()) { pushUserdata(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); @@ -104,7 +104,7 @@ int PartyFunctions::luaPartyGetMembers(lua_State* L) { int PartyFunctions::luaPartyGetMemberCount(lua_State* L) { // party:getMemberCount() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { lua_pushnumber(L, party->getMemberCount()); } else { @@ -115,12 +115,12 @@ int PartyFunctions::luaPartyGetMemberCount(lua_State* L) { int PartyFunctions::luaPartyGetInvitees(lua_State* L) { // party:getInvitees() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { lua_createtable(L, party->getInvitationCount(), 0); int index = 0; - for (std::shared_ptr player : party->getInvitees()) { + for (const auto &player : party->getInvitees()) { pushUserdata(L, player); setMetatable(L, -1, "Player"); lua_rawseti(L, -2, ++index); @@ -133,7 +133,7 @@ int PartyFunctions::luaPartyGetInvitees(lua_State* L) { int PartyFunctions::luaPartyGetInviteeCount(lua_State* L) { // party:getInviteeCount() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { lua_pushnumber(L, party->getInvitationCount()); } else { @@ -150,7 +150,7 @@ int PartyFunctions::luaPartyAddInvite(lua_State* L) { return 1; } - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->invitePlayer(player)); } else { @@ -167,7 +167,7 @@ int PartyFunctions::luaPartyRemoveInvite(lua_State* L) { return 1; } - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->removeInvite(player)); } else { @@ -184,7 +184,7 @@ int PartyFunctions::luaPartyAddMember(lua_State* L) { return 1; } - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->joinParty(player)); } else { @@ -201,7 +201,7 @@ int PartyFunctions::luaPartyRemoveMember(lua_State* L) { return 1; } - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->leaveParty(player)); } else { @@ -212,7 +212,7 @@ int PartyFunctions::luaPartyRemoveMember(lua_State* L) { int PartyFunctions::luaPartyIsSharedExperienceActive(lua_State* L) { // party:isSharedExperienceActive() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { pushBoolean(L, party->isSharedExperienceActive()); } else { @@ -223,7 +223,7 @@ int PartyFunctions::luaPartyIsSharedExperienceActive(lua_State* L) { int PartyFunctions::luaPartyIsSharedExperienceEnabled(lua_State* L) { // party:isSharedExperienceEnabled() - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { pushBoolean(L, party->isSharedExperienceEnabled()); } else { @@ -235,7 +235,7 @@ int PartyFunctions::luaPartyIsSharedExperienceEnabled(lua_State* L) { int PartyFunctions::luaPartyShareExperience(lua_State* L) { // party:shareExperience(experience) uint64_t experience = getNumber(L, 2); - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { party->shareExperience(experience); pushBoolean(L, true); @@ -248,7 +248,7 @@ int PartyFunctions::luaPartyShareExperience(lua_State* L) { int PartyFunctions::luaPartySetSharedExperience(lua_State* L) { // party:setSharedExperience(active) bool active = getBoolean(L, 2); - std::shared_ptr party = getUserdataShared(L, 1); + const auto &party = getUserdataShared(L, 1); if (party) { pushBoolean(L, party->setSharedExperience(party->getLeader(), active)); } else { diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 7bbe495f7c2..28e1fac9574 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -17,9 +17,7 @@ #include "creatures/players/player.hpp" #include "creatures/players/wheel/player_wheel.hpp" #include "creatures/players/achievement/player_achievement.hpp" -#include "creatures/players/cyclopedia/player_badge.hpp" #include "creatures/players/cyclopedia/player_cyclopedia.hpp" -#include "creatures/players/cyclopedia/player_title.hpp" #include "game/game.hpp" #include "io/iologindata.hpp" #include "io/ioprey.hpp" @@ -29,12 +27,11 @@ #include "map/spectators.hpp" #include "enums/account_errors.hpp" -#include "enums/account_type.hpp" #include "enums/account_coins.hpp" int PlayerFunctions::luaPlayerSendInventory(lua_State* L) { // player:sendInventory() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -48,13 +45,13 @@ int PlayerFunctions::luaPlayerSendInventory(lua_State* L) { int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { // player:sendLootStats(item, count) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { lua_pushnil(L); return 1; @@ -74,13 +71,13 @@ int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { int PlayerFunctions::luaPlayerUpdateSupplyTracker(lua_State* L) { // player:updateSupplyTracker(item) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { lua_pushnil(L); return 1; @@ -94,19 +91,19 @@ int PlayerFunctions::luaPlayerUpdateSupplyTracker(lua_State* L) { int PlayerFunctions::luaPlayerUpdateKillTracker(lua_State* L) { // player:updateKillTracker(creature, corpse) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr monster = getUserdataShared(L, 2); + const auto &monster = getUserdataShared(L, 2); if (!monster) { lua_pushnil(L); return 1; } - std::shared_ptr corpse = getUserdataShared(L, 3); + const auto &corpse = getUserdataShared(L, 3); if (!corpse) { lua_pushnil(L); return 1; @@ -157,7 +154,7 @@ int PlayerFunctions::luaPlayerCreate(lua_State* L) { int PlayerFunctions::luaPlayerResetCharmsMonsters(lua_State* L) { // player:resetCharmsBestiary() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setCharmPoints(0); player->setCharmExpansion(false); @@ -175,7 +172,7 @@ int PlayerFunctions::luaPlayerResetCharmsMonsters(lua_State* L) { int PlayerFunctions::luaPlayerUnlockAllCharmRunes(lua_State* L) { // player:unlockAllCharmRunes() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { for (int8_t i = CHARM_WOUND; i <= CHARM_LAST; i++) { const auto charm = g_iobestiary().getBestiaryCharm(static_cast(i)); @@ -193,7 +190,7 @@ int PlayerFunctions::luaPlayerUnlockAllCharmRunes(lua_State* L) { int PlayerFunctions::luaPlayeraddCharmPoints(lua_State* L) { // player:addCharmPoints() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int16_t charms = getNumber(L, 2); if (charms >= 0) { @@ -217,7 +214,7 @@ int PlayerFunctions::luaPlayerIsPlayer(lua_State* L) { int PlayerFunctions::luaPlayerGetGuid(lua_State* L) { // player:getGuid() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getGUID()); } else { @@ -228,7 +225,7 @@ int PlayerFunctions::luaPlayerGetGuid(lua_State* L) { int PlayerFunctions::luaPlayerGetIp(lua_State* L) { // player:getIp() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getIP()); } else { @@ -239,7 +236,7 @@ int PlayerFunctions::luaPlayerGetIp(lua_State* L) { int PlayerFunctions::luaPlayerGetAccountId(lua_State* L) { // player:getAccountId() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || player->getAccountId() == 0) { lua_pushnil(L); return 1; @@ -252,7 +249,7 @@ int PlayerFunctions::luaPlayerGetAccountId(lua_State* L) { int PlayerFunctions::luaPlayerGetLastLoginSaved(lua_State* L) { // player:getLastLoginSaved() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getLastLoginSaved()); } else { @@ -263,7 +260,7 @@ int PlayerFunctions::luaPlayerGetLastLoginSaved(lua_State* L) { int PlayerFunctions::luaPlayerGetLastLogout(lua_State* L) { // player:getLastLogout() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getLastLogout()); } else { @@ -274,7 +271,7 @@ int PlayerFunctions::luaPlayerGetLastLogout(lua_State* L) { int PlayerFunctions::luaPlayerGetAccountType(lua_State* L) { // player:getAccountType() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getAccountType()); } else { @@ -285,7 +282,7 @@ int PlayerFunctions::luaPlayerGetAccountType(lua_State* L) { int PlayerFunctions::luaPlayerSetAccountType(lua_State* L) { // player:setAccountType(accountType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { lua_pushnil(L); return 1; @@ -307,7 +304,7 @@ int PlayerFunctions::luaPlayerSetAccountType(lua_State* L) { int PlayerFunctions::luaPlayerAddBestiaryKill(lua_State* L) { // player:addBestiaryKill(name[, amount = 1]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const auto mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { @@ -324,7 +321,7 @@ int PlayerFunctions::luaPlayerAddBestiaryKill(lua_State* L) { int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State* L) { // player:isMonsterBestiaryUnlocked(raceId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -351,7 +348,7 @@ int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State* L) { int PlayerFunctions::luaPlayergetCharmMonsterType(lua_State* L) { // player:getCharmMonsterType(charmRune_t) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { charmRune_t charmid = getNumber(L, 2); uint16_t raceid = player->parseRacebyCharm(charmid, false, 0); @@ -374,7 +371,7 @@ int PlayerFunctions::luaPlayergetCharmMonsterType(lua_State* L) { int PlayerFunctions::luaPlayerRemovePreyStamina(lua_State* L) { // player:removePreyStamina(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { g_ioprey().checkPlayerPreys(player, getNumber(L, 2, 1)); pushBoolean(L, true); @@ -386,7 +383,7 @@ int PlayerFunctions::luaPlayerRemovePreyStamina(lua_State* L) { int PlayerFunctions::luaPlayerAddPreyCards(lua_State* L) { // player:addPreyCards(amount) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { player->addPreyCards(getNumber(L, 2, 0)); pushBoolean(L, true); } else { @@ -397,7 +394,7 @@ int PlayerFunctions::luaPlayerAddPreyCards(lua_State* L) { int PlayerFunctions::luaPlayerGetPreyCards(lua_State* L) { // player:getPreyCards() - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { lua_pushnumber(L, static_cast(player->getPreyCards())); } else { lua_pushnil(L); @@ -407,7 +404,7 @@ int PlayerFunctions::luaPlayerGetPreyCards(lua_State* L) { int PlayerFunctions::luaPlayerGetPreyExperiencePercentage(lua_State* L) { // player:getPreyExperiencePercentage(raceId) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { if (const std::unique_ptr &slot = player->getPreyWithMonster(getNumber(L, 2, 0)); slot && slot->isOccupied() && slot->bonus == PreyBonus_Experience && slot->bonusTimeLeft > 0) { lua_pushnumber(L, static_cast(100 + slot->bonusPercentage)); @@ -422,7 +419,7 @@ int PlayerFunctions::luaPlayerGetPreyExperiencePercentage(lua_State* L) { int PlayerFunctions::luaPlayerRemoveTaskHuntingPoints(lua_State* L) { // player:removeTaskHuntingPoints(amount) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { pushBoolean(L, player->useTaskHuntingPoints(getNumber(L, 2, 0))); } else { lua_pushnil(L); @@ -432,7 +429,7 @@ int PlayerFunctions::luaPlayerRemoveTaskHuntingPoints(lua_State* L) { int PlayerFunctions::luaPlayerGetTaskHuntingPoints(lua_State* L) { // player:getTaskHuntingPoints() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -445,7 +442,7 @@ int PlayerFunctions::luaPlayerGetTaskHuntingPoints(lua_State* L) { int PlayerFunctions::luaPlayerAddTaskHuntingPoints(lua_State* L) { // player:addTaskHuntingPoints(amount) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { auto points = getNumber(L, 2); player->addTaskHuntingPoints(getNumber(L, 2)); lua_pushnumber(L, static_cast(points)); @@ -457,7 +454,7 @@ int PlayerFunctions::luaPlayerAddTaskHuntingPoints(lua_State* L) { int PlayerFunctions::luaPlayerGetPreyLootPercentage(lua_State* L) { // player:getPreyLootPercentage(raceid) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { if (const std::unique_ptr &slot = player->getPreyWithMonster(getNumber(L, 2, 0)); slot && slot->isOccupied() && slot->bonus == PreyBonus_Loot) { lua_pushnumber(L, slot->bonusPercentage); @@ -472,7 +469,7 @@ int PlayerFunctions::luaPlayerGetPreyLootPercentage(lua_State* L) { int PlayerFunctions::luaPlayerisMonsterPrey(lua_State* L) { // player:isMonsterPrey(raceid) - if (std::shared_ptr player = getUserdataShared(L, 1)) { + if (const auto &player = getUserdataShared(L, 1)) { if (const std::unique_ptr &slot = player->getPreyWithMonster(getNumber(L, 2, 0)); slot && slot->isOccupied()) { pushBoolean(L, true); @@ -487,7 +484,7 @@ int PlayerFunctions::luaPlayerisMonsterPrey(lua_State* L) { int PlayerFunctions::luaPlayerPreyThirdSlot(lua_State* L) { // get: player:preyThirdSlot() set: player:preyThirdSlot(bool) - if (std::shared_ptr player = getUserdataShared(L, 1); + if (const auto &player = getUserdataShared(L, 1); const auto &slot = player->getPreySlotById(PreySlot_Three)) { if (!slot) { lua_pushnil(L); @@ -514,7 +511,7 @@ int PlayerFunctions::luaPlayerPreyThirdSlot(lua_State* L) { int PlayerFunctions::luaPlayerTaskThirdSlot(lua_State* L) { // get: player:taskHuntingThirdSlot() set: player:taskHuntingThirdSlot(bool) - if (std::shared_ptr player = getUserdataShared(L, 1); + if (const auto &player = getUserdataShared(L, 1); const auto &slot = player->getTaskHuntingSlotById(PreySlot_Three)) { if (lua_gettop(L) == 1) { pushBoolean(L, slot->state != PreyTaskDataState_Locked); @@ -539,7 +536,7 @@ int PlayerFunctions::luaPlayerTaskThirdSlot(lua_State* L) { int PlayerFunctions::luaPlayercharmExpansion(lua_State* L) { // get: player:charmExpansion() set: player:charmExpansion(bool) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { if (lua_gettop(L) == 1) { pushBoolean(L, player->hasCharmExpansion()); @@ -555,7 +552,7 @@ int PlayerFunctions::luaPlayercharmExpansion(lua_State* L) { int PlayerFunctions::luaPlayerGetCapacity(lua_State* L) { // player:getCapacity() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getCapacity()); } else { @@ -566,7 +563,7 @@ int PlayerFunctions::luaPlayerGetCapacity(lua_State* L) { int PlayerFunctions::luaPlayerSetCapacity(lua_State* L) { // player:setCapacity(capacity) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->capacity = getNumber(L, 2); player->sendStats(); @@ -579,7 +576,7 @@ int PlayerFunctions::luaPlayerSetCapacity(lua_State* L) { int PlayerFunctions::luaPlayerSetTraining(lua_State* L) { // player:setTraining(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { bool value = getBoolean(L, 2, false); player->setTraining(value); @@ -592,7 +589,7 @@ int PlayerFunctions::luaPlayerSetTraining(lua_State* L) { int PlayerFunctions::luaPlayerGetIsTraining(lua_State* L) { // player:isTraining() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); @@ -605,7 +602,7 @@ int PlayerFunctions::luaPlayerGetIsTraining(lua_State* L) { int PlayerFunctions::luaPlayerGetFreeCapacity(lua_State* L) { // player:getFreeCapacity() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getFreeCapacity()); } else { @@ -616,7 +613,7 @@ int PlayerFunctions::luaPlayerGetFreeCapacity(lua_State* L) { int PlayerFunctions::luaPlayerGetKills(lua_State* L) { // player:getKills() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -640,7 +637,7 @@ int PlayerFunctions::luaPlayerGetKills(lua_State* L) { int PlayerFunctions::luaPlayerSetKills(lua_State* L) { // player:setKills(kills) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -668,7 +665,7 @@ int PlayerFunctions::luaPlayerSetKills(lua_State* L) { int PlayerFunctions::luaPlayerGetReward(lua_State* L) { // player:getReward(rewardId[, autoCreate = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -687,7 +684,7 @@ int PlayerFunctions::luaPlayerGetReward(lua_State* L) { int PlayerFunctions::luaPlayerRemoveReward(lua_State* L) { // player:removeReward(rewardId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -701,7 +698,7 @@ int PlayerFunctions::luaPlayerRemoveReward(lua_State* L) { int PlayerFunctions::luaPlayerGetRewardList(lua_State* L) { // player:getRewardList() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -721,7 +718,7 @@ int PlayerFunctions::luaPlayerGetRewardList(lua_State* L) { int PlayerFunctions::luaPlayerSetDailyReward(lua_State* L) { // player:setDailyReward(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setDailyReward(getNumber(L, 2)); pushBoolean(L, true); @@ -733,14 +730,14 @@ int PlayerFunctions::luaPlayerSetDailyReward(lua_State* L) { int PlayerFunctions::luaPlayerGetDepotLocker(lua_State* L) { // player:getDepotLocker(depotId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } uint32_t depotId = getNumber(L, 2); - std::shared_ptr depotLocker = player->getDepotLocker(depotId); + const auto &depotLocker = player->getDepotLocker(depotId); if (depotLocker) { depotLocker->setParent(player); pushUserdata(L, depotLocker); @@ -753,7 +750,7 @@ int PlayerFunctions::luaPlayerGetDepotLocker(lua_State* L) { int PlayerFunctions::luaPlayerGetStashCounter(lua_State* L) { // player:getStashCount() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t sizeStash = getStashSize(player->getStashItems()); lua_pushnumber(L, sizeStash); @@ -765,7 +762,7 @@ int PlayerFunctions::luaPlayerGetStashCounter(lua_State* L) { int PlayerFunctions::luaPlayerGetDepotChest(lua_State* L) { // player:getDepotChest(depotId[, autoCreate = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -773,7 +770,7 @@ int PlayerFunctions::luaPlayerGetDepotChest(lua_State* L) { uint32_t depotId = getNumber(L, 2); bool autoCreate = getBoolean(L, 3, false); - std::shared_ptr depotChest = player->getDepotChest(depotId, autoCreate); + const auto &depotChest = player->getDepotChest(depotId, autoCreate); if (depotChest) { player->setLastDepotId(depotId); pushUserdata(L, depotChest); @@ -786,13 +783,13 @@ int PlayerFunctions::luaPlayerGetDepotChest(lua_State* L) { int PlayerFunctions::luaPlayerGetInbox(lua_State* L) { // player:getInbox() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr inbox = player->getInbox(); + const auto &inbox = player->getInbox(); if (inbox) { pushUserdata(L, inbox); setItemMetatable(L, -1, inbox); @@ -804,7 +801,7 @@ int PlayerFunctions::luaPlayerGetInbox(lua_State* L) { int PlayerFunctions::luaPlayerGetSkullTime(lua_State* L) { // player:getSkullTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getSkullTicks()); } else { @@ -815,7 +812,7 @@ int PlayerFunctions::luaPlayerGetSkullTime(lua_State* L) { int PlayerFunctions::luaPlayerSetSkullTime(lua_State* L) { // player:setSkullTime(skullTime) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setSkullTicks(getNumber(L, 2)); pushBoolean(L, true); @@ -827,7 +824,7 @@ int PlayerFunctions::luaPlayerSetSkullTime(lua_State* L) { int PlayerFunctions::luaPlayerGetDeathPenalty(lua_State* L) { // player:getDeathPenalty() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, static_cast(player->getLostPercent() * 100)); } else { @@ -838,7 +835,7 @@ int PlayerFunctions::luaPlayerGetDeathPenalty(lua_State* L) { int PlayerFunctions::luaPlayerGetExperience(lua_State* L) { // player:getExperience() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getExperience()); } else { @@ -849,7 +846,7 @@ int PlayerFunctions::luaPlayerGetExperience(lua_State* L) { int PlayerFunctions::luaPlayerAddExperience(lua_State* L) { // player:addExperience(experience[, sendText = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int64_t experience = getNumber(L, 2); bool sendText = getBoolean(L, 3, false); @@ -863,7 +860,7 @@ int PlayerFunctions::luaPlayerAddExperience(lua_State* L) { int PlayerFunctions::luaPlayerRemoveExperience(lua_State* L) { // player:removeExperience(experience[, sendText = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int64_t experience = getNumber(L, 2); bool sendText = getBoolean(L, 3, false); @@ -877,7 +874,7 @@ int PlayerFunctions::luaPlayerRemoveExperience(lua_State* L) { int PlayerFunctions::luaPlayerGetLevel(lua_State* L) { // player:getLevel() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getLevel()); } else { @@ -888,7 +885,7 @@ int PlayerFunctions::luaPlayerGetLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetMagicShieldCapacityFlat(lua_State* L) { // player:getMagicShieldCapacityFlat(useCharges) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMagicShieldCapacityFlat(getBoolean(L, 2, false))); } else { @@ -899,7 +896,7 @@ int PlayerFunctions::luaPlayerGetMagicShieldCapacityFlat(lua_State* L) { int PlayerFunctions::luaPlayerGetMagicShieldCapacityPercent(lua_State* L) { // player:getMagicShieldCapacityPercent(useCharges) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMagicShieldCapacityPercent(getBoolean(L, 2, false))); } else { @@ -910,7 +907,7 @@ int PlayerFunctions::luaPlayerGetMagicShieldCapacityPercent(lua_State* L) { int PlayerFunctions::luaPlayerSendSpellCooldown(lua_State* L) { // player:sendSpellCooldown(spellId, time) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -926,7 +923,7 @@ int PlayerFunctions::luaPlayerSendSpellCooldown(lua_State* L) { int PlayerFunctions::luaPlayerSendSpellGroupCooldown(lua_State* L) { // player:sendSpellGroupCooldown(groupId, time) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -942,7 +939,7 @@ int PlayerFunctions::luaPlayerSendSpellGroupCooldown(lua_State* L) { int PlayerFunctions::luaPlayerGetMagicLevel(lua_State* L) { // player:getMagicLevel() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMagicLevel()); } else { @@ -953,7 +950,7 @@ int PlayerFunctions::luaPlayerGetMagicLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetBaseMagicLevel(lua_State* L) { // player:getBaseMagicLevel() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getBaseMagicLevel()); } else { @@ -964,7 +961,7 @@ int PlayerFunctions::luaPlayerGetBaseMagicLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetMana(lua_State* L) { // player:getMana() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMana()); } else { @@ -975,7 +972,7 @@ int PlayerFunctions::luaPlayerGetMana(lua_State* L) { int PlayerFunctions::luaPlayerAddMana(lua_State* L) { // player:addMana(manaChange[, animationOnLoss = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -997,7 +994,7 @@ int PlayerFunctions::luaPlayerAddMana(lua_State* L) { int PlayerFunctions::luaPlayerGetMaxMana(lua_State* L) { // player:getMaxMana() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMaxMana()); } else { @@ -1024,7 +1021,7 @@ int PlayerFunctions::luaPlayerSetMaxMana(lua_State* L) { int PlayerFunctions::luaPlayerGetManaSpent(lua_State* L) { // player:getManaSpent() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getSpentMana()); } else { @@ -1035,7 +1032,7 @@ int PlayerFunctions::luaPlayerGetManaSpent(lua_State* L) { int PlayerFunctions::luaPlayerAddManaSpent(lua_State* L) { // player:addManaSpent(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->addManaSpent(getNumber(L, 2)); pushBoolean(L, true); @@ -1047,7 +1044,7 @@ int PlayerFunctions::luaPlayerAddManaSpent(lua_State* L) { int PlayerFunctions::luaPlayerGetBaseMaxHealth(lua_State* L) { // player:getBaseMaxHealth() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->healthMax); } else { @@ -1058,7 +1055,7 @@ int PlayerFunctions::luaPlayerGetBaseMaxHealth(lua_State* L) { int PlayerFunctions::luaPlayerGetBaseMaxMana(lua_State* L) { // player:getBaseMaxMana() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->manaMax); } else { @@ -1070,7 +1067,7 @@ int PlayerFunctions::luaPlayerGetBaseMaxMana(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillLevel(lua_State* L) { // player:getSkillLevel(skillType) skills_t skillType = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].level); } else { @@ -1082,7 +1079,7 @@ int PlayerFunctions::luaPlayerGetSkillLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetEffectiveSkillLevel(lua_State* L) { // player:getEffectiveSkillLevel(skillType) skills_t skillType = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->getSkillLevel(skillType)); } else { @@ -1094,7 +1091,7 @@ int PlayerFunctions::luaPlayerGetEffectiveSkillLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillPercent(lua_State* L) { // player:getSkillPercent(skillType) skills_t skillType = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].percent); } else { @@ -1106,7 +1103,7 @@ int PlayerFunctions::luaPlayerGetSkillPercent(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillTries(lua_State* L) { // player:getSkillTries(skillType) skills_t skillType = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].tries); } else { @@ -1117,7 +1114,7 @@ int PlayerFunctions::luaPlayerGetSkillTries(lua_State* L) { int PlayerFunctions::luaPlayerAddSkillTries(lua_State* L) { // player:addSkillTries(skillType, tries) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { skills_t skillType = getNumber(L, 2); uint64_t tries = getNumber(L, 3); @@ -1131,7 +1128,7 @@ int PlayerFunctions::luaPlayerAddSkillTries(lua_State* L) { int PlayerFunctions::luaPlayerSetLevel(lua_State* L) { // player:setLevel(level) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t level = getNumber(L, 2); player->level = level; @@ -1147,7 +1144,7 @@ int PlayerFunctions::luaPlayerSetLevel(lua_State* L) { int PlayerFunctions::luaPlayerSetMagicLevel(lua_State* L) { // player:setMagicLevel(level[, manaSpent]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t level = getNumber(L, 2); player->magLevel = level; @@ -1171,7 +1168,7 @@ int PlayerFunctions::luaPlayerSetMagicLevel(lua_State* L) { int PlayerFunctions::luaPlayerSetSkillLevel(lua_State* L) { // player:setSkillLevel(skillType, level[, tries]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { skills_t skillType = getNumber(L, 2); uint16_t level = getNumber(L, 3); @@ -1196,7 +1193,7 @@ int PlayerFunctions::luaPlayerSetSkillLevel(lua_State* L) { int PlayerFunctions::luaPlayerAddOfflineTrainingTime(lua_State* L) { // player:addOfflineTrainingTime(time) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int32_t time = getNumber(L, 2); player->addOfflineTrainingTime(time); @@ -1210,7 +1207,7 @@ int PlayerFunctions::luaPlayerAddOfflineTrainingTime(lua_State* L) { int PlayerFunctions::luaPlayerGetOfflineTrainingTime(lua_State* L) { // player:getOfflineTrainingTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getOfflineTrainingTime()); } else { @@ -1221,7 +1218,7 @@ int PlayerFunctions::luaPlayerGetOfflineTrainingTime(lua_State* L) { int PlayerFunctions::luaPlayerRemoveOfflineTrainingTime(lua_State* L) { // player:removeOfflineTrainingTime(time) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int32_t time = getNumber(L, 2); player->removeOfflineTrainingTime(time); @@ -1235,7 +1232,7 @@ int PlayerFunctions::luaPlayerRemoveOfflineTrainingTime(lua_State* L) { int PlayerFunctions::luaPlayerAddOfflineTrainingTries(lua_State* L) { // player:addOfflineTrainingTries(skillType, tries) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { skills_t skillType = getNumber(L, 2); uint64_t tries = getNumber(L, 3); @@ -1248,7 +1245,7 @@ int PlayerFunctions::luaPlayerAddOfflineTrainingTries(lua_State* L) { int PlayerFunctions::luaPlayerGetOfflineTrainingSkill(lua_State* L) { // player:getOfflineTrainingSkill() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getOfflineTrainingSkill()); } else { @@ -1259,7 +1256,7 @@ int PlayerFunctions::luaPlayerGetOfflineTrainingSkill(lua_State* L) { int PlayerFunctions::luaPlayerSetOfflineTrainingSkill(lua_State* L) { // player:setOfflineTrainingSkill(skillId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { int8_t skillId = getNumber(L, 2); player->setOfflineTrainingSkill(skillId); @@ -1272,7 +1269,7 @@ int PlayerFunctions::luaPlayerSetOfflineTrainingSkill(lua_State* L) { int PlayerFunctions::luaPlayerOpenStash(lua_State* L) { // player:openStash(isNpc) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); bool isNpc = getBoolean(L, 2, false); if (player) { player->sendOpenStash(isNpc); @@ -1286,7 +1283,7 @@ int PlayerFunctions::luaPlayerOpenStash(lua_State* L) { int PlayerFunctions::luaPlayerGetItemCount(lua_State* L) { // player:getItemCount(itemId[, subType = -1]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1310,7 +1307,7 @@ int PlayerFunctions::luaPlayerGetItemCount(lua_State* L) { int PlayerFunctions::luaPlayerGetStashItemCount(lua_State* L) { // player:getStashItemCount(itemId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1339,7 +1336,7 @@ int PlayerFunctions::luaPlayerGetStashItemCount(lua_State* L) { int PlayerFunctions::luaPlayerGetItemById(lua_State* L) { // player:getItemById(itemId, deepSearch[, subType = -1]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1358,7 +1355,7 @@ int PlayerFunctions::luaPlayerGetItemById(lua_State* L) { bool deepSearch = getBoolean(L, 3); int32_t subType = getNumber(L, 4, -1); - std::shared_ptr item = g_game().findItemOfType(player, itemId, deepSearch, subType); + const auto &item = g_game().findItemOfType(player, itemId, deepSearch, subType); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -1370,7 +1367,7 @@ int PlayerFunctions::luaPlayerGetItemById(lua_State* L) { int PlayerFunctions::luaPlayerGetVocation(lua_State* L) { // player:getVocation() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushUserdata(L, player->getVocation()); setMetatable(L, -1, "Vocation"); @@ -1382,7 +1379,7 @@ int PlayerFunctions::luaPlayerGetVocation(lua_State* L) { int PlayerFunctions::luaPlayerSetVocation(lua_State* L) { // player:setVocation(id or name or userdata) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1416,7 +1413,7 @@ int PlayerFunctions::luaPlayerSetVocation(lua_State* L) { int PlayerFunctions::luaPlayerIsPromoted(lua_State* L) { // player:isPromoted() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->isPromoted()); } else { @@ -1427,7 +1424,7 @@ int PlayerFunctions::luaPlayerIsPromoted(lua_State* L) { int PlayerFunctions::luaPlayerGetSex(lua_State* L) { // player:getSex() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getSex()); } else { @@ -1438,7 +1435,7 @@ int PlayerFunctions::luaPlayerGetSex(lua_State* L) { int PlayerFunctions::luaPlayerSetSex(lua_State* L) { // player:setSex(newSex) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { PlayerSex_t newSex = getNumber(L, 2); player->setSex(newSex); @@ -1451,7 +1448,7 @@ int PlayerFunctions::luaPlayerSetSex(lua_State* L) { int PlayerFunctions::luaPlayerGetPronoun(lua_State* L) { // player:getPronoun() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getPronoun()); } else { @@ -1462,7 +1459,7 @@ int PlayerFunctions::luaPlayerGetPronoun(lua_State* L) { int PlayerFunctions::luaPlayerSetPronoun(lua_State* L) { // player:setPronoun(newPronoun) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { PlayerPronoun_t newPronoun = getNumber(L, 2); player->setPronoun(newPronoun); @@ -1475,7 +1472,7 @@ int PlayerFunctions::luaPlayerSetPronoun(lua_State* L) { int PlayerFunctions::luaPlayerGetTown(lua_State* L) { // player:getTown() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushUserdata(L, player->getTown()); setMetatable(L, -1, "Town"); @@ -1493,7 +1490,7 @@ int PlayerFunctions::luaPlayerSetTown(lua_State* L) { return 1; } - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setTown(town); pushBoolean(L, true); @@ -1505,7 +1502,7 @@ int PlayerFunctions::luaPlayerSetTown(lua_State* L) { int PlayerFunctions::luaPlayerGetGuild(lua_State* L) { // player:getGuild() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1524,7 +1521,7 @@ int PlayerFunctions::luaPlayerGetGuild(lua_State* L) { int PlayerFunctions::luaPlayerSetGuild(lua_State* L) { // player:setGuild(guild) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1539,7 +1536,7 @@ int PlayerFunctions::luaPlayerSetGuild(lua_State* L) { int PlayerFunctions::luaPlayerGetGuildLevel(lua_State* L) { // player:getGuildLevel() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && player->getGuild()) { lua_pushnumber(L, player->getGuildRank()->level); } else { @@ -1551,7 +1548,7 @@ int PlayerFunctions::luaPlayerGetGuildLevel(lua_State* L) { int PlayerFunctions::luaPlayerSetGuildLevel(lua_State* L) { // player:setGuildLevel(level) uint8_t level = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getGuild()) { lua_pushnil(L); return 1; @@ -1570,7 +1567,7 @@ int PlayerFunctions::luaPlayerSetGuildLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetGuildNick(lua_State* L) { // player:getGuildNick() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushString(L, player->getGuildNick()); } else { @@ -1582,7 +1579,7 @@ int PlayerFunctions::luaPlayerGetGuildNick(lua_State* L) { int PlayerFunctions::luaPlayerSetGuildNick(lua_State* L) { // player:setGuildNick(nick) const std::string &nick = getString(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setGuildNick(nick); pushBoolean(L, true); @@ -1594,7 +1591,7 @@ int PlayerFunctions::luaPlayerSetGuildNick(lua_State* L) { int PlayerFunctions::luaPlayerGetGroup(lua_State* L) { // player:getGroup() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushUserdata(L, player->getGroup()); setMetatable(L, -1, "Group"); @@ -1606,13 +1603,13 @@ int PlayerFunctions::luaPlayerGetGroup(lua_State* L) { int PlayerFunctions::luaPlayerSetGroup(lua_State* L) { // player:setGroup(group) - std::shared_ptr group = getUserdataShared(L, 2); + const auto &group = getUserdataShared(L, 2); if (!group) { pushBoolean(L, false); return 1; } - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setGroup(group); pushBoolean(L, true); @@ -1627,7 +1624,7 @@ int PlayerFunctions::luaPlayerSetSpecialContainersAvailable(lua_State* L) { bool supplyStashMenu = getBoolean(L, 2, false); bool marketMenu = getBoolean(L, 3, false); bool depotSearchMenu = getBoolean(L, 4, false); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setSpecialMenuAvailable(supplyStashMenu, marketMenu, depotSearchMenu); pushBoolean(L, true); @@ -1639,7 +1636,7 @@ int PlayerFunctions::luaPlayerSetSpecialContainersAvailable(lua_State* L) { int PlayerFunctions::luaPlayerGetStamina(lua_State* L) { // player:getStamina() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getStaminaMinutes()); } else { @@ -1651,7 +1648,7 @@ int PlayerFunctions::luaPlayerGetStamina(lua_State* L) { int PlayerFunctions::luaPlayerSetStamina(lua_State* L) { // player:setStamina(stamina) uint16_t stamina = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->staminaMinutes = std::min(2520, stamina); player->sendStats(); @@ -1663,7 +1660,7 @@ int PlayerFunctions::luaPlayerSetStamina(lua_State* L) { int PlayerFunctions::luaPlayerGetSoul(lua_State* L) { // player:getSoul() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getSoul()); } else { @@ -1675,7 +1672,7 @@ int PlayerFunctions::luaPlayerGetSoul(lua_State* L) { int PlayerFunctions::luaPlayerAddSoul(lua_State* L) { // player:addSoul(soulChange) int32_t soulChange = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->changeSoul(soulChange); pushBoolean(L, true); @@ -1687,7 +1684,7 @@ int PlayerFunctions::luaPlayerAddSoul(lua_State* L) { int PlayerFunctions::luaPlayerGetMaxSoul(lua_State* L) { // player:getMaxSoul() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && player->vocation) { lua_pushnumber(L, player->vocation->getSoulMax()); } else { @@ -1698,7 +1695,7 @@ int PlayerFunctions::luaPlayerGetMaxSoul(lua_State* L) { int PlayerFunctions::luaPlayerGetBankBalance(lua_State* L) { // player:getBankBalance() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getBankBalance()); } else { @@ -1709,7 +1706,7 @@ int PlayerFunctions::luaPlayerGetBankBalance(lua_State* L) { int PlayerFunctions::luaPlayerSetBankBalance(lua_State* L) { // player:setBankBalance(bankBalance) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1737,7 +1734,7 @@ int PlayerFunctions::luaPlayerSetStorageValue(lua_State* L) { // player:setStorageValue(key, value) int32_t value = getNumber(L, 3); uint32_t key = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) { std::ostringstream ss; ss << "Accessing reserved range: " << key; @@ -1762,7 +1759,7 @@ int PlayerFunctions::luaPlayerSetStorageValue(lua_State* L) { int PlayerFunctions::luaPlayerGetStorageValueByName(lua_State* L) { // player:getStorageValueByName(name) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -1777,7 +1774,7 @@ int PlayerFunctions::luaPlayerGetStorageValueByName(lua_State* L) { int PlayerFunctions::luaPlayerSetStorageValueByName(lua_State* L) { // player:setStorageValueByName(storageName, value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -1795,7 +1792,7 @@ int PlayerFunctions::luaPlayerSetStorageValueByName(lua_State* L) { int PlayerFunctions::luaPlayerAddItem(lua_State* L) { // player:addItem(itemId, count = 1, canDropOnMap = true, subType = 1, slot = CONST_SLOT_WHEREEVER, tier = 0) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { pushBoolean(L, false); return 1; @@ -1849,7 +1846,7 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { subType -= stackCount; } - std::shared_ptr item = Item::CreateItem(itemId, stackCount); + const auto &item = Item::CreateItem(itemId, stackCount); if (!item) { if (!hasTable) { lua_pushnil(L); @@ -1885,14 +1882,14 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { int PlayerFunctions::luaPlayerAddItemEx(lua_State* L) { // player:addItemEx(item[, canDropOnMap = false[, index = INDEX_WHEREEVER[, flags = 0]]]) // player:addItemEx(item[, canDropOnMap = true[, slot = CONST_SLOT_WHEREEVER]]) - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1924,7 +1921,7 @@ int PlayerFunctions::luaPlayerAddItemEx(lua_State* L) { int PlayerFunctions::luaPlayerAddItemStash(lua_State* L) { // player:addItemStash(itemId, count = 1) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1940,7 +1937,7 @@ int PlayerFunctions::luaPlayerAddItemStash(lua_State* L) { int PlayerFunctions::luaPlayerRemoveStashItem(lua_State* L) { // player:removeStashItem(itemId, count) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1970,7 +1967,7 @@ int PlayerFunctions::luaPlayerRemoveStashItem(lua_State* L) { int PlayerFunctions::luaPlayerRemoveItem(lua_State* L) { // player:removeItem(itemId, count[, subType = -1[, ignoreEquipped = false]]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -1996,13 +1993,13 @@ int PlayerFunctions::luaPlayerRemoveItem(lua_State* L) { int PlayerFunctions::luaPlayerSendContainer(lua_State* L) { // player:sendContainer(container) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr container = getUserdataShared(L, 2); + const auto &container = getUserdataShared(L, 2); if (!container) { lua_pushnil(L); return 1; @@ -2015,7 +2012,7 @@ int PlayerFunctions::luaPlayerSendContainer(lua_State* L) { int PlayerFunctions::luaPlayerSendUpdateContainer(lua_State* L) { // player:sendUpdateContainer(container) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2034,7 +2031,7 @@ int PlayerFunctions::luaPlayerSendUpdateContainer(lua_State* L) { int PlayerFunctions::luaPlayerGetMoney(lua_State* L) { // player:getMoney() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getMoney()); } else { @@ -2046,7 +2043,7 @@ int PlayerFunctions::luaPlayerGetMoney(lua_State* L) { int PlayerFunctions::luaPlayerAddMoney(lua_State* L) { // player:addMoney(money) uint64_t money = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { g_game().addMoney(player, money); pushBoolean(L, true); @@ -2058,7 +2055,7 @@ int PlayerFunctions::luaPlayerAddMoney(lua_State* L) { int PlayerFunctions::luaPlayerRemoveMoney(lua_State* L) { // player:removeMoney(money[, flags = 0[, useBank = true]]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint64_t money = getNumber(L, 2); int32_t flags = getNumber(L, 3, 0); @@ -2072,7 +2069,7 @@ int PlayerFunctions::luaPlayerRemoveMoney(lua_State* L) { int PlayerFunctions::luaPlayerShowTextDialog(lua_State* L) { // player:showTextDialog(id or name or userdata[, text[, canWrite[, length]]]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2129,7 +2126,7 @@ int PlayerFunctions::luaPlayerSendTextMessage(lua_State* L) { // player:sendTextMessage(type, text[, position, primaryValue = 0, primaryColor = TEXTCOLOR_NONE[, secondaryValue = 0, secondaryColor = TEXTCOLOR_NONE]]) // player:sendTextMessage(type, text, channelId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2167,7 +2164,7 @@ int PlayerFunctions::luaPlayerSendTextMessage(lua_State* L) { int PlayerFunctions::luaPlayerSendChannelMessage(lua_State* L) { // player:sendChannelMessage(author, text, type, channelId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2184,13 +2181,13 @@ int PlayerFunctions::luaPlayerSendChannelMessage(lua_State* L) { int PlayerFunctions::luaPlayerSendPrivateMessage(lua_State* L) { // player:sendPrivateMessage(speaker, text[, type]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr speaker = getUserdataShared(L, 2); + const auto &speaker = getUserdataShared(L, 2); const std::string &text = getString(L, 3); SpeakClasses type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); player->sendPrivateMessage(speaker, type, text); @@ -2200,13 +2197,13 @@ int PlayerFunctions::luaPlayerSendPrivateMessage(lua_State* L) { int PlayerFunctions::luaPlayerChannelSay(lua_State* L) { // player:channelSay(speaker, type, text, channelId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr speaker = getCreature(L, 2); + const auto &speaker = getCreature(L, 2); SpeakClasses type = getNumber(L, 3); const std::string &text = getString(L, 4); uint16_t channelId = getNumber(L, 5); @@ -2218,7 +2215,7 @@ int PlayerFunctions::luaPlayerChannelSay(lua_State* L) { int PlayerFunctions::luaPlayerOpenChannel(lua_State* L) { // player:openChannel(channelId) uint16_t channelId = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { g_game().playerOpenChannel(player->getID(), channelId); pushBoolean(L, true); @@ -2230,20 +2227,20 @@ int PlayerFunctions::luaPlayerOpenChannel(lua_State* L) { int PlayerFunctions::luaPlayerGetSlotItem(lua_State* L) { // player:getSlotItem(slot) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } uint32_t slot = getNumber(L, 2); - std::shared_ptr thing = player->getThing(slot); + const auto &thing = player->getThing(slot); if (!thing) { lua_pushnil(L); return 1; } - std::shared_ptr item = thing->getItem(); + const auto &item = thing->getItem(); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -2255,13 +2252,13 @@ int PlayerFunctions::luaPlayerGetSlotItem(lua_State* L) { int PlayerFunctions::luaPlayerGetParty(lua_State* L) { // player:getParty() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr party = player->getParty(); + const auto &party = player->getParty(); if (party) { pushUserdata(L, party); setMetatable(L, -1, "Party"); @@ -2273,7 +2270,7 @@ int PlayerFunctions::luaPlayerGetParty(lua_State* L) { int PlayerFunctions::luaPlayerAddOutfit(lua_State* L) { // player:addOutfit(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->addOutfit(getNumber(L, 2), 0); pushBoolean(L, true); @@ -2285,7 +2282,7 @@ int PlayerFunctions::luaPlayerAddOutfit(lua_State* L) { int PlayerFunctions::luaPlayerAddOutfitAddon(lua_State* L) { // player:addOutfitAddon(lookType, addon) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); uint8_t addon = getNumber(L, 3); @@ -2299,7 +2296,7 @@ int PlayerFunctions::luaPlayerAddOutfitAddon(lua_State* L) { int PlayerFunctions::luaPlayerRemoveOutfit(lua_State* L) { // player:removeOutfit(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); pushBoolean(L, player->removeOutfit(lookType)); @@ -2311,7 +2308,7 @@ int PlayerFunctions::luaPlayerRemoveOutfit(lua_State* L) { int PlayerFunctions::luaPlayerRemoveOutfitAddon(lua_State* L) { // player:removeOutfitAddon(lookType, addon) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); uint8_t addon = getNumber(L, 3); @@ -2324,7 +2321,7 @@ int PlayerFunctions::luaPlayerRemoveOutfitAddon(lua_State* L) { int PlayerFunctions::luaPlayerHasOutfit(lua_State* L) { // player:hasOutfit(lookType[, addon = 0]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); uint8_t addon = getNumber(L, 3, 0); @@ -2337,7 +2334,7 @@ int PlayerFunctions::luaPlayerHasOutfit(lua_State* L) { int PlayerFunctions::luaPlayerSendOutfitWindow(lua_State* L) { // player:sendOutfitWindow() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->sendOutfitWindow(); pushBoolean(L, true); @@ -2349,7 +2346,7 @@ int PlayerFunctions::luaPlayerSendOutfitWindow(lua_State* L) { int PlayerFunctions::luaPlayerAddMount(lua_State* L) { // player:addMount(mountId or mountName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2359,7 +2356,7 @@ int PlayerFunctions::luaPlayerAddMount(lua_State* L) { if (isNumber(L, 2)) { mountId = getNumber(L, 2); } else { - const std::shared_ptr mount = g_game().mounts.getMountByName(getString(L, 2)); + const auto &mount = g_game().mounts.getMountByName(getString(L, 2)); if (!mount) { lua_pushnil(L); return 1; @@ -2372,7 +2369,7 @@ int PlayerFunctions::luaPlayerAddMount(lua_State* L) { int PlayerFunctions::luaPlayerRemoveMount(lua_State* L) { // player:removeMount(mountId or mountName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2382,7 +2379,7 @@ int PlayerFunctions::luaPlayerRemoveMount(lua_State* L) { if (isNumber(L, 2)) { mountId = getNumber(L, 2); } else { - const std::shared_ptr mount = g_game().mounts.getMountByName(getString(L, 2)); + const auto &mount = g_game().mounts.getMountByName(getString(L, 2)); if (!mount) { lua_pushnil(L); return 1; @@ -2395,7 +2392,7 @@ int PlayerFunctions::luaPlayerRemoveMount(lua_State* L) { int PlayerFunctions::luaPlayerHasMount(lua_State* L) { // player:hasMount(mountId or mountName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2418,7 +2415,7 @@ int PlayerFunctions::luaPlayerHasMount(lua_State* L) { int PlayerFunctions::luaPlayerAddFamiliar(lua_State* L) { // player:addFamiliar(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->addFamiliar(getNumber(L, 2)); pushBoolean(L, true); @@ -2430,7 +2427,7 @@ int PlayerFunctions::luaPlayerAddFamiliar(lua_State* L) { int PlayerFunctions::luaPlayerRemoveFamiliar(lua_State* L) { // player:removeFamiliar(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); pushBoolean(L, player->removeFamiliar(lookType)); @@ -2442,7 +2439,7 @@ int PlayerFunctions::luaPlayerRemoveFamiliar(lua_State* L) { int PlayerFunctions::luaPlayerHasFamiliar(lua_State* L) { // player:hasFamiliar(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); pushBoolean(L, player->canFamiliar(lookType)); @@ -2454,7 +2451,7 @@ int PlayerFunctions::luaPlayerHasFamiliar(lua_State* L) { int PlayerFunctions::luaPlayerSetFamiliarLooktype(lua_State* L) { // player:setFamiliarLooktype(lookType) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setFamiliarLooktype(getNumber(L, 2)); pushBoolean(L, true); @@ -2466,7 +2463,7 @@ int PlayerFunctions::luaPlayerSetFamiliarLooktype(lua_State* L) { int PlayerFunctions::luaPlayerGetFamiliarLooktype(lua_State* L) { // player:getFamiliarLooktype() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->defaultOutfit.lookFamiliarsType); } else { @@ -2477,7 +2474,7 @@ int PlayerFunctions::luaPlayerGetFamiliarLooktype(lua_State* L) { int PlayerFunctions::luaPlayerGetPremiumDays(lua_State* L) { // player:getPremiumDays() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player && player->getAccount()) { lua_pushnumber(L, player->getAccount()->getPremiumRemainingDays()); } else { @@ -2488,7 +2485,7 @@ int PlayerFunctions::luaPlayerGetPremiumDays(lua_State* L) { int PlayerFunctions::luaPlayerAddPremiumDays(lua_State* L) { // player:addPremiumDays(days) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { lua_pushnil(L); return 1; @@ -2517,7 +2514,7 @@ int PlayerFunctions::luaPlayerAddPremiumDays(lua_State* L) { int PlayerFunctions::luaPlayerRemovePremiumDays(lua_State* L) { // player:removePremiumDays(days) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { lua_pushnil(L); return 1; @@ -2546,7 +2543,7 @@ int PlayerFunctions::luaPlayerRemovePremiumDays(lua_State* L) { int PlayerFunctions::luaPlayerGetTibiaCoins(lua_State* L) { // player:getTibiaCoins() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2564,7 +2561,7 @@ int PlayerFunctions::luaPlayerGetTibiaCoins(lua_State* L) { int PlayerFunctions::luaPlayerAddTibiaCoins(lua_State* L) { // player:addTibiaCoins(coins) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2590,7 +2587,7 @@ int PlayerFunctions::luaPlayerAddTibiaCoins(lua_State* L) { int PlayerFunctions::luaPlayerRemoveTibiaCoins(lua_State* L) { // player:removeTibiaCoins(coins) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2615,7 +2612,7 @@ int PlayerFunctions::luaPlayerRemoveTibiaCoins(lua_State* L) { int PlayerFunctions::luaPlayerGetTransferableCoins(lua_State* L) { // player:getTransferableCoins() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2633,7 +2630,7 @@ int PlayerFunctions::luaPlayerGetTransferableCoins(lua_State* L) { int PlayerFunctions::luaPlayerAddTransferableCoins(lua_State* L) { // player:addTransferableCoins(coins) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2659,7 +2656,7 @@ int PlayerFunctions::luaPlayerAddTransferableCoins(lua_State* L) { int PlayerFunctions::luaPlayerRemoveTransferableCoins(lua_State* L) { // player:removeTransferableCoins(coins) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player || !player->getAccount()) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -2686,7 +2683,7 @@ int PlayerFunctions::luaPlayerRemoveTransferableCoins(lua_State* L) { int PlayerFunctions::luaPlayerHasBlessing(lua_State* L) { // player:hasBlessing(blessing) uint8_t blessing = getNumber(L, 2); - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->hasBlessing(blessing)); } else { @@ -2697,7 +2694,7 @@ int PlayerFunctions::luaPlayerHasBlessing(lua_State* L) { int PlayerFunctions::luaPlayerAddBlessing(lua_State* L) { // player:addBlessing(blessing) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2714,7 +2711,7 @@ int PlayerFunctions::luaPlayerAddBlessing(lua_State* L) { int PlayerFunctions::luaPlayerRemoveBlessing(lua_State* L) { // player:removeBlessing(blessing) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2735,7 +2732,7 @@ int PlayerFunctions::luaPlayerRemoveBlessing(lua_State* L) { int PlayerFunctions::luaPlayerGetBlessingCount(lua_State* L) { // player:getBlessingCount(index[, storeCount = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); uint8_t index = getNumber(L, 2); if (index == 0) { index = 1; @@ -2751,7 +2748,7 @@ int PlayerFunctions::luaPlayerGetBlessingCount(lua_State* L) { int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { // player:canLearnSpell(spellName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2785,7 +2782,7 @@ int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { int PlayerFunctions::luaPlayerLearnSpell(lua_State* L) { // player:learnSpell(spellName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const std::string &spellName = getString(L, 2); player->learnInstantSpell(spellName); @@ -2798,7 +2795,7 @@ int PlayerFunctions::luaPlayerLearnSpell(lua_State* L) { int PlayerFunctions::luaPlayerForgetSpell(lua_State* L) { // player:forgetSpell(spellName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const std::string &spellName = getString(L, 2); player->forgetInstantSpell(spellName); @@ -2811,7 +2808,7 @@ int PlayerFunctions::luaPlayerForgetSpell(lua_State* L) { int PlayerFunctions::luaPlayerHasLearnedSpell(lua_State* L) { // player:hasLearnedSpell(spellName) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const std::string &spellName = getString(L, 2); pushBoolean(L, player->hasLearnedInstantSpell(spellName)); @@ -2823,7 +2820,7 @@ int PlayerFunctions::luaPlayerHasLearnedSpell(lua_State* L) { int PlayerFunctions::luaPlayerSendTutorial(lua_State* L) { // player:sendTutorial(tutorialId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint8_t tutorialId = getNumber(L, 2); player->sendTutorial(tutorialId); @@ -2836,14 +2833,14 @@ int PlayerFunctions::luaPlayerSendTutorial(lua_State* L) { int PlayerFunctions::luaPlayerOpenImbuementWindow(lua_State* L) { // player:openImbuementWindow(item) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -2856,7 +2853,7 @@ int PlayerFunctions::luaPlayerOpenImbuementWindow(lua_State* L) { int PlayerFunctions::luaPlayerCloseImbuementWindow(lua_State* L) { // player:closeImbuementWindow() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -2869,7 +2866,7 @@ int PlayerFunctions::luaPlayerCloseImbuementWindow(lua_State* L) { int PlayerFunctions::luaPlayerAddMapMark(lua_State* L) { // player:addMapMark(position, type, description) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const Position &position = getPosition(L, 2); uint8_t type = getNumber(L, 3); @@ -2884,7 +2881,7 @@ int PlayerFunctions::luaPlayerAddMapMark(lua_State* L) { int PlayerFunctions::luaPlayerSave(lua_State* L) { // player:save() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { if (!player->isOffline()) { player->loginPosition = player->getPosition(); @@ -2898,7 +2895,7 @@ int PlayerFunctions::luaPlayerSave(lua_State* L) { int PlayerFunctions::luaPlayerPopupFYI(lua_State* L) { // player:popupFYI(message) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { const std::string &message = getString(L, 2); player->sendFYIBox(message); @@ -2911,7 +2908,7 @@ int PlayerFunctions::luaPlayerPopupFYI(lua_State* L) { int PlayerFunctions::luaPlayerIsPzLocked(lua_State* L) { // player:isPzLocked() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->isPzLocked()); } else { @@ -2922,7 +2919,7 @@ int PlayerFunctions::luaPlayerIsPzLocked(lua_State* L) { int PlayerFunctions::luaPlayerGetClient(lua_State* L) { // player:getClient() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_createtable(L, 0, 2); setField(L, "version", player->getProtocolVersion()); @@ -2935,7 +2932,7 @@ int PlayerFunctions::luaPlayerGetClient(lua_State* L) { int PlayerFunctions::luaPlayerGetHouse(lua_State* L) { // player:getHouse() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2953,7 +2950,7 @@ int PlayerFunctions::luaPlayerGetHouse(lua_State* L) { int PlayerFunctions::luaPlayerSendHouseWindow(lua_State* L) { // player:sendHouseWindow(house, listId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2973,7 +2970,7 @@ int PlayerFunctions::luaPlayerSendHouseWindow(lua_State* L) { int PlayerFunctions::luaPlayerSetEditHouse(lua_State* L) { // player:setEditHouse(house, listId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -2993,7 +2990,7 @@ int PlayerFunctions::luaPlayerSetEditHouse(lua_State* L) { int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { // player:setGhostMode(enabled) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3007,7 +3004,7 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { player->switchGhostMode(); - std::shared_ptr tile = player->getTile(); + const auto &tile = player->getTile(); const Position &position = player->getPosition(); for (const auto &spectator : Spectators().find(position, true)) { @@ -3044,13 +3041,13 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { int PlayerFunctions::luaPlayerGetContainerId(lua_State* L) { // player:getContainerId(container) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr container = getUserdataShared(L, 2); + const auto &container = getUserdataShared(L, 2); if (container) { lua_pushnumber(L, player->getContainerID(container)); } else { @@ -3061,13 +3058,13 @@ int PlayerFunctions::luaPlayerGetContainerId(lua_State* L) { int PlayerFunctions::luaPlayerGetContainerById(lua_State* L) { // player:getContainerById(id) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } - std::shared_ptr container = player->getContainerByID(getNumber(L, 2)); + const auto &container = player->getContainerByID(getNumber(L, 2)); if (container) { pushUserdata(L, container); setMetatable(L, -1, "Container"); @@ -3079,7 +3076,7 @@ int PlayerFunctions::luaPlayerGetContainerById(lua_State* L) { int PlayerFunctions::luaPlayerGetContainerIndex(lua_State* L) { // player:getContainerIndex(id) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getContainerIndex(getNumber(L, 2))); } else { @@ -3090,13 +3087,14 @@ int PlayerFunctions::luaPlayerGetContainerIndex(lua_State* L) { int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { // player:getInstantSpells() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; } std::vector> spells; + spells.reserve(30); for (auto &[key, spell] : g_spells().getInstantSpells()) { if (spell->canCast(player)) { spells.push_back(spell); @@ -3106,7 +3104,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { lua_createtable(L, spells.size(), 0); int index = 0; - for (auto spell : spells) { + for (const auto &spell : spells) { pushInstantSpell(L, *spell); lua_rawseti(L, -2, ++index); } @@ -3115,7 +3113,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { int PlayerFunctions::luaPlayerCanCast(lua_State* L) { // player:canCast(spell) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); const auto spell = getUserdataShared(L, 2); if (player && spell) { pushBoolean(L, spell->canCast(player)); @@ -3127,7 +3125,7 @@ int PlayerFunctions::luaPlayerCanCast(lua_State* L) { int PlayerFunctions::luaPlayerHasChaseMode(lua_State* L) { // player:hasChaseMode() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->chaseMode); } else { @@ -3138,7 +3136,7 @@ int PlayerFunctions::luaPlayerHasChaseMode(lua_State* L) { int PlayerFunctions::luaPlayerHasSecureMode(lua_State* L) { // player:hasSecureMode() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->secureMode); } else { @@ -3149,7 +3147,7 @@ int PlayerFunctions::luaPlayerHasSecureMode(lua_State* L) { int PlayerFunctions::luaPlayerGetFightMode(lua_State* L) { // player:getFightMode() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->fightMode); } else { @@ -3160,7 +3158,7 @@ int PlayerFunctions::luaPlayerGetFightMode(lua_State* L) { int PlayerFunctions::luaPlayerGetBaseXpGain(lua_State* L) { // player:getBaseXpGain() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getBaseXpGain()); } else { @@ -3171,7 +3169,7 @@ int PlayerFunctions::luaPlayerGetBaseXpGain(lua_State* L) { int PlayerFunctions::luaPlayerSetBaseXpGain(lua_State* L) { // player:setBaseXpGain(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setBaseXpGain(getNumber(L, 2)); player->sendStats(); @@ -3184,7 +3182,7 @@ int PlayerFunctions::luaPlayerSetBaseXpGain(lua_State* L) { int PlayerFunctions::luaPlayerGetVoucherXpBoost(lua_State* L) { // player:getVoucherXpBoost() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getVoucherXpBoost()); } else { @@ -3195,7 +3193,7 @@ int PlayerFunctions::luaPlayerGetVoucherXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerSetVoucherXpBoost(lua_State* L) { // player:setVoucherXpBoost(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setVoucherXpBoost(getNumber(L, 2)); player->sendStats(); @@ -3208,7 +3206,7 @@ int PlayerFunctions::luaPlayerSetVoucherXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerGetGrindingXpBoost(lua_State* L) { // player:getGrindingXpBoost() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getGrindingXpBoost()); } else { @@ -3219,7 +3217,7 @@ int PlayerFunctions::luaPlayerGetGrindingXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerSetGrindingXpBoost(lua_State* L) { // player:setGrindingXpBoost(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setGrindingXpBoost(getNumber(L, 2)); player->sendStats(); @@ -3232,7 +3230,7 @@ int PlayerFunctions::luaPlayerSetGrindingXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerGetXpBoostPercent(lua_State* L) { // player:getXpBoostPercent() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getXpBoostPercent()); } else { @@ -3243,7 +3241,7 @@ int PlayerFunctions::luaPlayerGetXpBoostPercent(lua_State* L) { int PlayerFunctions::luaPlayerSetXpBoostPercent(lua_State* L) { // player:setXpBoostPercent(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t percent = getNumber(L, 2); player->setXpBoostPercent(percent); @@ -3256,7 +3254,7 @@ int PlayerFunctions::luaPlayerSetXpBoostPercent(lua_State* L) { int PlayerFunctions::luaPlayerGetStaminaXpBoost(lua_State* L) { // player:getStaminaXpBoost() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getStaminaXpBoost()); } else { @@ -3267,7 +3265,7 @@ int PlayerFunctions::luaPlayerGetStaminaXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerSetStaminaXpBoost(lua_State* L) { // player:setStaminaXpBoost(value) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { player->setStaminaXpBoost(getNumber(L, 2)); player->sendStats(); @@ -3280,7 +3278,7 @@ int PlayerFunctions::luaPlayerSetStaminaXpBoost(lua_State* L) { int PlayerFunctions::luaPlayerSetXpBoostTime(lua_State* L) { // player:setXpBoostTime(timeLeft) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { uint16_t timeLeft = getNumber(L, 2); player->setXpBoostTime(timeLeft); @@ -3294,7 +3292,7 @@ int PlayerFunctions::luaPlayerSetXpBoostTime(lua_State* L) { int PlayerFunctions::luaPlayerGetXpBoostTime(lua_State* L) { // player:getXpBoostTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getXpBoostTime()); } else { @@ -3305,7 +3303,7 @@ int PlayerFunctions::luaPlayerGetXpBoostTime(lua_State* L) { int PlayerFunctions::luaPlayerGetIdleTime(lua_State* L) { // player:getIdleTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { lua_pushnumber(L, player->getIdleTime()); } else { @@ -3316,7 +3314,7 @@ int PlayerFunctions::luaPlayerGetIdleTime(lua_State* L) { int PlayerFunctions::luaPlayerGetFreeBackpackSlots(lua_State* L) { // player:getFreeBackpackSlots() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); } @@ -3326,7 +3324,7 @@ int PlayerFunctions::luaPlayerGetFreeBackpackSlots(lua_State* L) { } int PlayerFunctions::luaPlayerIsOffline(lua_State* L) { - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player) { pushBoolean(L, player->isOffline()); } else { @@ -3338,7 +3336,7 @@ int PlayerFunctions::luaPlayerIsOffline(lua_State* L) { int PlayerFunctions::luaPlayerOpenMarket(lua_State* L) { // player:openMarket() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3352,7 +3350,7 @@ int PlayerFunctions::luaPlayerOpenMarket(lua_State* L) { // Forge int PlayerFunctions::luaPlayerOpenForge(lua_State* L) { // player:openForge() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3366,7 +3364,7 @@ int PlayerFunctions::luaPlayerOpenForge(lua_State* L) { int PlayerFunctions::luaPlayerCloseForge(lua_State* L) { // player:closeForge() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3380,7 +3378,7 @@ int PlayerFunctions::luaPlayerCloseForge(lua_State* L) { int PlayerFunctions::luaPlayerAddForgeDusts(lua_State* L) { // player:addForgeDusts(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3394,7 +3392,7 @@ int PlayerFunctions::luaPlayerAddForgeDusts(lua_State* L) { int PlayerFunctions::luaPlayerRemoveForgeDusts(lua_State* L) { // player:removeForgeDusts(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3408,7 +3406,7 @@ int PlayerFunctions::luaPlayerRemoveForgeDusts(lua_State* L) { int PlayerFunctions::luaPlayerGetForgeDusts(lua_State* L) { // player:getForgeDusts() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3421,7 +3419,7 @@ int PlayerFunctions::luaPlayerGetForgeDusts(lua_State* L) { int PlayerFunctions::luaPlayerSetForgeDusts(lua_State* L) { // player:setForgeDusts() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3435,7 +3433,7 @@ int PlayerFunctions::luaPlayerSetForgeDusts(lua_State* L) { int PlayerFunctions::luaPlayerAddForgeDustLevel(lua_State* L) { // player:addForgeDustLevel(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3449,7 +3447,7 @@ int PlayerFunctions::luaPlayerAddForgeDustLevel(lua_State* L) { int PlayerFunctions::luaPlayerRemoveForgeDustLevel(lua_State* L) { // player:removeForgeDustLevel(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3463,7 +3461,7 @@ int PlayerFunctions::luaPlayerRemoveForgeDustLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetForgeDustLevel(lua_State* L) { // player:getForgeDustLevel() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3476,7 +3474,7 @@ int PlayerFunctions::luaPlayerGetForgeDustLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetForgeSlivers(lua_State* L) { // player:getForgeSlivers() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3490,7 +3488,7 @@ int PlayerFunctions::luaPlayerGetForgeSlivers(lua_State* L) { int PlayerFunctions::luaPlayerGetForgeCores(lua_State* L) { // player:getForgeCores() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3504,7 +3502,7 @@ int PlayerFunctions::luaPlayerGetForgeCores(lua_State* L) { int PlayerFunctions::luaPlayerSetFaction(lua_State* L) { // player:setFaction(factionId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3519,7 +3517,7 @@ int PlayerFunctions::luaPlayerSetFaction(lua_State* L) { int PlayerFunctions::luaPlayerGetFaction(lua_State* L) { // player:getFaction() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (player == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3532,7 +3530,7 @@ int PlayerFunctions::luaPlayerGetFaction(lua_State* L) { int PlayerFunctions::luaPlayerIsUIExhausted(lua_State* L) { // player:isUIExhausted() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3546,7 +3544,7 @@ int PlayerFunctions::luaPlayerIsUIExhausted(lua_State* L) { int PlayerFunctions::luaPlayerUpdateUIExhausted(lua_State* L) { // player:updateUIExhausted(exhaustionTime = 250) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3561,7 +3559,7 @@ int PlayerFunctions::luaPlayerUpdateUIExhausted(lua_State* L) { // Bosstiary Cooldown Timer int PlayerFunctions::luaPlayerBosstiaryCooldownTimer(lua_State* L) { // player:sendBosstiaryCooldownTimer() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3575,7 +3573,7 @@ int PlayerFunctions::luaPlayerBosstiaryCooldownTimer(lua_State* L) { int PlayerFunctions::luaPlayerGetBosstiaryLevel(lua_State* L) { // player:getBosstiaryLevel(name) - if (std::shared_ptr player = getUserdataShared(L, 1); + if (const auto &player = getUserdataShared(L, 1); player) { const auto mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { @@ -3597,7 +3595,7 @@ int PlayerFunctions::luaPlayerGetBosstiaryLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetBosstiaryKills(lua_State* L) { // player:getBosstiaryKills(name) - if (std::shared_ptr player = getUserdataShared(L, 1); + if (const auto &player = getUserdataShared(L, 1); player) { const auto mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { @@ -3619,7 +3617,7 @@ int PlayerFunctions::luaPlayerGetBosstiaryKills(lua_State* L) { int PlayerFunctions::luaPlayerAddBosstiaryKill(lua_State* L) { // player:addBosstiaryKill(name[, amount = 1]) - if (std::shared_ptr player = getUserdataShared(L, 1); + if (const auto &player = getUserdataShared(L, 1); player) { const auto mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { @@ -3636,7 +3634,7 @@ int PlayerFunctions::luaPlayerAddBosstiaryKill(lua_State* L) { int PlayerFunctions::luaPlayerSetBossPoints(lua_State* L) { // player:setBossPoints() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3650,7 +3648,7 @@ int PlayerFunctions::luaPlayerSetBossPoints(lua_State* L) { int PlayerFunctions::luaPlayerSetRemoveBossTime(lua_State* L) { // player:setRemoveBossTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3664,7 +3662,7 @@ int PlayerFunctions::luaPlayerSetRemoveBossTime(lua_State* L) { int PlayerFunctions::luaPlayerGetSlotBossId(lua_State* L) { // player:getSlotBossId(slotId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3679,7 +3677,7 @@ int PlayerFunctions::luaPlayerGetSlotBossId(lua_State* L) { int PlayerFunctions::luaPlayerGetBossBonus(lua_State* L) { // player:getBossBonus(slotId) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3701,7 +3699,7 @@ int PlayerFunctions::luaPlayerGetBossBonus(lua_State* L) { int PlayerFunctions::luaPlayerSendSingleSoundEffect(lua_State* L) { // player:sendSingleSoundEffect(soundId[, actor = true]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3718,7 +3716,7 @@ int PlayerFunctions::luaPlayerSendSingleSoundEffect(lua_State* L) { int PlayerFunctions::luaPlayerSendDoubleSoundEffect(lua_State* L) { // player:sendDoubleSoundEffect(mainSoundId, secondarySoundId[, actor = true]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3767,7 +3765,7 @@ int PlayerFunctions::luaPlayerChangeName(lua_State* L) { int PlayerFunctions::luaPlayerHasGroupFlag(lua_State* L) { // player:hasGroupFlag(flag) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3780,7 +3778,7 @@ int PlayerFunctions::luaPlayerHasGroupFlag(lua_State* L) { int PlayerFunctions::luaPlayerSetGroupFlag(lua_State* L) { // player:setGroupFlag(flag) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3793,7 +3791,7 @@ int PlayerFunctions::luaPlayerSetGroupFlag(lua_State* L) { int PlayerFunctions::luaPlayerRemoveGroupFlag(lua_State* L) { // player:removeGroupFlag(flag) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3807,7 +3805,7 @@ int PlayerFunctions::luaPlayerRemoveGroupFlag(lua_State* L) { // Hazard system int PlayerFunctions::luaPlayerAddHazardSystemPoints(lua_State* L) { // player:setHazardSystemPoints(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); @@ -3834,7 +3832,7 @@ int PlayerFunctions::luaPlayerGetHazardSystemPoints(lua_State* L) { int PlayerFunctions::luaPlayerSetLoyaltyBonus(lua_State* L) { // player:setLoyaltyBonus(amount) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3847,7 +3845,7 @@ int PlayerFunctions::luaPlayerSetLoyaltyBonus(lua_State* L) { int PlayerFunctions::luaPlayerGetLoyaltyBonus(lua_State* L) { // player:getLoyaltyBonus() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3871,7 +3869,7 @@ int PlayerFunctions::luaPlayerGetLoyaltyPoints(lua_State* L) { int PlayerFunctions::luaPlayerGetLoyaltyTitle(lua_State* L) { // player:getLoyaltyTitle() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3883,7 +3881,7 @@ int PlayerFunctions::luaPlayerGetLoyaltyTitle(lua_State* L) { int PlayerFunctions::luaPlayerSetLoyaltyTitle(lua_State* L) { // player:setLoyaltyTitle(name) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3897,7 +3895,7 @@ int PlayerFunctions::luaPlayerSetLoyaltyTitle(lua_State* L) { // Wheel of destiny system int PlayerFunctions::luaPlayerInstantSkillWOD(lua_State* L) { // player:instantSkillWOD(name[, value]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3915,7 +3913,7 @@ int PlayerFunctions::luaPlayerInstantSkillWOD(lua_State* L) { int PlayerFunctions::luaPlayerUpgradeSpellWOD(lua_State* L) { // player:upgradeSpellsWOD([name[, add]]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3945,7 +3943,7 @@ int PlayerFunctions::luaPlayerUpgradeSpellWOD(lua_State* L) { int PlayerFunctions::luaPlayerRevelationStageWOD(lua_State* L) { // player:revelationStageWOD([name[, set]]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3971,7 +3969,7 @@ int PlayerFunctions::luaPlayerRevelationStageWOD(lua_State* L) { int PlayerFunctions::luaPlayerReloadData(lua_State* L) { // player:reloadData() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3988,7 +3986,7 @@ int PlayerFunctions::luaPlayerReloadData(lua_State* L) { int PlayerFunctions::luaPlayerOnThinkWheelOfDestiny(lua_State* L) { // player:onThinkWheelOfDestiny([force = false]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -4001,7 +3999,7 @@ int PlayerFunctions::luaPlayerOnThinkWheelOfDestiny(lua_State* L) { int PlayerFunctions::luaPlayerAvatarTimer(lua_State* L) { // player:avatarTimer([value]) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -4018,7 +4016,7 @@ int PlayerFunctions::luaPlayerAvatarTimer(lua_State* L) { int PlayerFunctions::luaPlayerGetWheelSpellAdditionalArea(lua_State* L) { // player:getWheelSpellAdditionalArea(spellname) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4045,7 +4043,7 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalArea(lua_State* L) { int PlayerFunctions::luaPlayerGetWheelSpellAdditionalTarget(lua_State* L) { // player:getWheelSpellAdditionalTarget(spellname) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4072,7 +4070,7 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalTarget(lua_State* L) { int PlayerFunctions::luaPlayerGetWheelSpellAdditionalDuration(lua_State* L) { // player:getWheelSpellAdditionalDuration(spellname) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4099,7 +4097,7 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalDuration(lua_State* L) { int PlayerFunctions::luaPlayerUpdateConcoction(lua_State* L) { // player:updateConcoction(itemid, timeLeft) - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -4111,7 +4109,7 @@ int PlayerFunctions::luaPlayerUpdateConcoction(lua_State* L) { int PlayerFunctions::luaPlayerClearSpellCooldowns(lua_State* L) { // player:clearSpellCooldowns() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -4123,7 +4121,7 @@ int PlayerFunctions::luaPlayerClearSpellCooldowns(lua_State* L) { int PlayerFunctions::luaPlayerIsVip(lua_State* L) { // player:isVip() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4135,7 +4133,7 @@ int PlayerFunctions::luaPlayerIsVip(lua_State* L) { int PlayerFunctions::luaPlayerGetVipDays(lua_State* L) { // player:getVipDays() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4148,7 +4146,7 @@ int PlayerFunctions::luaPlayerGetVipDays(lua_State* L) { int PlayerFunctions::luaPlayerGetVipTime(lua_State* L) { // player:getVipTime() - std::shared_ptr player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/player/vocation_functions.cpp b/src/lua/functions/creatures/player/vocation_functions.cpp index 15cf888bf8a..5cd64cbe1d3 100644 --- a/src/lua/functions/creatures/player/vocation_functions.cpp +++ b/src/lua/functions/creatures/player/vocation_functions.cpp @@ -21,7 +21,7 @@ int VocationFunctions::luaVocationCreate(lua_State* L) { vocationId = g_vocations().getVocationId(getString(L, 2)); } - std::shared_ptr vocation = g_vocations().getVocation(vocationId); + const auto &vocation = g_vocations().getVocation(vocationId); if (vocation) { pushUserdata(L, vocation); setMetatable(L, -1, "Vocation"); @@ -33,7 +33,7 @@ int VocationFunctions::luaVocationCreate(lua_State* L) { int VocationFunctions::luaVocationGetId(lua_State* L) { // vocation:getId() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getId()); } else { @@ -44,7 +44,7 @@ int VocationFunctions::luaVocationGetId(lua_State* L) { int VocationFunctions::luaVocationGetClientId(lua_State* L) { // vocation:getClientId() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getClientId()); } else { @@ -55,7 +55,7 @@ int VocationFunctions::luaVocationGetClientId(lua_State* L) { int VocationFunctions::luaVocationGetBaseId(lua_State* L) { // vocation:getBaseId() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getBaseId()); } else { @@ -66,7 +66,7 @@ int VocationFunctions::luaVocationGetBaseId(lua_State* L) { int VocationFunctions::luaVocationGetName(lua_State* L) { // vocation:getName() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { pushString(L, vocation->getVocName()); } else { @@ -77,7 +77,7 @@ int VocationFunctions::luaVocationGetName(lua_State* L) { int VocationFunctions::luaVocationGetDescription(lua_State* L) { // vocation:getDescription() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { pushString(L, vocation->getVocDescription()); } else { @@ -88,7 +88,7 @@ int VocationFunctions::luaVocationGetDescription(lua_State* L) { int VocationFunctions::luaVocationGetRequiredSkillTries(lua_State* L) { // vocation:getRequiredSkillTries(skillType, skillLevel) - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { skills_t skillType = getNumber(L, 2); uint16_t skillLevel = getNumber(L, 3); @@ -101,7 +101,7 @@ int VocationFunctions::luaVocationGetRequiredSkillTries(lua_State* L) { int VocationFunctions::luaVocationGetRequiredManaSpent(lua_State* L) { // vocation:getRequiredManaSpent(magicLevel) - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { uint32_t magicLevel = getNumber(L, 2); lua_pushnumber(L, vocation->getReqMana(magicLevel)); @@ -113,7 +113,7 @@ int VocationFunctions::luaVocationGetRequiredManaSpent(lua_State* L) { int VocationFunctions::luaVocationGetCapacityGain(lua_State* L) { // vocation:getCapacityGain() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getCapGain()); } else { @@ -124,7 +124,7 @@ int VocationFunctions::luaVocationGetCapacityGain(lua_State* L) { int VocationFunctions::luaVocationGetHealthGain(lua_State* L) { // vocation:getHealthGain() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getHPGain()); } else { @@ -135,7 +135,7 @@ int VocationFunctions::luaVocationGetHealthGain(lua_State* L) { int VocationFunctions::luaVocationGetHealthGainTicks(lua_State* L) { // vocation:getHealthGainTicks() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getHealthGainTicks()); } else { @@ -146,7 +146,7 @@ int VocationFunctions::luaVocationGetHealthGainTicks(lua_State* L) { int VocationFunctions::luaVocationGetHealthGainAmount(lua_State* L) { // vocation:getHealthGainAmount() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getHealthGainAmount()); } else { @@ -157,7 +157,7 @@ int VocationFunctions::luaVocationGetHealthGainAmount(lua_State* L) { int VocationFunctions::luaVocationGetManaGain(lua_State* L) { // vocation:getManaGain() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getManaGain()); } else { @@ -168,7 +168,7 @@ int VocationFunctions::luaVocationGetManaGain(lua_State* L) { int VocationFunctions::luaVocationGetManaGainTicks(lua_State* L) { // vocation:getManaGainTicks() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getManaGainTicks()); } else { @@ -179,7 +179,7 @@ int VocationFunctions::luaVocationGetManaGainTicks(lua_State* L) { int VocationFunctions::luaVocationGetManaGainAmount(lua_State* L) { // vocation:getManaGainAmount() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getManaGainAmount()); } else { @@ -190,7 +190,7 @@ int VocationFunctions::luaVocationGetManaGainAmount(lua_State* L) { int VocationFunctions::luaVocationGetMaxSoul(lua_State* L) { // vocation:getMaxSoul() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getSoulMax()); } else { @@ -201,7 +201,7 @@ int VocationFunctions::luaVocationGetMaxSoul(lua_State* L) { int VocationFunctions::luaVocationGetSoulGainTicks(lua_State* L) { // vocation:getSoulGainTicks() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getSoulGainTicks()); } else { @@ -212,7 +212,7 @@ int VocationFunctions::luaVocationGetSoulGainTicks(lua_State* L) { int VocationFunctions::luaVocationGetBaseAttackSpeed(lua_State* L) { // vocation:getBaseAttackSpeed() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getBaseAttackSpeed()); } else { @@ -223,7 +223,7 @@ int VocationFunctions::luaVocationGetBaseAttackSpeed(lua_State* L) { int VocationFunctions::luaVocationGetAttackSpeed(lua_State* L) { // vocation:getAttackSpeed() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getAttackSpeed()); } else { @@ -234,7 +234,7 @@ int VocationFunctions::luaVocationGetAttackSpeed(lua_State* L) { int VocationFunctions::luaVocationGetBaseSpeed(lua_State* L) { // vocation:getBaseSpeed() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (vocation) { lua_pushnumber(L, vocation->getBaseSpeed()); } else { @@ -245,7 +245,7 @@ int VocationFunctions::luaVocationGetBaseSpeed(lua_State* L) { int VocationFunctions::luaVocationGetDemotion(lua_State* L) { // vocation:getDemotion() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (!vocation) { lua_pushnil(L); return 1; @@ -257,7 +257,7 @@ int VocationFunctions::luaVocationGetDemotion(lua_State* L) { return 1; } - std::shared_ptr demotedVocation = g_vocations().getVocation(fromId); + const auto &demotedVocation = g_vocations().getVocation(fromId); if (demotedVocation && demotedVocation != vocation) { pushUserdata(L, demotedVocation); setMetatable(L, -1, "Vocation"); @@ -269,7 +269,7 @@ int VocationFunctions::luaVocationGetDemotion(lua_State* L) { int VocationFunctions::luaVocationGetPromotion(lua_State* L) { // vocation:getPromotion() - std::shared_ptr vocation = getUserdataShared(L, 1); + const auto &vocation = getUserdataShared(L, 1); if (!vocation) { lua_pushnil(L); return 1; @@ -281,7 +281,7 @@ int VocationFunctions::luaVocationGetPromotion(lua_State* L) { return 1; } - std::shared_ptr promotedVocation = g_vocations().getVocation(promotedId); + const auto &promotedVocation = g_vocations().getVocation(promotedId); if (promotedVocation && promotedVocation != vocation) { pushUserdata(L, promotedVocation); setMetatable(L, -1, "Vocation"); diff --git a/src/lua/functions/events/action_functions.cpp b/src/lua/functions/events/action_functions.cpp index 31b202465c7..6260cb78614 100644 --- a/src/lua/functions/events/action_functions.cpp +++ b/src/lua/functions/events/action_functions.cpp @@ -16,7 +16,7 @@ int ActionFunctions::luaCreateAction(lua_State* L) { // Action() - auto action = std::make_shared(getScriptEnv()->getScriptInterface()); + const auto action = std::make_shared(getScriptEnv()->getScriptInterface()); pushUserdata(L, action); setMetatable(L, -1, "Action"); return 1; @@ -24,7 +24,7 @@ int ActionFunctions::luaCreateAction(lua_State* L) { int ActionFunctions::luaActionOnUse(lua_State* L) { // action:onUse(callback) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { if (!action->loadCallback()) { pushBoolean(L, false); @@ -41,7 +41,7 @@ int ActionFunctions::luaActionOnUse(lua_State* L) { int ActionFunctions::luaActionRegister(lua_State* L) { // action:register() - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { if (!action->isLoadedCallback()) { pushBoolean(L, false); @@ -58,7 +58,7 @@ int ActionFunctions::luaActionRegister(lua_State* L) { int ActionFunctions::luaActionItemId(lua_State* L) { // action:id(ids) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -78,7 +78,7 @@ int ActionFunctions::luaActionItemId(lua_State* L) { int ActionFunctions::luaActionActionId(lua_State* L) { // action:aid(aids) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -98,7 +98,7 @@ int ActionFunctions::luaActionActionId(lua_State* L) { int ActionFunctions::luaActionUniqueId(lua_State* L) { // action:uid(uids) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -122,7 +122,7 @@ int ActionFunctions::luaActionPosition(lua_State* L) { * @param itemId or @param itemName = if item id or string name is set, the item is created on position (if not exists), this variable is nil by default * action:position(positions, itemId or name) */ - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (!action) { reportErrorFunc(getErrorDesc(LUA_ERROR_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -179,7 +179,7 @@ int ActionFunctions::luaActionPosition(lua_State* L) { int ActionFunctions::luaActionAllowFarUse(lua_State* L) { // action:allowFarUse(bool) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { action->setAllowFarUse(getBoolean(L, 2)); pushBoolean(L, true); @@ -192,7 +192,7 @@ int ActionFunctions::luaActionAllowFarUse(lua_State* L) { int ActionFunctions::luaActionBlockWalls(lua_State* L) { // action:blockWalls(bool) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { action->setCheckLineOfSight(getBoolean(L, 2)); pushBoolean(L, true); @@ -205,7 +205,7 @@ int ActionFunctions::luaActionBlockWalls(lua_State* L) { int ActionFunctions::luaActionCheckFloor(lua_State* L) { // action:checkFloor(bool) - const auto action = getUserdataShared(L, 1); + const auto &action = getUserdataShared(L, 1); if (action) { action->setCheckFloor(getBoolean(L, 2)); pushBoolean(L, true); diff --git a/src/lua/functions/events/creature_event_functions.cpp b/src/lua/functions/events/creature_event_functions.cpp index 7edbabad1d3..a82f1105723 100644 --- a/src/lua/functions/events/creature_event_functions.cpp +++ b/src/lua/functions/events/creature_event_functions.cpp @@ -15,7 +15,7 @@ int CreatureEventFunctions::luaCreateCreatureEvent(lua_State* L) { // CreatureEvent(eventName) - auto creatureEvent = std::make_shared(getScriptEnv()->getScriptInterface()); + const auto creatureEvent = std::make_shared(getScriptEnv()->getScriptInterface()); creatureEvent->setName(getString(L, 2)); pushUserdata(L, creatureEvent); setMetatable(L, -1, "CreatureEvent"); @@ -24,7 +24,7 @@ int CreatureEventFunctions::luaCreateCreatureEvent(lua_State* L) { int CreatureEventFunctions::luaCreatureEventType(lua_State* L) { // creatureevent:type(callback) - const auto creatureEvent = getUserdataShared(L, 1); + const auto &creatureEvent = getUserdataShared(L, 1); if (creatureEvent) { std::string typeName = getString(L, 2); std::string tmpStr = asLowerCaseString(typeName); @@ -68,7 +68,7 @@ int CreatureEventFunctions::luaCreatureEventType(lua_State* L) { int CreatureEventFunctions::luaCreatureEventRegister(lua_State* L) { // creatureevent:register() - const auto creatureEvent = getUserdataShared(L, 1); + const auto &creatureEvent = getUserdataShared(L, 1); if (creatureEvent) { if (!creatureEvent->isLoadedCallback()) { pushBoolean(L, false); @@ -83,7 +83,7 @@ int CreatureEventFunctions::luaCreatureEventRegister(lua_State* L) { int CreatureEventFunctions::luaCreatureEventOnCallback(lua_State* L) { // creatureevent:onLogin / logout / etc. (callback) - const auto creatureEvent = getUserdataShared(L, 1); + const auto &creatureEvent = getUserdataShared(L, 1); if (creatureEvent) { if (!creatureEvent->loadCallback()) { pushBoolean(L, false); diff --git a/src/lua/functions/events/event_callback_functions.cpp b/src/lua/functions/events/event_callback_functions.cpp index 54457f4367a..ab1a326ba94 100644 --- a/src/lua/functions/events/event_callback_functions.cpp +++ b/src/lua/functions/events/event_callback_functions.cpp @@ -41,7 +41,7 @@ int EventCallbackFunctions::luaEventCallbackCreate(lua_State* luaState) { } int EventCallbackFunctions::luaEventCallbackType(lua_State* luaState) { - auto callback = getUserdataShared(luaState, 1); + const auto &callback = getUserdataShared(luaState, 1); if (!callback) { reportErrorFunc("EventCallback is nil"); return 0; @@ -72,7 +72,7 @@ int EventCallbackFunctions::luaEventCallbackType(lua_State* luaState) { } int EventCallbackFunctions::luaEventCallbackRegister(lua_State* luaState) { - auto callback = getUserdataShared(luaState, 1); + const auto &callback = getUserdataShared(luaState, 1); if (!callback) { reportErrorFunc("EventCallback is nil, failed to register script"); return 0; @@ -89,7 +89,7 @@ int EventCallbackFunctions::luaEventCallbackRegister(lua_State* luaState) { // Callback functions int EventCallbackFunctions::luaEventCallbackLoad(lua_State* luaState) { - auto callback = getUserdataShared(luaState, 1); + const auto &callback = getUserdataShared(luaState, 1); if (!callback) { reportErrorFunc("EventCallback is nil"); return 1; diff --git a/src/lua/functions/events/global_event_functions.cpp b/src/lua/functions/events/global_event_functions.cpp index 129a466e97c..d23ad4bf2c9 100644 --- a/src/lua/functions/events/global_event_functions.cpp +++ b/src/lua/functions/events/global_event_functions.cpp @@ -12,7 +12,6 @@ #include "lua/functions/events/global_event_functions.hpp" #include "game/game.hpp" #include "lua/global/globalevent.hpp" -#include "lua/scripts/scripts.hpp" #include "utils/tools.hpp" int GlobalEventFunctions::luaCreateGlobalEvent(lua_State* L) { @@ -26,7 +25,7 @@ int GlobalEventFunctions::luaCreateGlobalEvent(lua_State* L) { int GlobalEventFunctions::luaGlobalEventType(lua_State* L) { // globalevent:type(callback) - const auto global = getUserdataShared(L, 1); + const auto &global = getUserdataShared(L, 1); if (global) { std::string typeName = getString(L, 2); std::string tmpStr = asLowerCaseString(typeName); @@ -56,7 +55,7 @@ int GlobalEventFunctions::luaGlobalEventType(lua_State* L) { int GlobalEventFunctions::luaGlobalEventRegister(lua_State* L) { // globalevent:register() - const auto globalevent = getUserdataShared(L, 1); + const auto &globalevent = getUserdataShared(L, 1); if (globalevent) { if (!globalevent->isLoadedCallback()) { pushBoolean(L, false); @@ -76,7 +75,7 @@ int GlobalEventFunctions::luaGlobalEventRegister(lua_State* L) { int GlobalEventFunctions::luaGlobalEventOnCallback(lua_State* L) { // globalevent:onThink / record / etc. (callback) - const auto globalevent = getUserdataShared(L, 1); + const auto &globalevent = getUserdataShared(L, 1); if (globalevent) { if (!globalevent->loadCallback()) { pushBoolean(L, false); @@ -91,7 +90,7 @@ int GlobalEventFunctions::luaGlobalEventOnCallback(lua_State* L) { int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { // globalevent:time(time) - const auto globalevent = getUserdataShared(L, 1); + const auto &globalevent = getUserdataShared(L, 1); if (globalevent) { std::string timer = getString(L, 2); std::vector params = vectorAtoi(explodeString(timer, ":")); @@ -154,7 +153,7 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { int GlobalEventFunctions::luaGlobalEventInterval(lua_State* L) { // globalevent:interval(interval) - const auto globalevent = getUserdataShared(L, 1); + const auto &globalevent = getUserdataShared(L, 1); if (globalevent) { globalevent->setInterval(getNumber(L, 2)); globalevent->setNextExecution(OTSYS_TIME() + getNumber(L, 2)); diff --git a/src/lua/functions/events/move_event_functions.cpp b/src/lua/functions/events/move_event_functions.cpp index 8340dded92f..29d80fc20ce 100644 --- a/src/lua/functions/events/move_event_functions.cpp +++ b/src/lua/functions/events/move_event_functions.cpp @@ -23,7 +23,7 @@ int MoveEventFunctions::luaCreateMoveEvent(lua_State* L) { int MoveEventFunctions::luaMoveEventType(lua_State* L) { // moveevent:type(callback) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { std::string typeName = getString(L, 2); std::string tmpStr = asLowerCaseString(typeName); @@ -60,7 +60,7 @@ int MoveEventFunctions::luaMoveEventType(lua_State* L) { int MoveEventFunctions::luaMoveEventRegister(lua_State* L) { // moveevent:register() - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { // If not scripted, register item event // Example: unscripted_equipments.lua @@ -78,7 +78,7 @@ int MoveEventFunctions::luaMoveEventRegister(lua_State* L) { int MoveEventFunctions::luaMoveEventOnCallback(lua_State* L) { // moveevent:onEquip / deEquip / etc. (callback) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { if (!moveevent->loadCallback()) { pushBoolean(L, false); @@ -94,7 +94,7 @@ int MoveEventFunctions::luaMoveEventOnCallback(lua_State* L) { int MoveEventFunctions::luaMoveEventSlot(lua_State* L) { // moveevent:slot(slot) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (!moveevent) { lua_pushnil(L); return 1; @@ -139,7 +139,7 @@ int MoveEventFunctions::luaMoveEventSlot(lua_State* L) { int MoveEventFunctions::luaMoveEventLevel(lua_State* L) { // moveevent:level(lvl) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { moveevent->setRequiredLevel(getNumber(L, 2)); moveevent->setWieldInfo(WIELDINFO_LEVEL); @@ -152,7 +152,7 @@ int MoveEventFunctions::luaMoveEventLevel(lua_State* L) { int MoveEventFunctions::luaMoveEventMagLevel(lua_State* L) { // moveevent:magicLevel(lvl) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { moveevent->setRequiredMagLevel(getNumber(L, 2)); moveevent->setWieldInfo(WIELDINFO_MAGLV); @@ -165,7 +165,7 @@ int MoveEventFunctions::luaMoveEventMagLevel(lua_State* L) { int MoveEventFunctions::luaMoveEventPremium(lua_State* L) { // moveevent:premium(bool) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { moveevent->setNeedPremium(getBoolean(L, 2)); moveevent->setWieldInfo(WIELDINFO_PREMIUM); @@ -178,7 +178,7 @@ int MoveEventFunctions::luaMoveEventPremium(lua_State* L) { int MoveEventFunctions::luaMoveEventVocation(lua_State* L) { // moveevent:vocation(vocName[, showInDescription = false, lastVoc = false]) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { moveevent->addVocEquipMap(getString(L, 2)); moveevent->setWieldInfo(WIELDINFO_VOCREQ); @@ -217,7 +217,7 @@ int MoveEventFunctions::luaMoveEventVocation(lua_State* L) { int MoveEventFunctions::luaMoveEventItemId(lua_State* L) { // moveevent:id(ids) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -236,7 +236,7 @@ int MoveEventFunctions::luaMoveEventItemId(lua_State* L) { int MoveEventFunctions::luaMoveEventActionId(lua_State* L) { // moveevent:aid(ids) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -255,7 +255,7 @@ int MoveEventFunctions::luaMoveEventActionId(lua_State* L) { int MoveEventFunctions::luaMoveEventUniqueId(lua_State* L) { // moveevent:uid(ids) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { @@ -274,7 +274,7 @@ int MoveEventFunctions::luaMoveEventUniqueId(lua_State* L) { int MoveEventFunctions::luaMoveEventPosition(lua_State* L) { // moveevent:position(positions) - const auto moveevent = getUserdataShared(L, 1); + const auto &moveevent = getUserdataShared(L, 1); if (moveevent) { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { diff --git a/src/lua/functions/events/talk_action_functions.cpp b/src/lua/functions/events/talk_action_functions.cpp index 559e251eb8e..6ffb3fef652 100644 --- a/src/lua/functions/events/talk_action_functions.cpp +++ b/src/lua/functions/events/talk_action_functions.cpp @@ -19,11 +19,12 @@ int TalkActionFunctions::luaCreateTalkAction(lua_State* L) { // TalkAction(words) or TalkAction(word1, word2, word3) std::vector wordsVector; + wordsVector.reserve(500); for (int i = 2; i <= lua_gettop(L); i++) { - wordsVector.push_back(getString(L, i)); + wordsVector.emplace_back(getString(L, i)); } - auto talkactionSharedPtr = std::make_shared(getScriptEnv()->getScriptInterface()); + const auto talkactionSharedPtr = std::make_shared(getScriptEnv()->getScriptInterface()); talkactionSharedPtr->setWords(wordsVector); pushUserdata(L, talkactionSharedPtr); setMetatable(L, -1, "TalkAction"); @@ -32,7 +33,7 @@ int TalkActionFunctions::luaCreateTalkAction(lua_State* L) { int TalkActionFunctions::luaTalkActionOnSay(lua_State* L) { // talkAction:onSay(callback) - auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -49,7 +50,7 @@ int TalkActionFunctions::luaTalkActionOnSay(lua_State* L) { int TalkActionFunctions::luaTalkActionGroupType(lua_State* L) { // talkAction:groupType(GroupType = GROUP_TYPE_NORMAL) - auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -94,7 +95,7 @@ int TalkActionFunctions::luaTalkActionGroupType(lua_State* L) { int TalkActionFunctions::luaTalkActionRegister(lua_State* L) { // talkAction:register() - auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -119,7 +120,7 @@ int TalkActionFunctions::luaTalkActionRegister(lua_State* L) { int TalkActionFunctions::luaTalkActionSeparator(lua_State* L) { // talkAction:separator(sep) - auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -133,7 +134,7 @@ int TalkActionFunctions::luaTalkActionSeparator(lua_State* L) { int TalkActionFunctions::luaTalkActionGetName(lua_State* L) { // local name = talkAction:getName() - const auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -146,7 +147,7 @@ int TalkActionFunctions::luaTalkActionGetName(lua_State* L) { int TalkActionFunctions::luaTalkActionGetDescription(lua_State* L) { // local description = talkAction:getDescription() - const auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -159,7 +160,7 @@ int TalkActionFunctions::luaTalkActionGetDescription(lua_State* L) { int TalkActionFunctions::luaTalkActionSetDescription(lua_State* L) { // local description = talkAction:setDescription() - auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); @@ -173,7 +174,7 @@ int TalkActionFunctions::luaTalkActionSetDescription(lua_State* L) { int TalkActionFunctions::luaTalkActionGetGroupType(lua_State* L) { // local groupType = talkAction:getGroupType() - const auto talkactionSharedPtr = getUserdataShared(L, 1); + const auto &talkactionSharedPtr = getUserdataShared(L, 1); if (!talkactionSharedPtr) { reportErrorFunc(getErrorDesc(LUA_ERROR_TALK_ACTION_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/items/container_functions.cpp b/src/lua/functions/items/container_functions.cpp index 30eb26c6801..fd0c2c38a8b 100644 --- a/src/lua/functions/items/container_functions.cpp +++ b/src/lua/functions/items/container_functions.cpp @@ -17,7 +17,7 @@ int ContainerFunctions::luaContainerCreate(lua_State* L) { // Container(uid) uint32_t id = getNumber(L, 2); - std::shared_ptr container = getScriptEnv()->getContainerByUID(id); + const auto &container = getScriptEnv()->getContainerByUID(id); if (container) { pushUserdata(L, container); setMetatable(L, -1, "Container"); @@ -29,7 +29,7 @@ int ContainerFunctions::luaContainerCreate(lua_State* L) { int ContainerFunctions::luaContainerGetSize(lua_State* L) { // container:getSize() - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (container) { lua_pushnumber(L, container->size()); } else { @@ -51,7 +51,7 @@ int ContainerFunctions::luaContainerGetMaxCapacity(lua_State* L) { int ContainerFunctions::luaContainerGetCapacity(lua_State* L) { // container:getCapacity() - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (container) { lua_pushnumber(L, container->capacity()); } else { @@ -62,7 +62,7 @@ int ContainerFunctions::luaContainerGetCapacity(lua_State* L) { int ContainerFunctions::luaContainerGetEmptySlots(lua_State* L) { // container:getEmptySlots([recursive = false]) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -72,7 +72,7 @@ int ContainerFunctions::luaContainerGetEmptySlots(lua_State* L) { bool recursive = getBoolean(L, 2, false); if (recursive) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - if (std::shared_ptr tmpContainer = (*it)->getContainer()) { + if (auto tmpContainer = (*it)->getContainer()) { slots += tmpContainer->capacity() - tmpContainer->size(); } } @@ -83,7 +83,7 @@ int ContainerFunctions::luaContainerGetEmptySlots(lua_State* L) { int ContainerFunctions::luaContainerGetItemHoldingCount(lua_State* L) { // container:getItemHoldingCount() - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (container) { lua_pushnumber(L, container->getItemHoldingCount()); } else { @@ -94,14 +94,14 @@ int ContainerFunctions::luaContainerGetItemHoldingCount(lua_State* L) { int ContainerFunctions::luaContainerGetItem(lua_State* L) { // container:getItem(index) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; } uint32_t index = getNumber(L, 2); - std::shared_ptr item = container->getItemByIndex(index); + const auto &item = container->getItemByIndex(index); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -113,8 +113,8 @@ int ContainerFunctions::luaContainerGetItem(lua_State* L) { int ContainerFunctions::luaContainerHasItem(lua_State* L) { // container:hasItem(item) - std::shared_ptr item = getUserdataShared(L, 2); - std::shared_ptr container = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 2); + const auto &container = getUserdataShared(L, 1); if (container) { pushBoolean(L, container->isHoldingItem(item)); } else { @@ -125,7 +125,7 @@ int ContainerFunctions::luaContainerHasItem(lua_State* L) { int ContainerFunctions::luaContainerAddItem(lua_State* L) { // container:addItem(itemId[, count/subType = 1[, index = INDEX_WHEREEVER[, flags = 0]]]) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); reportErrorFunc("Container is nullptr"); @@ -150,7 +150,7 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { count = std::min(count, it.stackSize); } - std::shared_ptr item = Item::CreateItem(itemId, count); + const auto &item = Item::CreateItem(itemId, count); if (!item) { lua_pushnil(L); reportErrorFunc("Item is nullptr"); @@ -173,13 +173,13 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { int ContainerFunctions::luaContainerAddItemEx(lua_State* L) { // container:addItemEx(item[, index = INDEX_WHEREEVER[, flags = 0]]) - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -203,7 +203,7 @@ int ContainerFunctions::luaContainerAddItemEx(lua_State* L) { int ContainerFunctions::luaContainerGetCorpseOwner(lua_State* L) { // container:getCorpseOwner() - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (container) { lua_pushnumber(L, container->getCorpseOwner()); } else { @@ -214,7 +214,7 @@ int ContainerFunctions::luaContainerGetCorpseOwner(lua_State* L) { int ContainerFunctions::luaContainerGetItemCountById(lua_State* L) { // container:getItemCountById(itemId[, subType = -1]) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -238,7 +238,7 @@ int ContainerFunctions::luaContainerGetItemCountById(lua_State* L) { int ContainerFunctions::luaContainerGetContentDescription(lua_State* L) { // container:getContentDescription([oldProtocol]) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (container) { pushString(L, container->getContentDescription(getBoolean(L, 2, false))); } else { @@ -249,7 +249,7 @@ int ContainerFunctions::luaContainerGetContentDescription(lua_State* L) { int ContainerFunctions::luaContainerGetItems(lua_State* L) { // container:getItems([recursive = false]) - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; @@ -261,7 +261,7 @@ int ContainerFunctions::luaContainerGetItems(lua_State* L) { lua_createtable(L, static_cast(items.size()), 0); int index = 0; - for (std::shared_ptr item : items) { + for (const auto &item : items) { index++; pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -272,14 +272,14 @@ int ContainerFunctions::luaContainerGetItems(lua_State* L) { int ContainerFunctions::luaContainerRegisterReward(lua_State* L) { // container:registerReward() - std::shared_ptr container = getUserdataShared(L, 1); + const auto &container = getUserdataShared(L, 1); if (!container) { lua_pushnil(L); return 1; } int64_t rewardId = getTimeMsNow(); - std::shared_ptr rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); + const auto &rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); rewardContainer->setAttribute(ItemAttribute_t::DATE, rewardId); container->setAttribute(ItemAttribute_t::DATE, rewardId); container->internalAddThing(rewardContainer); diff --git a/src/lua/functions/items/item_functions.cpp b/src/lua/functions/items/item_functions.cpp index 361a469da32..565fa496bd7 100644 --- a/src/lua/functions/items/item_functions.cpp +++ b/src/lua/functions/items/item_functions.cpp @@ -23,7 +23,7 @@ int ItemFunctions::luaItemCreate(lua_State* L) { // Item(uid) uint32_t id = getNumber(L, 2); - std::shared_ptr item = getScriptEnv()->getItemByUID(id); + const auto &item = getScriptEnv()->getItemByUID(id); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -41,13 +41,13 @@ int ItemFunctions::luaItemIsItem(lua_State* L) { int ItemFunctions::luaItemGetParent(lua_State* L) { // item:getParent() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr parent = item->getParent(); + const auto &parent = item->getParent(); if (!parent) { lua_pushnil(L); return 1; @@ -59,13 +59,13 @@ int ItemFunctions::luaItemGetParent(lua_State* L) { int ItemFunctions::luaItemGetTopParent(lua_State* L) { // item:getTopParent() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr topParent = item->getTopParent(); + const auto &topParent = item->getTopParent(); if (!topParent) { lua_pushnil(L); return 1; @@ -77,7 +77,7 @@ int ItemFunctions::luaItemGetTopParent(lua_State* L) { int ItemFunctions::luaItemGetId(lua_State* L) { // item:getId() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, item->getID()); } else { @@ -88,13 +88,13 @@ int ItemFunctions::luaItemGetId(lua_State* L) { int ItemFunctions::luaItemClone(lua_State* L) { // item:clone() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr clone = item->clone(); + const auto &clone = item->clone(); if (!clone) { lua_pushnil(L); return 1; @@ -110,13 +110,13 @@ int ItemFunctions::luaItemClone(lua_State* L) { int ItemFunctions::luaItemSplit(lua_State* L) { // item:split([count = 1]) - std::shared_ptr* itemPtr = getRawUserDataShared(L, 1); + const auto &itemPtr = getRawUserDataShared(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - std::shared_ptr item = *itemPtr; + const auto &item = *itemPtr; if (!item || !item->isStackable() || item->isRemoved()) { lua_pushnil(L); return 1; @@ -125,7 +125,7 @@ int ItemFunctions::luaItemSplit(lua_State* L) { uint16_t count = std::min(getNumber(L, 2, 1), item->getItemCount()); uint16_t diff = item->getItemCount() - count; - std::shared_ptr splitItem = item->clone(); + const auto &splitItem = item->clone(); if (!splitItem) { lua_pushnil(L); return 1; @@ -136,7 +136,7 @@ int ItemFunctions::luaItemSplit(lua_State* L) { ScriptEnvironment* env = getScriptEnv(); uint32_t uid = env->addThing(item); - std::shared_ptr newItem = g_game().transformItem(item, item->getID(), diff); + const auto &newItem = g_game().transformItem(item, item->getID(), diff); if (item->isRemoved()) { env->removeItemByUID(uid); } @@ -157,7 +157,7 @@ int ItemFunctions::luaItemSplit(lua_State* L) { int ItemFunctions::luaItemRemove(lua_State* L) { // item:remove([count = -1]) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { int32_t count = getNumber(L, 2, -1); pushBoolean(L, g_game().internalRemoveItem(item, count) == RETURNVALUE_NOERROR); @@ -169,7 +169,7 @@ int ItemFunctions::luaItemRemove(lua_State* L) { int ItemFunctions::luaItemGetUniqueId(lua_State* L) { // item:getUniqueId() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { uint32_t uniqueId = item->getAttribute(ItemAttribute_t::UNIQUEID); if (uniqueId == 0) { @@ -184,7 +184,7 @@ int ItemFunctions::luaItemGetUniqueId(lua_State* L) { int ItemFunctions::luaItemGetActionId(lua_State* L) { // item:getActionId() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { auto actionId = item->getAttribute(ItemAttribute_t::ACTIONID); lua_pushnumber(L, actionId); @@ -197,7 +197,7 @@ int ItemFunctions::luaItemGetActionId(lua_State* L) { int ItemFunctions::luaItemSetActionId(lua_State* L) { // item:setActionId(actionId) uint16_t actionId = getNumber(L, 2); - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { item->setAttribute(ItemAttribute_t::ACTIONID, actionId); pushBoolean(L, true); @@ -209,7 +209,7 @@ int ItemFunctions::luaItemSetActionId(lua_State* L) { int ItemFunctions::luaItemGetCount(lua_State* L) { // item:getCount() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, item->getItemCount()); } else { @@ -220,7 +220,7 @@ int ItemFunctions::luaItemGetCount(lua_State* L) { int ItemFunctions::luaItemGetCharges(lua_State* L) { // item:getCharges() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, item->getCharges()); } else { @@ -231,7 +231,7 @@ int ItemFunctions::luaItemGetCharges(lua_State* L) { int ItemFunctions::luaItemGetFluidType(lua_State* L) { // item:getFluidType() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, static_cast(item->getAttribute(ItemAttribute_t::FLUIDTYPE))); } else { @@ -242,7 +242,7 @@ int ItemFunctions::luaItemGetFluidType(lua_State* L) { int ItemFunctions::luaItemGetWeight(lua_State* L) { // item:getWeight() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, item->getWeight()); } else { @@ -253,7 +253,7 @@ int ItemFunctions::luaItemGetWeight(lua_State* L) { int ItemFunctions::luaItemGetSubType(lua_State* L) { // item:getSubType() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { lua_pushnumber(L, item->getSubType()); } else { @@ -264,7 +264,7 @@ int ItemFunctions::luaItemGetSubType(lua_State* L) { int ItemFunctions::luaItemGetName(lua_State* L) { // item:getName() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { pushString(L, item->getName()); } else { @@ -275,7 +275,7 @@ int ItemFunctions::luaItemGetName(lua_State* L) { int ItemFunctions::luaItemGetPluralName(lua_State* L) { // item:getPluralName() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { pushString(L, item->getPluralName()); } else { @@ -286,7 +286,7 @@ int ItemFunctions::luaItemGetPluralName(lua_State* L) { int ItemFunctions::luaItemGetArticle(lua_State* L) { // item:getArticle() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { pushString(L, item->getArticle()); } else { @@ -297,7 +297,7 @@ int ItemFunctions::luaItemGetArticle(lua_State* L) { int ItemFunctions::luaItemGetPosition(lua_State* L) { // item:getPosition() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { pushPosition(L, item->getPosition()); } else { @@ -308,13 +308,13 @@ int ItemFunctions::luaItemGetPosition(lua_State* L) { int ItemFunctions::luaItemGetTile(lua_State* L) { // item:getTile() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr tile = item->getTile(); + const auto &tile = item->getTile(); if (tile) { pushUserdata(L, tile); setMetatable(L, -1, "Tile"); @@ -326,7 +326,7 @@ int ItemFunctions::luaItemGetTile(lua_State* L) { int ItemFunctions::luaItemHasAttribute(lua_State* L) { // item:hasAttribute(key) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -347,7 +347,7 @@ int ItemFunctions::luaItemHasAttribute(lua_State* L) { int ItemFunctions::luaItemGetAttribute(lua_State* L) { // item:getAttribute(key) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -379,7 +379,7 @@ int ItemFunctions::luaItemGetAttribute(lua_State* L) { int ItemFunctions::luaItemSetAttribute(lua_State* L) { // item:setAttribute(key, value) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -438,7 +438,7 @@ int ItemFunctions::luaItemSetAttribute(lua_State* L) { int ItemFunctions::luaItemRemoveAttribute(lua_State* L) { // item:removeAttribute(key) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -470,7 +470,7 @@ int ItemFunctions::luaItemRemoveAttribute(lua_State* L) { int ItemFunctions::luaItemGetCustomAttribute(lua_State* L) { // item:getCustomAttribute(key) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -496,7 +496,7 @@ int ItemFunctions::luaItemGetCustomAttribute(lua_State* L) { int ItemFunctions::luaItemSetCustomAttribute(lua_State* L) { // item:setCustomAttribute(key, value) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -537,7 +537,7 @@ int ItemFunctions::luaItemSetCustomAttribute(lua_State* L) { int ItemFunctions::luaItemRemoveCustomAttribute(lua_State* L) { // item:removeCustomAttribute(key) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -555,7 +555,7 @@ int ItemFunctions::luaItemRemoveCustomAttribute(lua_State* L) { int ItemFunctions::luaItemCanBeMoved(lua_State* L) { // item:canBeMoved() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { pushBoolean(L, item->canBeMoved()); } else { @@ -566,7 +566,7 @@ int ItemFunctions::luaItemCanBeMoved(lua_State* L) { int ItemFunctions::luaItemSerializeAttributes(lua_State* L) { // item:serializeAttributes() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { lua_pushnil(L); return 1; @@ -583,13 +583,13 @@ int ItemFunctions::luaItemSerializeAttributes(lua_State* L) { int ItemFunctions::luaItemMoveTo(lua_State* L) { // item:moveTo(position or cylinder[, flags]) - std::shared_ptr* itemPtr = getRawUserDataShared(L, 1); + const auto &itemPtr = getRawUserDataShared(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - std::shared_ptr item = *itemPtr; + const auto &item = *itemPtr; if (!item || item->isRemoved()) { lua_pushnil(L); return 1; @@ -643,13 +643,13 @@ int ItemFunctions::luaItemMoveTo(lua_State* L) { int ItemFunctions::luaItemTransform(lua_State* L) { // item:transform(itemId[, count/subType = -1]) - std::shared_ptr* itemPtr = getRawUserDataShared(L, 1); + const auto &itemPtr = getRawUserDataShared(L, 1); if (!itemPtr) { lua_pushnil(L); return 1; } - std::shared_ptr &item = *itemPtr; + auto &item = *itemPtr; if (!item) { lua_pushnil(L); return 1; @@ -680,7 +680,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { ScriptEnvironment* env = getScriptEnv(); uint32_t uid = env->addThing(item); - std::shared_ptr newItem = g_game().transformItem(item, itemId, subType); + const auto &newItem = g_game().transformItem(item, itemId, subType); if (item->isRemoved()) { env->removeItemByUID(uid); } @@ -696,7 +696,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { int ItemFunctions::luaItemDecay(lua_State* L) { // item:decay(decayId) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { if (isNumber(L, 2)) { ItemType &it = Item::items.getItemType(item->getID()); @@ -713,13 +713,13 @@ int ItemFunctions::luaItemDecay(lua_State* L) { int ItemFunctions::luaItemMoveToSlot(lua_State* L) { // item:moveToSlot(player, slot) - std::shared_ptr item = getUserdataShared(L, 1); + auto item = getUserdataShared(L, 1); if (!item || item->isRemoved()) { lua_pushnil(L); return 1; } - std::shared_ptr player = getUserdataShared(L, 2); + const auto &player = getUserdataShared(L, 2); if (!player) { lua_pushnil(L); return 1; @@ -739,7 +739,7 @@ int ItemFunctions::luaItemMoveToSlot(lua_State* L) { int ItemFunctions::luaItemGetDescription(lua_State* L) { // item:getDescription(distance) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { int32_t distance = getNumber(L, 2); pushString(L, item->getDescription(distance)); @@ -751,7 +751,7 @@ int ItemFunctions::luaItemGetDescription(lua_State* L) { int ItemFunctions::luaItemHasProperty(lua_State* L) { // item:hasProperty(property) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (item) { ItemProperty property = getNumber(L, 2); pushBoolean(L, item->hasProperty(property)); @@ -763,7 +763,7 @@ int ItemFunctions::luaItemHasProperty(lua_State* L) { int ItemFunctions::luaItemGetImbuement(lua_State* L) { // item:getImbuement() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -794,7 +794,7 @@ int ItemFunctions::luaItemGetImbuement(lua_State* L) { int ItemFunctions::luaItemGetImbuementSlot(lua_State* L) { // item:getImbuementSlot() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -808,7 +808,7 @@ int ItemFunctions::luaItemGetImbuementSlot(lua_State* L) { int ItemFunctions::luaItemSetDuration(lua_State* L) { // item:setDuration(minDuration, maxDuration = 0, decayTo = 0, showDuration = true) // Example: item:setDuration(10000, 20000, 2129, false) = random duration from range 10000/20000 - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -845,7 +845,7 @@ int ItemFunctions::luaItemSetDuration(lua_State* L) { int ItemFunctions::luaItemIsInsideDepot(lua_State* L) { // item:isInsideDepot([includeInbox = false]) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -872,7 +872,7 @@ int ItemFunctions::luaItemIsContainer(lua_State* L) { int ItemFunctions::luaItemGetTier(lua_State* L) { // item:getTier() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -885,7 +885,7 @@ int ItemFunctions::luaItemGetTier(lua_State* L) { int ItemFunctions::luaItemSetTier(lua_State* L) { // item:setTier(tier) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -899,7 +899,7 @@ int ItemFunctions::luaItemSetTier(lua_State* L) { int ItemFunctions::luaItemGetClassification(lua_State* L) { // item:getClassification() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -912,7 +912,7 @@ int ItemFunctions::luaItemGetClassification(lua_State* L) { int ItemFunctions::luaItemCanReceiveAutoCarpet(lua_State* L) { // item:canReceiveAutoCarpet() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -925,14 +925,14 @@ int ItemFunctions::luaItemCanReceiveAutoCarpet(lua_State* L) { int ItemFunctions::luaItemSetOwner(lua_State* L) { // item:setOwner(creature|creatureId) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); return 0; } if (isUserdata(L, 2)) { - std::shared_ptr creature = getUserdataShared(L, 2); + const auto &creature = getUserdataShared(L, 2); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 0; @@ -955,7 +955,7 @@ int ItemFunctions::luaItemSetOwner(lua_State* L) { int ItemFunctions::luaItemGetOwnerId(lua_State* L) { // item:getOwner() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); return 0; @@ -972,14 +972,14 @@ int ItemFunctions::luaItemGetOwnerId(lua_State* L) { int ItemFunctions::luaItemIsOwner(lua_State* L) { // item:isOwner(creature|creatureId) - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); return 0; } if (isUserdata(L, 2)) { - std::shared_ptr creature = getUserdataShared(L, 2); + const auto &creature = getUserdataShared(L, 2); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 0; @@ -1000,7 +1000,7 @@ int ItemFunctions::luaItemIsOwner(lua_State* L) { int ItemFunctions::luaItemGetOwnerName(lua_State* L) { // item:getOwnerName() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); return 0; @@ -1017,7 +1017,7 @@ int ItemFunctions::luaItemGetOwnerName(lua_State* L) { int ItemFunctions::luaItemHasOwner(lua_State* L) { // item:hasOwner() - std::shared_ptr item = getUserdataShared(L, 1); + const auto &item = getUserdataShared(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); return 1; diff --git a/src/lua/functions/items/weapon_functions.cpp b/src/lua/functions/items/weapon_functions.cpp index 61eff2dfb66..21cd0332735 100644 --- a/src/lua/functions/items/weapon_functions.cpp +++ b/src/lua/functions/items/weapon_functions.cpp @@ -14,7 +14,6 @@ #include "game/game.hpp" #include "items/item.hpp" #include "lua/scripts/lua_environment.hpp" -#include "lua/scripts/scripts.hpp" #include "utils/tools.hpp" int WeaponFunctions::luaCreateWeapon(lua_State* L) { diff --git a/src/lua/functions/lua_functions_loader.cpp b/src/lua/functions/lua_functions_loader.cpp index c2dedfb57b6..224a3b8367b 100644 --- a/src/lua/functions/lua_functions_loader.cpp +++ b/src/lua/functions/lua_functions_loader.cpp @@ -186,7 +186,7 @@ void LuaFunctionsLoader::pushVariant(lua_State* L, const LuaVariant &var) { setMetatable(L, -1, "Variant"); } -void LuaFunctionsLoader::pushThing(lua_State* L, std::shared_ptr thing) { +void LuaFunctionsLoader::pushThing(lua_State* L, const std::shared_ptr &thing) { if (validateDispatcherContext(__FUNCTION__)) { return; } @@ -200,10 +200,10 @@ void LuaFunctionsLoader::pushThing(lua_State* L, std::shared_ptr thing) { return; } - if (std::shared_ptr item = thing->getItem()) { + if (const auto &item = thing->getItem()) { pushUserdata(L, item); setItemMetatable(L, -1, item); - } else if (std::shared_ptr creature = thing->getCreature()) { + } else if (const auto &creature = thing->getCreature()) { pushUserdata(L, creature); setCreatureMetatable(L, -1, creature); } else { @@ -211,18 +211,18 @@ void LuaFunctionsLoader::pushThing(lua_State* L, std::shared_ptr thing) { } } -void LuaFunctionsLoader::pushCylinder(lua_State* L, std::shared_ptr cylinder) { +void LuaFunctionsLoader::pushCylinder(lua_State* L, const std::shared_ptr &cylinder) { if (validateDispatcherContext(__FUNCTION__)) { return; } - if (std::shared_ptr creature = cylinder->getCreature()) { + if (const auto &creature = cylinder->getCreature()) { pushUserdata(L, creature); setCreatureMetatable(L, -1, creature); - } else if (std::shared_ptr parentItem = cylinder->getItem()) { + } else if (const auto &parentItem = cylinder->getItem()) { pushUserdata(L, parentItem); setItemMetatable(L, -1, parentItem); - } else if (std::shared_ptr tile = cylinder->getTile()) { + } else if (const auto &tile = cylinder->getTile()) { pushUserdata(L, tile); setMetatable(L, -1, "Tile"); } else if (cylinder == VirtualCylinder::virtualCylinder) { @@ -250,7 +250,7 @@ void LuaFunctionsLoader::pushCallback(lua_State* L, int32_t callback) { std::string LuaFunctionsLoader::popString(lua_State* L) { if (lua_gettop(L) == 0) { - return std::string(); + return {}; } std::string str(getString(L, -1)); @@ -310,7 +310,7 @@ void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std lua_setmetatable(L, index - 1); } -void LuaFunctionsLoader::setItemMetatable(lua_State* L, int32_t index, std::shared_ptr item) { +void LuaFunctionsLoader::setItemMetatable(lua_State* L, int32_t index, const std::shared_ptr &item) { if (validateDispatcherContext(__FUNCTION__)) { return; } @@ -325,7 +325,7 @@ void LuaFunctionsLoader::setItemMetatable(lua_State* L, int32_t index, std::shar lua_setmetatable(L, index - 1); } -void LuaFunctionsLoader::setCreatureMetatable(lua_State* L, int32_t index, std::shared_ptr creature) { +void LuaFunctionsLoader::setCreatureMetatable(lua_State* L, int32_t index, const std::shared_ptr &creature) { if (validateDispatcherContext(__FUNCTION__)) { return; } @@ -392,7 +392,7 @@ std::string LuaFunctionsLoader::getString(lua_State* L, int32_t arg) { size_t len; const char* c_str = lua_tolstring(L, arg, &len); if (!c_str || len == 0) { - return std::string(); + return {}; } return std::string(c_str, len); } diff --git a/src/lua/functions/lua_functions_loader.hpp b/src/lua/functions/lua_functions_loader.hpp index e5251e3a1c3..c8176e03522 100644 --- a/src/lua/functions/lua_functions_loader.hpp +++ b/src/lua/functions/lua_functions_loader.hpp @@ -39,11 +39,11 @@ class LuaFunctionsLoader { static void reportError(const char* function, const std::string &error_desc, bool stack_trace = false); static int luaErrorHandler(lua_State* L); - static void pushThing(lua_State* L, std::shared_ptr thing); + static void pushThing(lua_State* L, const std::shared_ptr &thing); static void pushVariant(lua_State* L, const LuaVariant &var); static void pushString(lua_State* L, const std::string &value); static void pushCallback(lua_State* L, int32_t callback); - static void pushCylinder(lua_State* L, std::shared_ptr cylinder); + static void pushCylinder(lua_State* L, const std::shared_ptr &cylinder); static std::string popString(lua_State* L); static int32_t popCallback(lua_State* L); @@ -56,8 +56,8 @@ class LuaFunctionsLoader { static void setMetatable(lua_State* L, int32_t index, const std::string &name); static void setWeakMetatable(lua_State* L, int32_t index, const std::string &name); - static void setItemMetatable(lua_State* L, int32_t index, std::shared_ptr item); - static void setCreatureMetatable(lua_State* L, int32_t index, std::shared_ptr creature); + static void setItemMetatable(lua_State* L, int32_t index, const std::shared_ptr &item); + static void setCreatureMetatable(lua_State* L, int32_t index, const std::shared_ptr &creature); template static typename std::enable_if::value, T>::type diff --git a/src/lua/functions/map/house_functions.cpp b/src/lua/functions/map/house_functions.cpp index ffba0d0b5a9..af2248b255e 100644 --- a/src/lua/functions/map/house_functions.cpp +++ b/src/lua/functions/map/house_functions.cpp @@ -125,11 +125,11 @@ int HouseFunctions::luaHouseSetHouseOwner(lua_State* L) { int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { // house:setNewOwnerGuid(guid[, updateDatabase = true]) - auto house = getUserdataShared(L, 1); + const auto &house = getUserdataShared(L, 1); if (house) { auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && house->hasNewOwnership()) { - const auto player = g_game().getPlayerByGUID(house->getOwner()); + const auto &player = g_game().getPlayerByGUID(house->getOwner()); if (player) { player->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You cannot leave this house. Ownership is already scheduled to be transferred upon the next server restart."); } @@ -148,7 +148,7 @@ int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { int HouseFunctions::luaHouseHasItemOnTile(lua_State* L) { // house:hasItemOnTile() - auto house = getUserdataShared(L, 1); + const auto &house = getUserdataShared(L, 1); if (!house) { reportErrorFunc("House not found"); lua_pushnil(L); @@ -161,7 +161,7 @@ int HouseFunctions::luaHouseHasItemOnTile(lua_State* L) { int HouseFunctions::luaHouseHasNewOwnership(lua_State* L) { // house:hasNewOwnership(guid) - auto house = getUserdataShared(L, 1); + const auto &house = getUserdataShared(L, 1); if (!house) { reportErrorFunc("House not found"); lua_pushnil(L); @@ -176,8 +176,8 @@ int HouseFunctions::luaHouseHasNewOwnership(lua_State* L) { int HouseFunctions::luaHouseStartTrade(lua_State* L) { // house:startTrade(player, tradePartner) const auto &house = getUserdataShared(L, 1); - std::shared_ptr player = getUserdataShared(L, 2); - std::shared_ptr tradePartner = getUserdataShared(L, 3); + const auto &player = getUserdataShared(L, 2); + const auto &tradePartner = getUserdataShared(L, 3); if (!player || !tradePartner || !house) { lua_pushnil(L); @@ -204,7 +204,7 @@ int HouseFunctions::luaHouseStartTrade(lua_State* L) { return 1; } - std::shared_ptr transferItem = house->getTransferItem(); + const auto &transferItem = house->getTransferItem(); if (!transferItem) { lua_pushnumber(L, RETURNVALUE_YOUCANNOTTRADETHISHOUSE); return 1; @@ -235,11 +235,11 @@ int HouseFunctions::luaHouseGetBeds(lua_State* L) { return 1; } - const auto beds = house->getBeds(); + const auto &beds = house->getBeds(); lua_createtable(L, beds.size(), 0); int index = 0; - for (std::shared_ptr bedItem : beds) { + for (const auto &bedItem : beds) { pushUserdata(L, bedItem); setItemMetatable(L, -1, bedItem); lua_rawseti(L, -2, ++index); @@ -265,11 +265,11 @@ int HouseFunctions::luaHouseGetDoors(lua_State* L) { return 1; } - const auto doors = house->getDoors(); + const auto &doors = house->getDoors(); lua_createtable(L, doors.size(), 0); int index = 0; - for (std::shared_ptr door : doors) { + for (const auto &door : doors) { pushUserdata(L, door); setItemMetatable(L, -1, door); lua_rawseti(L, -2, ++index); @@ -295,7 +295,7 @@ int HouseFunctions::luaHouseGetDoorIdByPosition(lua_State* L) { return 1; } - std::shared_ptr door = house->getDoorByPosition(getPosition(L, 2)); + const auto &door = house->getDoorByPosition(getPosition(L, 2)); if (door) { lua_pushnumber(L, door->getDoorId()); } else { @@ -312,11 +312,11 @@ int HouseFunctions::luaHouseGetTiles(lua_State* L) { return 1; } - const auto tiles = house->getTiles(); + const auto &tiles = house->getTiles(); lua_newtable(L); int index = 0; - for (std::shared_ptr tile : tiles) { + for (const auto &tile : tiles) { pushUserdata(L, tile); setMetatable(L, -1, "Tile"); lua_rawseti(L, -2, ++index); @@ -332,14 +332,14 @@ int HouseFunctions::luaHouseGetItems(lua_State* L) { return 1; } - const auto tiles = house->getTiles(); + const auto &tiles = house->getTiles(); lua_newtable(L); int index = 0; - for (std::shared_ptr tile : tiles) { + for (const auto &tile : tiles) { TileItemVector* itemVector = tile->getItemList(); if (itemVector) { - for (auto &item : *itemVector) { + for (const auto &item : *itemVector) { pushUserdata(L, item); setItemMetatable(L, -1, item); lua_rawseti(L, -2, ++index); diff --git a/src/lua/functions/map/position_functions.cpp b/src/lua/functions/map/position_functions.cpp index 0e4397f3fce..34f110786a0 100644 --- a/src/lua/functions/map/position_functions.cpp +++ b/src/lua/functions/map/position_functions.cpp @@ -131,13 +131,13 @@ int PositionFunctions::luaPositionGetTile(lua_State* L) { int PositionFunctions::luaPositionGetZones(lua_State* L) { // position:getZones() const Position &position = getPosition(L, 1); - auto tile = g_game().map.getTile(position); + const auto &tile = g_game().map.getTile(position); if (tile == nullptr) { lua_pushnil(L); return 1; } int index = 0; - for (auto zone : tile->getZones()) { + for (const auto &zone : tile->getZones()) { index++; pushUserdata(L, zone); setMetatable(L, -1, "Zone"); diff --git a/src/lua/functions/map/position_functions.hpp b/src/lua/functions/map/position_functions.hpp index 095ec0667c7..e8b126c60f1 100644 --- a/src/lua/functions/map/position_functions.hpp +++ b/src/lua/functions/map/position_functions.hpp @@ -14,7 +14,7 @@ class PositionFunctions final : LuaScriptInterface { public: static void init(lua_State* L) { - registerClass(L, "Position", "", PositionFunctions::luaPositionCreate); + registerSharedClass(L, "Position", "", PositionFunctions::luaPositionCreate); registerMetaMethod(L, "Position", "__add", PositionFunctions::luaPositionAdd); registerMetaMethod(L, "Position", "__sub", PositionFunctions::luaPositionSub); registerMetaMethod(L, "Position", "__eq", PositionFunctions::luaPositionCompare); diff --git a/src/lua/functions/map/teleport_functions.cpp b/src/lua/functions/map/teleport_functions.cpp index 32fce583057..49e2ec71b1b 100644 --- a/src/lua/functions/map/teleport_functions.cpp +++ b/src/lua/functions/map/teleport_functions.cpp @@ -18,7 +18,7 @@ int TeleportFunctions::luaTeleportCreate(lua_State* L) { // Teleport(uid) uint32_t id = getNumber(L, 2); - std::shared_ptr item = getScriptEnv()->getItemByUID(id); + const auto &item = getScriptEnv()->getItemByUID(id); if (item && item->getTeleport()) { pushUserdata(L, item); setMetatable(L, -1, "Teleport"); @@ -30,7 +30,7 @@ int TeleportFunctions::luaTeleportCreate(lua_State* L) { int TeleportFunctions::luaTeleportGetDestination(lua_State* L) { // teleport:getDestination() - std::shared_ptr teleport = getUserdataShared(L, 1); + const auto &teleport = getUserdataShared(L, 1); if (teleport) { pushPosition(L, teleport->getDestPos()); } else { @@ -41,7 +41,7 @@ int TeleportFunctions::luaTeleportGetDestination(lua_State* L) { int TeleportFunctions::luaTeleportSetDestination(lua_State* L) { // teleport:setDestination(position) - std::shared_ptr teleport = getUserdataShared(L, 1); + const auto &teleport = getUserdataShared(L, 1); if (teleport) { teleport->setDestPos(getPosition(L, 2)); pushBoolean(L, true); diff --git a/src/lua/functions/map/tile_functions.cpp b/src/lua/functions/map/tile_functions.cpp index cdd82abda8c..cfd3e5149bf 100644 --- a/src/lua/functions/map/tile_functions.cpp +++ b/src/lua/functions/map/tile_functions.cpp @@ -36,7 +36,7 @@ int TileFunctions::luaTileCreate(lua_State* L) { int TileFunctions::luaTileGetPosition(lua_State* L) { // tile:getPosition() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (tile) { pushPosition(L, tile->getPosition()); } else { @@ -47,7 +47,7 @@ int TileFunctions::luaTileGetPosition(lua_State* L) { int TileFunctions::luaTileGetGround(lua_State* L) { // tile:getGround() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (tile && tile->getGround()) { pushUserdata(L, tile->getGround()); setItemMetatable(L, -1, tile->getGround()); @@ -60,22 +60,22 @@ int TileFunctions::luaTileGetGround(lua_State* L) { int TileFunctions::luaTileGetThing(lua_State* L) { // tile:getThing(index) int32_t index = getNumber(L, 2); - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr thing = tile->getThing(index); + const auto &thing = tile->getThing(index); if (!thing) { lua_pushnil(L); return 1; } - if (std::shared_ptr creature = thing->getCreature()) { + if (const auto &creature = thing->getCreature()) { pushUserdata(L, creature); setCreatureMetatable(L, -1, creature); - } else if (std::shared_ptr item = thing->getItem()) { + } else if (const auto &item = thing->getItem()) { pushUserdata(L, item); setItemMetatable(L, -1, item); } else { @@ -86,7 +86,7 @@ int TileFunctions::luaTileGetThing(lua_State* L) { int TileFunctions::luaTileGetThingCount(lua_State* L) { // tile:getThingCount() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (tile) { lua_pushnumber(L, tile->getThingCount()); } else { @@ -97,23 +97,23 @@ int TileFunctions::luaTileGetThingCount(lua_State* L) { int TileFunctions::luaTileGetTopVisibleThing(lua_State* L) { // tile:getTopVisibleThing(creature) - std::shared_ptr creature = getCreature(L, 2); - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &creature = getCreature(L, 2); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr thing = tile->getTopVisibleThing(creature); + const auto &thing = tile->getTopVisibleThing(creature); if (!thing) { lua_pushnil(L); return 1; } - if (std::shared_ptr visibleCreature = thing->getCreature()) { + if (const auto &visibleCreature = thing->getCreature()) { pushUserdata(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); - } else if (std::shared_ptr visibleItem = thing->getItem()) { + } else if (const auto &visibleItem = thing->getItem()) { pushUserdata(L, visibleItem); setItemMetatable(L, -1, visibleItem); } else { @@ -124,13 +124,13 @@ int TileFunctions::luaTileGetTopVisibleThing(lua_State* L) { int TileFunctions::luaTileGetTopTopItem(lua_State* L) { // tile:getTopTopItem() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr item = tile->getTopTopItem(); + const auto &item = tile->getTopTopItem(); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -142,13 +142,13 @@ int TileFunctions::luaTileGetTopTopItem(lua_State* L) { int TileFunctions::luaTileGetTopDownItem(lua_State* L) { // tile:getTopDownItem() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr item = tile->getTopDownItem(); + const auto &item = tile->getTopDownItem(); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -160,13 +160,13 @@ int TileFunctions::luaTileGetTopDownItem(lua_State* L) { int TileFunctions::luaTileGetFieldItem(lua_State* L) { // tile:getFieldItem() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr item = tile->getFieldItem(); + const auto &item = tile->getFieldItem(); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -178,7 +178,7 @@ int TileFunctions::luaTileGetFieldItem(lua_State* L) { int TileFunctions::luaTileGetItemById(lua_State* L) { // tile:getItemById(itemId[, subType = -1]) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -196,7 +196,7 @@ int TileFunctions::luaTileGetItemById(lua_State* L) { } int32_t subType = getNumber(L, 3, -1); - std::shared_ptr item = g_game().findItemOfType(tile, itemId, false, subType); + const auto &item = g_game().findItemOfType(tile, itemId, false, subType); if (item) { pushUserdata(L, item); setItemMetatable(L, -1, item); @@ -208,7 +208,7 @@ int TileFunctions::luaTileGetItemById(lua_State* L) { int TileFunctions::luaTileGetItemByType(lua_State* L) { // tile:getItemByType(itemType) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -246,7 +246,7 @@ int TileFunctions::luaTileGetItemByType(lua_State* L) { return 1; } - if (std::shared_ptr item = tile->getGround()) { + if (const auto &item = tile->getGround()) { const ItemType &it = Item::items[item->getID()]; if (it.type == itemType) { pushUserdata(L, item); @@ -272,7 +272,7 @@ int TileFunctions::luaTileGetItemByType(lua_State* L) { int TileFunctions::luaTileGetItemByTopOrder(lua_State* L) { // tile:getItemByTopOrder(topOrder) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -280,7 +280,7 @@ int TileFunctions::luaTileGetItemByTopOrder(lua_State* L) { int32_t topOrder = getNumber(L, 2); - std::shared_ptr item = tile->getItemByTopOrder(topOrder); + const auto &item = tile->getItemByTopOrder(topOrder); if (!item) { lua_pushnil(L); return 1; @@ -293,7 +293,7 @@ int TileFunctions::luaTileGetItemByTopOrder(lua_State* L) { int TileFunctions::luaTileGetItemCountById(lua_State* L) { // tile:getItemCountById(itemId[, subType = -1]) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -318,13 +318,13 @@ int TileFunctions::luaTileGetItemCountById(lua_State* L) { int TileFunctions::luaTileGetBottomCreature(lua_State* L) { // tile:getBottomCreature() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr creature = tile->getBottomCreature(); + const auto &creature = tile->getBottomCreature(); if (!creature) { lua_pushnil(L); return 1; @@ -337,13 +337,13 @@ int TileFunctions::luaTileGetBottomCreature(lua_State* L) { int TileFunctions::luaTileGetTopCreature(lua_State* L) { // tile:getTopCreature() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr creature = tile->getTopCreature(); + const auto &creature = tile->getTopCreature(); if (!creature) { lua_pushnil(L); return 1; @@ -356,19 +356,19 @@ int TileFunctions::luaTileGetTopCreature(lua_State* L) { int TileFunctions::luaTileGetBottomVisibleCreature(lua_State* L) { // tile:getBottomVisibleCreature(creature) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr visibleCreature = tile->getBottomVisibleCreature(creature); + const auto &visibleCreature = tile->getBottomVisibleCreature(creature); if (visibleCreature) { pushUserdata(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); @@ -380,19 +380,19 @@ int TileFunctions::luaTileGetBottomVisibleCreature(lua_State* L) { int TileFunctions::luaTileGetTopVisibleCreature(lua_State* L) { // tile:getTopVisibleCreature(creature) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr visibleCreature = tile->getTopVisibleCreature(creature); + const auto &visibleCreature = tile->getTopVisibleCreature(creature); if (visibleCreature) { pushUserdata(L, visibleCreature); setCreatureMetatable(L, -1, visibleCreature); @@ -404,7 +404,7 @@ int TileFunctions::luaTileGetTopVisibleCreature(lua_State* L) { int TileFunctions::luaTileGetItems(lua_State* L) { // tile:getItems() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -429,7 +429,7 @@ int TileFunctions::luaTileGetItems(lua_State* L) { int TileFunctions::luaTileGetItemCount(lua_State* L) { // tile:getItemCount() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -441,7 +441,7 @@ int TileFunctions::luaTileGetItemCount(lua_State* L) { int TileFunctions::luaTileGetDownItemCount(lua_State* L) { // tile:getDownItemCount() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (tile) { lua_pushnumber(L, tile->getDownItemCount()); } else { @@ -452,7 +452,7 @@ int TileFunctions::luaTileGetDownItemCount(lua_State* L) { int TileFunctions::luaTileGetTopItemCount(lua_State* L) { // tile:getTopItemCount() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -464,7 +464,7 @@ int TileFunctions::luaTileGetTopItemCount(lua_State* L) { int TileFunctions::luaTileGetCreatures(lua_State* L) { // tile:getCreatures() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -489,7 +489,7 @@ int TileFunctions::luaTileGetCreatures(lua_State* L) { int TileFunctions::luaTileGetCreatureCount(lua_State* L) { // tile:getCreatureCount() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -501,7 +501,7 @@ int TileFunctions::luaTileGetCreatureCount(lua_State* L) { int TileFunctions::luaTileHasProperty(lua_State* L) { // tile:hasProperty(property[, item]) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -525,13 +525,13 @@ int TileFunctions::luaTileHasProperty(lua_State* L) { int TileFunctions::luaTileGetThingIndex(lua_State* L) { // tile:getThingIndex(thing) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr thing = getThing(L, 2); + const auto &thing = getThing(L, 2); if (thing) { lua_pushnumber(L, tile->getThingIndex(thing)); } else { @@ -542,7 +542,7 @@ int TileFunctions::luaTileGetThingIndex(lua_State* L) { int TileFunctions::luaTileHasFlag(lua_State* L) { // tile:hasFlag(flag) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (tile) { TileFlags_t flag = getNumber(L, 2); pushBoolean(L, tile->hasFlag(flag)); @@ -554,13 +554,13 @@ int TileFunctions::luaTileHasFlag(lua_State* L) { int TileFunctions::luaTileQueryAdd(lua_State* L) { // tile:queryAdd(thing[, flags]) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - std::shared_ptr thing = getThing(L, 2); + const auto &thing = getThing(L, 2); if (thing) { uint32_t flags = getNumber(L, 3, 0); lua_pushnumber(L, tile->queryAdd(0, thing, 1, flags)); @@ -572,7 +572,7 @@ int TileFunctions::luaTileQueryAdd(lua_State* L) { int TileFunctions::luaTileAddItem(lua_State* L) { // tile:addItem(itemId[, count/subType = 1[, flags = 0]]) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -591,7 +591,7 @@ int TileFunctions::luaTileAddItem(lua_State* L) { uint32_t subType = getNumber(L, 3, 1); - std::shared_ptr item = Item::CreateItem(itemId, std::min(subType, Item::items[itemId].stackSize)); + const auto &item = Item::CreateItem(itemId, std::min(subType, Item::items[itemId].stackSize)); if (!item) { lua_pushnil(L); return 1; @@ -612,13 +612,13 @@ int TileFunctions::luaTileAddItem(lua_State* L) { int TileFunctions::luaTileAddItemEx(lua_State* L) { // tile:addItemEx(item[, flags = 0]) - std::shared_ptr item = getUserdataShared(L, 2); + const auto &item = getUserdataShared(L, 2); if (!item) { lua_pushnil(L); return 1; } - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; @@ -641,13 +641,13 @@ int TileFunctions::luaTileAddItemEx(lua_State* L) { int TileFunctions::luaTileGetHouse(lua_State* L) { // tile:getHouse() - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; } - if (std::shared_ptr houseTile = std::dynamic_pointer_cast(tile)) { + if (const auto &houseTile = std::dynamic_pointer_cast(tile)) { pushUserdata(L, houseTile->getHouse()); setMetatable(L, -1, "House"); } else { @@ -658,7 +658,7 @@ int TileFunctions::luaTileGetHouse(lua_State* L) { int TileFunctions::luaTileSweep(lua_State* L) { // tile:sweep(actor) - std::shared_ptr tile = getUserdataShared(L, 1); + const auto &tile = getUserdataShared(L, 1); if (!tile) { lua_pushnil(L); return 1; diff --git a/src/lua/global/baseevents.cpp b/src/lua/global/baseevents.cpp index 3b312100d3b..d1bcaf4f191 100644 --- a/src/lua/global/baseevents.cpp +++ b/src/lua/global/baseevents.cpp @@ -41,7 +41,7 @@ bool BaseEvents::loadFromXml() { loaded = true; for (auto node : doc.child(scriptsName.c_str()).children()) { - Event_ptr event = getEvent(node.name()); + const auto &event = getEvent(node.name()); if (!event) { continue; } @@ -66,7 +66,7 @@ bool BaseEvents::loadFromXml() { } if (success) { - registerEvent(std::move(event), node); + registerEvent(event, node); } } return true; @@ -74,7 +74,7 @@ bool BaseEvents::loadFromXml() { bool BaseEvents::reload() { loaded = false; - clear(false); + clear(); return loadFromXml(); } diff --git a/src/lua/global/baseevents.hpp b/src/lua/global/baseevents.hpp index 48e2d104a92..9fe5c79b2ea 100644 --- a/src/lua/global/baseevents.hpp +++ b/src/lua/global/baseevents.hpp @@ -12,7 +12,7 @@ #include "lua/scripts/luascript.hpp" class Event; -using Event_ptr = std::unique_ptr; +using Event_ptr = std::shared_ptr; /** * @brief Class that describes an event @@ -147,8 +147,8 @@ class BaseEvents { virtual LuaScriptInterface &getScriptInterface() = 0; virtual std::string getScriptBaseName() const = 0; virtual Event_ptr getEvent(const std::string &nodeName) = 0; - virtual bool registerEvent(Event_ptr event, const pugi::xml_node &node) = 0; - virtual void clear(bool) = 0; + virtual bool registerEvent(const Event_ptr &event, const pugi::xml_node &node) = 0; + virtual void clear() = 0; bool loaded = false; diff --git a/src/lua/global/globalevent.cpp b/src/lua/global/globalevent.cpp index a9d589a1f76..a564313b443 100644 --- a/src/lua/global/globalevent.cpp +++ b/src/lua/global/globalevent.cpp @@ -30,7 +30,7 @@ void GlobalEvents::clear() { timerMap.clear(); } -bool GlobalEvents::registerLuaEvent(const std::shared_ptr globalEvent) { +bool GlobalEvents::registerLuaEvent(const std::shared_ptr &globalEvent) { if (globalEvent->getEventType() == GLOBALEVENT_TIMER) { auto result = timerMap.emplace(globalEvent->getName(), globalEvent); if (result.second) { @@ -206,20 +206,20 @@ std::string GlobalEvent::getScriptTypeName() const { return "onSave"; default: g_logger().error("[GlobalEvent::getScriptTypeName] - Invalid event type"); - return std::string(); + return {}; } } bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightInfo) const { // onPeriodChange(lightState, lightTime) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executePeriodChange - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -232,14 +232,14 @@ bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightIn bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { // onRecord(current, old) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executeRecord - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -251,14 +251,14 @@ bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { } bool GlobalEvent::executeEvent() const { - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executeEvent - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); diff --git a/src/lua/global/globalevent.hpp b/src/lua/global/globalevent.hpp index 128a743b3fb..9298ef38bad 100644 --- a/src/lua/global/globalevent.hpp +++ b/src/lua/global/globalevent.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "utils/utils_definitions.hpp" #include "lua/scripts/scripts.hpp" @@ -38,7 +40,7 @@ class GlobalEvents final : public Scripts { GlobalEventMap getEventMap(GlobalEvent_t type); - bool registerLuaEvent(const std::shared_ptr globalEvent); + bool registerLuaEvent(const std::shared_ptr &globalEvent); void clear(); private: @@ -67,7 +69,7 @@ class GlobalEvent final : public Script { return name; } void setName(std::string eventName) { - name = eventName; + name = std::move(eventName); } uint32_t getInterval() const { return interval; diff --git a/src/lua/modules/modules.cpp b/src/lua/modules/modules.cpp index 8b79524ec2c..fcbdd99fdc3 100644 --- a/src/lua/modules/modules.cpp +++ b/src/lua/modules/modules.cpp @@ -18,10 +18,10 @@ Modules::Modules() : scriptInterface.initState(); } -void Modules::clear(bool) { +void Modules::clear() { // clear recvbyte list - for (auto &it : recvbyteList) { - it.second.clearEvent(); + for (const auto &it : recvbyteList) { + it.second->clearEvent(); } // clear lua state @@ -40,54 +40,55 @@ Event_ptr Modules::getEvent(const std::string &nodeName) { if (strcasecmp(nodeName.c_str(), "module") != 0) { return nullptr; } - return Event_ptr(new Module(&scriptInterface)); + return std::make_unique(&scriptInterface); } -bool Modules::registerEvent(Event_ptr event, const pugi::xml_node &) { - Module_ptr module { static_cast(event.release()) }; +bool Modules::registerEvent(const Event_ptr &event, const pugi::xml_node &) { + auto module = std::dynamic_pointer_cast(event); if (module->getEventType() == MODULE_TYPE_NONE) { g_logger().error("Trying to register event without type!"); return false; } - Module* oldModule = getEventByRecvbyte(module->getRecvbyte(), false); + auto oldModule = getEventByRecvbyte(module->getRecvbyte(), false); if (oldModule) { if (!oldModule->isLoaded() && oldModule->getEventType() == module->getEventType()) { - oldModule->copyEvent(module.get()); + oldModule->copyEvent(module); + return true; } return false; + } + + auto it = recvbyteList.find(module->getRecvbyte()); + if (it != recvbyteList.end()) { + it->second = module; } else { - auto it = recvbyteList.find(module->getRecvbyte()); - if (it != recvbyteList.end()) { - it->second = *module; - } else { - recvbyteList.emplace(module->getRecvbyte(), std::move(*module)); - } - return true; + recvbyteList.emplace(module->getRecvbyte(), module); } + return true; } -Module* Modules::getEventByRecvbyte(uint8_t recvbyte, bool force) { - ModulesList::iterator it = recvbyteList.find(recvbyte); +Module_ptr Modules::getEventByRecvbyte(uint8_t recvbyte, bool force) { + auto it = recvbyteList.find(recvbyte); if (it != recvbyteList.end()) { - if (!force || it->second.isLoaded()) { - return &it->second; + if (!force || it->second->isLoaded()) { + return it->second; } } return nullptr; } void Modules::executeOnRecvbyte(uint32_t playerId, NetworkMessage &msg, uint8_t byte) const { - std::shared_ptr player = g_game().getPlayerByID(playerId); + auto player = g_game().getPlayerByID(playerId); if (!player) { return; } - for (auto &it : recvbyteList) { - Module module = it.second; - if (module.getEventType() == MODULE_TYPE_RECVBYTE && module.getRecvbyte() == byte && player->canRunModule(module.getRecvbyte())) { - player->setModuleDelay(module.getRecvbyte(), module.getDelay()); - module.executeOnRecvbyte(player, msg); + for (const auto &it : recvbyteList) { + auto &module = it.second; + if (module->getEventType() == MODULE_TYPE_RECVBYTE && module->getRecvbyte() == byte && player->canRunModule(module->getRecvbyte())) { + player->setModuleDelay(module->getRecvbyte(), module->getDelay()); + module->executeOnRecvbyte(player, msg); return; } } @@ -99,15 +100,15 @@ Module::Module(LuaScriptInterface* interface) : bool Module::configureEvent(const pugi::xml_node &node) { delay = 0; - pugi::xml_attribute typeAttribute = node.attribute("type"); + auto typeAttribute = node.attribute("type"); if (!typeAttribute) { g_logger().error("Missing type for module."); return false; } - std::string tmpStr = asLowerCaseString(typeAttribute.as_string()); + auto tmpStr = asLowerCaseString(typeAttribute.as_string()); if (tmpStr == "recvbyte") { - pugi::xml_attribute byteAttribute = node.attribute("byte"); + auto byteAttribute = node.attribute("byte"); if (!byteAttribute) { g_logger().error("Missing byte for module typed recvbyte."); return false; @@ -120,9 +121,9 @@ bool Module::configureEvent(const pugi::xml_node &node) { return false; } - pugi::xml_attribute delayAttribute = node.attribute("delay"); + auto delayAttribute = node.attribute("delay"); if (delayAttribute) { - delay = static_cast(delayAttribute.as_uint()); + delay = static_cast(delayAttribute.as_uint()); } loaded = true; @@ -134,11 +135,11 @@ std::string Module::getScriptEventName() const { case MODULE_TYPE_RECVBYTE: return "onRecvbyte"; default: - return std::string(); + return {}; } } -void Module::copyEvent(Module* module) { +void Module::copyEvent(const Module_ptr &module) { scriptId = module->scriptId; scriptInterface = module->scriptInterface; scripted = module->scripted; @@ -152,14 +153,13 @@ void Module::clearEvent() { loaded = false; } -void Module::executeOnRecvbyte(std::shared_ptr player, NetworkMessage &msg) { - // onRecvbyte(player, msg, recvbyte) - if (!scriptInterface->reserveScriptEnv()) { +void Module::executeOnRecvbyte(const std::shared_ptr &player, NetworkMessage &msg) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("Call stack overflow. Too many lua script calls being nested {}", player->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); diff --git a/src/lua/modules/modules.hpp b/src/lua/modules/modules.hpp index 6543138d515..62cc736fbfa 100644 --- a/src/lua/modules/modules.hpp +++ b/src/lua/modules/modules.hpp @@ -16,7 +16,7 @@ #include "server/network/message/networkmessage.hpp" class Module; -using Module_ptr = std::unique_ptr; +using Module_ptr = std::shared_ptr; class Module final : public Event { public: @@ -32,17 +32,17 @@ class Module final : public Event { } void clearEvent(); - void copyEvent(Module* creatureEvent); + void copyEvent(const Module_ptr &creatureEvent); // scripting - void executeOnRecvbyte(std::shared_ptr player, NetworkMessage &msg); + void executeOnRecvbyte(const std::shared_ptr &player, NetworkMessage &msg); // - uint8_t getRecvbyte() { + uint8_t getRecvbyte() const { return recvbyte; } - int16_t getDelay() { + int16_t getDelay() const { return delay; } @@ -50,8 +50,8 @@ class Module final : public Event { std::string getScriptEventName() const final; ModuleType_t type; - uint8_t recvbyte; - int16_t delay; + uint8_t recvbyte {}; + int16_t delay {}; bool loaded; }; @@ -68,16 +68,16 @@ class Modules final : public BaseEvents { } void executeOnRecvbyte(uint32_t playerId, NetworkMessage &msg, uint8_t byte) const; - Module* getEventByRecvbyte(uint8_t recvbyte, bool force); + Module_ptr getEventByRecvbyte(uint8_t recvbyte, bool force); protected: LuaScriptInterface &getScriptInterface() override; std::string getScriptBaseName() const override; Event_ptr getEvent(const std::string &nodeName) override; - bool registerEvent(Event_ptr event, const pugi::xml_node &node) override; - void clear(bool) override final; + bool registerEvent(const Event_ptr &event, const pugi::xml_node &node) override; + void clear() override final; - typedef std::map ModulesList; + using ModulesList = std::map; ModulesList recvbyteList; LuaScriptInterface scriptInterface; diff --git a/src/lua/scripts/lua_environment.hpp b/src/lua/scripts/lua_environment.hpp index b467599cad4..d6611249f61 100644 --- a/src/lua/scripts/lua_environment.hpp +++ b/src/lua/scripts/lua_environment.hpp @@ -89,7 +89,7 @@ class LuaEnvironment : public LuaScriptInterface { private: void executeTimerEvent(uint32_t eventIndex); - phmap::flat_hash_map timerEvents; + std::unordered_map timerEvents; uint32_t lastEventTimerId = 1; phmap::flat_hash_map> areaMap; @@ -100,8 +100,8 @@ class LuaEnvironment : public LuaScriptInterface { phmap::flat_hash_map> combatIdMap; uint32_t lastCombatId = 0; - phmap::flat_hash_map> weaponMap; - phmap::flat_hash_map> weaponIdMap; + std::unordered_map> weaponMap; + std::unordered_map> weaponIdMap; uint32_t lastWeaponId = 0; LuaScriptInterface* testInterface = nullptr; diff --git a/src/lua/scripts/script_environment.cpp b/src/lua/scripts/script_environment.cpp index 4a7ad7acd94..80dcbb7ce97 100644 --- a/src/lua/scripts/script_environment.cpp +++ b/src/lua/scripts/script_environment.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "game/game.hpp" @@ -41,7 +43,7 @@ bool ScriptEnvironment::setCallbackId(int32_t newCallbackId, LuaScriptInterface* if (this->callbackId != 0) { // nested callbacks are not allowed if (interface) { - interface->reportErrorFunc("Nested callbacks!"); + LuaScriptInterface::reportErrorFunc("Nested callbacks!"); } return false; } @@ -58,17 +60,17 @@ void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface*&r retTimerEvent = this->timerEvent; } -uint32_t ScriptEnvironment::addThing(std::shared_ptr thing) { +uint32_t ScriptEnvironment::addThing(const std::shared_ptr &thing) { if (!thing || thing->isRemoved()) { return 0; } - std::shared_ptr creature = thing->getCreature(); + const auto &creature = thing->getCreature(); if (creature) { return creature->getID(); } - std::shared_ptr item = thing->getItem(); + const auto &item = thing->getItem(); if (item && item->hasAttribute(ItemAttribute_t::UNIQUEID)) { return item->getAttribute(ItemAttribute_t::UNIQUEID); } @@ -96,7 +98,7 @@ std::shared_ptr ScriptEnvironment::getThingByUID(uint32_t uid) { } if (uid <= std::numeric_limits::max()) { - std::shared_ptr item = g_game().getUniqueItem(static_cast(uid)); + const auto &item = g_game().getUniqueItem(static_cast(uid)); if (item && !item->isRemoved()) { return item; } @@ -105,7 +107,7 @@ std::shared_ptr ScriptEnvironment::getThingByUID(uint32_t uid) { auto it = localMap.find(uid); if (it != localMap.end()) { - std::shared_ptr item = it->second; + const auto &item = it->second; if (!item->isRemoved()) { return item; } @@ -114,7 +116,7 @@ std::shared_ptr ScriptEnvironment::getThingByUID(uint32_t uid) { } std::shared_ptr ScriptEnvironment::getItemByUID(uint32_t uid) { - std::shared_ptr thing = getThingByUID(uid); + const auto &thing = getThingByUID(uid); if (!thing) { return nullptr; } @@ -122,7 +124,7 @@ std::shared_ptr ScriptEnvironment::getItemByUID(uint32_t uid) { } std::shared_ptr ScriptEnvironment::getContainerByUID(uint32_t uid) { - std::shared_ptr item = getItemByUID(uid); + const auto &item = getItemByUID(uid); if (!item) { return nullptr; } @@ -141,11 +143,11 @@ void ScriptEnvironment::removeItemByUID(uint32_t uid) { } } -void ScriptEnvironment::addTempItem(std::shared_ptr item) { +void ScriptEnvironment::addTempItem(const std::shared_ptr &item) { tempItems.emplace(this, item); } -void ScriptEnvironment::removeTempItem(std::shared_ptr item) { +void ScriptEnvironment::removeTempItem(const std::shared_ptr &item) { for (auto it = tempItems.begin(), end = tempItems.end(); it != end; ++it) { if (it->second == item) { tempItems.erase(it); @@ -155,7 +157,7 @@ void ScriptEnvironment::removeTempItem(std::shared_ptr item) { } uint32_t ScriptEnvironment::addResult(DBResult_ptr res) { - tempResults[++lastResultId] = res; + tempResults[++lastResultId] = std::move(res); return lastResultId; } diff --git a/src/lua/scripts/script_environment.hpp b/src/lua/scripts/script_environment.hpp index fe89d3f1e5d..3e22693851a 100644 --- a/src/lua/scripts/script_environment.hpp +++ b/src/lua/scripts/script_environment.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "database/database.hpp" #include "declarations.hpp" @@ -52,9 +54,9 @@ class ScriptEnvironment { void getEventInfo(int32_t &scriptId, LuaScriptInterface*&scriptInterface, int32_t &callbackId, bool &timerEvent) const; - void addTempItem(std::shared_ptr item); - static void removeTempItem(std::shared_ptr item); - uint32_t addThing(std::shared_ptr thing); + void addTempItem(const std::shared_ptr &item); + static void removeTempItem(const std::shared_ptr &item); + uint32_t addThing(const std::shared_ptr &thing); void insertItem(uint32_t uid, std::shared_ptr item); static DBResult_ptr getResultByID(uint32_t id); @@ -62,7 +64,7 @@ class ScriptEnvironment { static bool removeResult(uint32_t id); void setNpc(std::shared_ptr npc) { - curNpc = npc; + curNpc = std::move(npc); } std::shared_ptr getNpc() const { return curNpc; @@ -77,7 +79,7 @@ class ScriptEnvironment { using StorageMap = std::map; using DBResultMap = std::map; - LuaScriptInterface* interface; + LuaScriptInterface* interface {}; // for npc scripts std::shared_ptr curNpc = nullptr; @@ -90,9 +92,9 @@ class ScriptEnvironment { uint32_t lastUID = std::numeric_limits::max(); // script file id - int32_t scriptId; - int32_t callbackId; - bool timerEvent; + int32_t scriptId {}; + int32_t callbackId {}; + bool timerEvent {}; // result map static uint32_t lastResultId; diff --git a/src/lua/scripts/scripts.cpp b/src/lua/scripts/scripts.cpp index cb92c1cc29a..b42e74ca3fb 100644 --- a/src/lua/scripts/scripts.cpp +++ b/src/lua/scripts/scripts.cpp @@ -72,7 +72,7 @@ bool Scripts::loadScripts(std::string loadPath, bool isLib, bool reload) { // Recursive iterate through all entries in the directory for (const auto &entry : std::filesystem::recursive_directory_iterator(dir)) { // Get the filename of the entry as a string - const auto realPath = entry.path(); + const auto &realPath = entry.path(); std::string fileFolder = realPath.parent_path().filename().string(); // Script folder, example: "actions" std::string scriptFolder = realPath.parent_path().string(); diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 032b9b512d0..60d9b3f74a1 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -1661,7 +1661,7 @@ void ProtocolGame::parseSetOutfit(NetworkMessage &msg) { } uint16_t startBufferPosition = msg.getBufferPosition(); - Module* outfitModule = g_modules().getEventByRecvbyte(0xD3, false); + const auto &outfitModule = g_modules().getEventByRecvbyte(0xD3, false); if (outfitModule) { outfitModule->executeOnRecvbyte(player, msg); } From db4565db3eb85c9222f047b7ee66959c6573f4e4 Mon Sep 17 00:00:00 2001 From: Beats Date: Mon, 29 Jul 2024 22:00:36 -0300 Subject: [PATCH 02/34] up --- .../monster/gaz_haragoth_heal.lua | 42 +- src/account/account.cpp | 2 +- src/creatures/combat/combat.cpp | 156 ++--- src/creatures/combat/combat.hpp | 104 +-- src/creatures/combat/condition.cpp | 72 +- src/creatures/combat/condition.hpp | 38 +- src/creatures/combat/spells.cpp | 58 +- src/creatures/combat/spells.hpp | 50 +- src/creatures/creature.cpp | 46 +- src/creatures/creature.hpp | 56 +- src/creatures/creatures_definitions.hpp | 33 +- src/creatures/interactions/chat.cpp | 30 +- src/creatures/interactions/chat.hpp | 8 +- src/creatures/monsters/monster.cpp | 24 +- src/creatures/monsters/monster.hpp | 18 +- src/creatures/monsters/monsters.cpp | 8 +- src/creatures/monsters/monsters.hpp | 14 +- .../monsters/spawns/spawn_monster.cpp | 6 +- .../monsters/spawns/spawn_monster.hpp | 6 +- src/creatures/npcs/npc.cpp | 24 +- src/creatures/npcs/npc.hpp | 18 +- src/creatures/npcs/npcs.cpp | 2 +- src/creatures/npcs/npcs.hpp | 2 +- src/creatures/npcs/spawns/spawn_npc.cpp | 2 +- src/creatures/npcs/spawns/spawn_npc.hpp | 4 +- .../players/cyclopedia/player_badge.hpp | 2 +- .../players/cyclopedia/player_cyclopedia.cpp | 4 +- src/creatures/players/grouping/party.cpp | 46 +- src/creatures/players/grouping/party.hpp | 40 +- .../players/imbuements/imbuements.cpp | 8 +- .../players/imbuements/imbuements.hpp | 8 +- src/creatures/players/management/ban.cpp | 4 +- src/creatures/players/management/waitlist.cpp | 6 +- src/creatures/players/management/waitlist.hpp | 6 +- src/creatures/players/player.cpp | 256 ++++---- src/creatures/players/player.hpp | 292 +++++---- src/creatures/players/vip/player_vip.cpp | 14 +- src/creatures/players/vip/player_vip.hpp | 12 +- src/creatures/players/vocations/vocation.cpp | 6 +- src/creatures/players/wheel/player_wheel.cpp | 22 +- src/creatures/players/wheel/player_wheel.hpp | 14 +- src/creatures/players/wheel/wheel_gems.hpp | 2 +- src/database/database.cpp | 10 +- src/database/database.hpp | 15 +- src/database/databasetasks.cpp | 4 +- src/database/databasetasks.hpp | 4 +- src/game/bank/bank.cpp | 14 +- src/game/bank/bank.hpp | 10 +- src/game/game.cpp | 614 +++++++++--------- src/game/game.hpp | 253 ++++---- src/game/movement/teleport.cpp | 4 +- src/game/movement/teleport.hpp | 6 +- src/game/scheduling/dispatcher.cpp | 8 +- src/game/scheduling/dispatcher.hpp | 10 +- src/game/scheduling/events_scheduler.hpp | 2 +- src/game/scheduling/task.cpp | 27 +- src/game/scheduling/task.hpp | 29 +- src/game/zones/zone.hpp | 8 +- src/io/fileloader.hpp | 6 +- src/io/functions/iologindata_load_player.cpp | 100 +-- src/io/functions/iologindata_load_player.hpp | 56 +- src/io/functions/iologindata_save_player.cpp | 38 +- src/io/functions/iologindata_save_player.hpp | 30 +- src/io/io_bosstiary.cpp | 10 +- src/io/io_bosstiary.hpp | 4 +- src/io/iobestiary.cpp | 30 +- src/io/iobestiary.hpp | 30 +- src/io/ioguild.cpp | 4 +- src/io/ioguild.hpp | 2 +- src/io/iologindata.cpp | 14 +- src/io/iologindata.hpp | 10 +- src/io/iomap.cpp | 2 +- src/io/iomap.hpp | 6 +- src/io/iomapserialize.cpp | 16 +- src/io/iomapserialize.hpp | 8 +- src/io/iomarket.cpp | 16 +- src/io/iomarket.hpp | 2 +- src/io/ioprey.cpp | 6 +- src/io/ioprey.hpp | 6 +- src/items/bed.cpp | 16 +- src/items/bed.hpp | 20 +- src/items/containers/container.cpp | 70 +- src/items/containers/container.hpp | 62 +- src/items/containers/depot/depotchest.cpp | 2 +- src/items/containers/depot/depotlocker.cpp | 2 +- src/items/containers/depot/depotlocker.hpp | 2 +- src/items/containers/inbox/inbox.cpp | 2 +- src/items/containers/mailbox/mailbox.cpp | 18 +- src/items/containers/mailbox/mailbox.hpp | 8 +- src/items/containers/rewards/reward.cpp | 2 +- src/items/decay/decay.cpp | 8 +- src/items/decay/decay.hpp | 6 +- src/items/functions/item/attribute.cpp | 2 +- src/items/functions/item/attribute.hpp | 26 +- src/items/functions/item/custom_attribute.cpp | 18 +- src/items/functions/item/custom_attribute.hpp | 8 +- src/items/functions/item/item_parse.cpp | 112 ++-- src/items/functions/item/item_parse.hpp | 2 +- src/items/item.cpp | 36 +- src/items/item.hpp | 54 +- src/items/items.cpp | 8 +- src/items/items.hpp | 6 +- src/items/items_classification.hpp | 2 +- src/items/items_definitions.hpp | 2 +- src/items/tile.cpp | 132 ++-- src/items/tile.hpp | 62 +- src/items/trashholder.cpp | 4 +- src/items/trashholder.hpp | 2 +- src/items/weapons/weapons.cpp | 32 +- src/items/weapons/weapons.hpp | 28 +- src/kv/kv.hpp | 11 +- src/kv/value_wrapper.cpp | 6 +- src/kv/value_wrapper.hpp | 2 +- src/lib/di/runtime_provider.hpp | 2 +- src/lib/di/shared.hpp | 2 +- src/lua/callbacks/creaturecallback.cpp | 11 +- src/lua/callbacks/creaturecallback.hpp | 10 +- src/lua/callbacks/event_callback.cpp | 14 +- src/lua/callbacks/event_callback.hpp | 4 +- src/lua/creature/actions.cpp | 16 +- src/lua/creature/actions.hpp | 8 +- src/lua/creature/events.cpp | 16 +- src/lua/creature/events.hpp | 6 +- src/lua/creature/movement.hpp | 9 +- src/lua/creature/raids.cpp | 2 +- .../functions/core/game/bank_functions.cpp | 2 +- .../functions/core/game/game_functions.cpp | 16 +- .../functions/core/game/global_functions.cpp | 8 +- src/lua/functions/core/libs/db_functions.cpp | 4 +- src/lua/functions/core/libs/kv_functions.cpp | 2 +- .../network/network_message_functions.cpp | 6 +- .../core/network/webhook_functions.cpp | 2 +- .../creatures/combat/spell_functions.cpp | 2 +- .../creatures/creature_functions.cpp | 20 +- .../creatures/player/player_functions.cpp | 34 +- .../events/global_event_functions.cpp | 2 +- .../functions/items/container_functions.cpp | 12 +- .../functions/items/imbuement_functions.cpp | 16 +- .../items/item_classification_functions.cpp | 2 +- src/lua/functions/items/item_functions.cpp | 8 +- .../functions/items/item_type_functions.cpp | 106 +-- src/lua/functions/map/house_functions.cpp | 2 +- src/lua/functions/map/position_functions.cpp | 6 +- src/lua/functions/map/tile_functions.cpp | 12 +- src/lua/global/baseevents.cpp | 2 +- src/lua/global/baseevents.hpp | 2 +- src/lua/modules/modules.hpp | 2 +- src/lua/scripts/script_environment.cpp | 2 +- src/map/house/house.cpp | 46 +- src/map/house/house.hpp | 38 +- src/map/house/housetile.cpp | 16 +- src/map/house/housetile.hpp | 2 +- src/map/map.cpp | 4 +- src/map/map.hpp | 10 +- src/map/mapcache.cpp | 4 +- src/map/mapcache.hpp | 2 +- src/map/utils/astarnodes.cpp | 2 +- src/map/utils/astarnodes.hpp | 4 +- src/map/utils/mapsector.hpp | 4 +- src/security/argon.cpp | 5 +- src/security/argon.hpp | 10 +- src/security/rsa.cpp | 2 +- src/security/rsa.hpp | 6 +- src/server/network/connection/connection.cpp | 6 +- src/server/network/connection/connection.hpp | 4 +- src/server/network/protocol/protocol.cpp | 8 +- src/server/network/protocol/protocol.hpp | 2 +- src/server/network/protocol/protocolgame.cpp | 351 +++++----- src/server/network/protocol/protocolgame.hpp | 140 ++-- src/server/network/protocol/protocollogin.cpp | 2 +- src/server/network/protocol/protocollogin.hpp | 4 +- .../network/protocol/protocolstatus.cpp | 2 +- .../network/protocol/protocolstatus.hpp | 2 +- src/server/network/webhook/webhook.cpp | 4 +- src/server/network/webhook/webhook.hpp | 2 +- src/utils/benchmark.hpp | 2 +- src/utils/tools.cpp | 15 +- src/utils/tools.hpp | 6 +- 178 files changed, 2424 insertions(+), 2403 deletions(-) diff --git a/data-otservbr-global/scripts/creaturescripts/monster/gaz_haragoth_heal.lua b/data-otservbr-global/scripts/creaturescripts/monster/gaz_haragoth_heal.lua index e0d446bb3bc..7e88e97168e 100644 --- a/data-otservbr-global/scripts/creaturescripts/monster/gaz_haragoth_heal.lua +++ b/data-otservbr-global/scripts/creaturescripts/monster/gaz_haragoth_heal.lua @@ -5,22 +5,36 @@ condition:setParameter(CONDITION_PARAM_HEALTHGAIN, 0.01) condition:setParameter(CONDITION_PARAM_HEALTHTICKS, 7 * 1000) local gazHaragothHeal = CreatureEvent("GazHaragothHeal") -function gazHaragothHeal.onThink(creature) - local hp = (creature:getHealth() / creature:getMaxHealth()) * 100 - if hp < 12.5 and not creature:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT, 88888) then - creature:addCondition(condition) - creature:say("Gaz'haragoth begins to draw on the nightmares to HEAL himself!", TALKTYPE_MONSTER_YELL) - addEvent(function(cid) - local creature = Creature(cid) - if not creature then - return +function gazHaragothHeal.onHealthChange(creature, attacker, primaryDamage, primaryType, secondaryDamage, secondaryType, origin) + if not creature then + return true + end + local creatureName = creature:getName():lower() == "gaz'haragoth" + if creatureName then + if attacker then + local hp = (creature:getHealth() / creature:getMaxHealth()) * 100 + if hp > 12.5 then + return primaryDamage, primaryType, secondaryDamage, secondaryType + end + if hp <= 12.5 and not creature:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT, 88888) then + if not creature then + return true + end + creature:addCondition(condition) + creature:say("Gaz'haragoth begins to draw on the nightmares to HEAL himself!", TALKTYPE_MONSTER_YELL) + addEvent(function() + if not creature then + return true + end + creature:addHealth(300000) + creature:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) + creature:say("Gaz'haragoth HEALS himself!", TALKTYPE_MONSTER_YELL) + return true + end, 7000, creature:getId()) end - creature:addHealth(300000) - creature:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) - creature:say("Gaz'haragoth HEALS himself!", TALKTYPE_MONSTER_YELL) - return true - end, 7000, creature:getId()) + end end + return primaryDamage, primaryType, secondaryDamage, secondaryType end gazHaragothHeal:register() diff --git a/src/account/account.cpp b/src/account/account.cpp index 2e5f58dd864..af82a9ae62c 100644 --- a/src/account/account.cpp +++ b/src/account/account.cpp @@ -280,7 +280,7 @@ bool Account::authenticateSession() { } bool Account::authenticatePassword(const std::string &password) { - if (Argon2 {}.argon(password.c_str(), getPassword())) { + if (Argon2 {}.argon(password, getPassword())) { return true; } diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 8e3de0da1bd..1d023ae1c1b 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "declarations.hpp" @@ -24,7 +26,7 @@ #include "lua/callbacks/event_callback.hpp" #include "lua/callbacks/events_callbacks.hpp" -int32_t Combat::getLevelFormula(std::shared_ptr player, const std::shared_ptr wheelSpell, const CombatDamage &damage) const { +int32_t Combat::getLevelFormula(const std::shared_ptr &player, const std::shared_ptr &wheelSpell, const CombatDamage &damage) const { if (!player) { return 0; } @@ -43,7 +45,7 @@ int32_t Combat::getLevelFormula(std::shared_ptr player, const std::share return levelFormula; } -CombatDamage Combat::getCombatDamage(std::shared_ptr creature, std::shared_ptr target) const { +CombatDamage Combat::getCombatDamage(const std::shared_ptr &creature, const std::shared_ptr &target) const { CombatDamage damage; damage.origin = params.origin; damage.primary.type = params.combatType; @@ -66,7 +68,7 @@ CombatDamage Combat::getCombatDamage(std::shared_ptr creature, std::sh int32_t min, max; if (creature->getCombatValues(min, max)) { damage.primary.value = normal_random(min, max); - } else if (std::shared_ptr player = creature->getPlayer()) { + } else if (const auto player = creature->getPlayer()) { if (params.valueCallback) { params.valueCallback->getMinMaxValues(player, damage, params.useCharges); } else if (formulaType == COMBAT_FORMULA_LEVELMAGIC) { @@ -184,7 +186,7 @@ ConditionType_t Combat::DamageToConditionType(CombatType_t type) { } } -bool Combat::isPlayerCombat(std::shared_ptr target) { +bool Combat::isPlayerCombat(const std::shared_ptr &target) { if (target->getPlayer()) { return true; } @@ -196,7 +198,7 @@ bool Combat::isPlayerCombat(std::shared_ptr target) { return false; } -ReturnValue Combat::canTargetCreature(std::shared_ptr player, std::shared_ptr target) { +ReturnValue Combat::canTargetCreature(const std::shared_ptr &player, const std::shared_ptr &target) { if (player == target) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -244,7 +246,7 @@ ReturnValue Combat::canTargetCreature(std::shared_ptr player, std::share return Combat::canDoCombat(player, target, true); } -ReturnValue Combat::canDoCombat(std::shared_ptr caster, std::shared_ptr tile, bool aggressive) { +ReturnValue Combat::canDoCombat(const std::shared_ptr &caster, const std::shared_ptr &tile, bool aggressive) { if (tile->hasProperty(CONST_PROP_BLOCKPROJECTILE)) { return RETURNVALUE_NOTENOUGHROOM; } @@ -269,7 +271,7 @@ ReturnValue Combat::canDoCombat(std::shared_ptr caster, std::shared_pt return RETURNVALUE_FIRSTGOUPSTAIRS; } - if (std::shared_ptr player = caster->getPlayer()) { + if (const auto player = caster->getPlayer()) { if (player->hasFlag(PlayerFlags_t::IgnoreProtectionZone)) { return RETURNVALUE_NOERROR; } @@ -282,11 +284,11 @@ ReturnValue Combat::canDoCombat(std::shared_ptr caster, std::shared_pt return ret; } -bool Combat::isInPvpZone(std::shared_ptr attacker, std::shared_ptr target) { +bool Combat::isInPvpZone(const std::shared_ptr &attacker, const std::shared_ptr &target) { return attacker->getZoneType() == ZONE_PVP && target->getZoneType() == ZONE_PVP; } -bool Combat::isProtected(std::shared_ptr attacker, std::shared_ptr target) { +bool Combat::isProtected(const std::shared_ptr &attacker, const std::shared_ptr &target) { uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__); if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) { return true; @@ -303,7 +305,7 @@ bool Combat::isProtected(std::shared_ptr attacker, std::shared_ptr attacker, std::shared_ptr target, bool aggressive) { +ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const std::shared_ptr &target, bool aggressive) { if (!aggressive) { return RETURNVALUE_NOERROR; } @@ -540,7 +542,7 @@ void Combat::setChainCallback(uint8_t chainTargets, uint8_t chainDistance, bool g_logger().trace("ChainCallback created: {}, with targets: {}, distance: {}, backtracking: {}", params.chainCallback != nullptr, chainTargets, chainDistance, backtracking); } -CallBack* Combat::getCallback(CallBackParam_t key) { +CallBack* Combat::getCallback(CallBackParam_t key) const { switch (key) { case CALLBACK_PARAM_LEVELMAGICVALUE: case CALLBACK_PARAM_SKILLVALUE: { @@ -566,7 +568,7 @@ CallBack* Combat::getCallback(CallBackParam_t key) { return nullptr; } -void Combat::CombatHealthFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data) { +void Combat::CombatHealthFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data) { if (!data) { g_logger().error("[{}]: CombatDamage is nullptr", __FUNCTION__); return; @@ -596,7 +598,7 @@ void Combat::CombatHealthFunc(std::shared_ptr caster, std::shared_ptr< } if (attackerPlayer) { - std::shared_ptr item = attackerPlayer->getWeapon(); + const auto item = attackerPlayer->getWeapon(); damage = applyImbuementElementalDamage(attackerPlayer, item, damage); g_events().eventPlayerOnCombat(attackerPlayer, target, item, damage); @@ -641,7 +643,7 @@ void Combat::CombatHealthFunc(std::shared_ptr caster, std::shared_ptr< } } -CombatDamage Combat::applyImbuementElementalDamage(std::shared_ptr attackerPlayer, std::shared_ptr item, CombatDamage damage) { +CombatDamage Combat::applyImbuementElementalDamage(const std::shared_ptr &attackerPlayer, std::shared_ptr item, CombatDamage damage) { if (!item) { return damage; } @@ -683,7 +685,7 @@ CombatDamage Combat::applyImbuementElementalDamage(std::shared_ptr attac return damage; } -void Combat::CombatManaFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data) { +void Combat::CombatManaFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data) { if (!data) { g_logger().error("[{}]: CombatDamage is nullptr", __FUNCTION__); return; @@ -702,7 +704,7 @@ void Combat::CombatManaFunc(std::shared_ptr caster, std::shared_ptr player) { +bool Combat::checkFearConditionAffected(const std::shared_ptr &player) { if (player->isImmuneFear()) { return false; } @@ -730,7 +732,7 @@ bool Combat::checkFearConditionAffected(std::shared_ptr player) { return true; } -void Combat::CombatConditionFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data) { +void Combat::CombatConditionFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data) { if (params.origin == ORIGIN_MELEE && data && data->primary.value == 0 && data->secondary.value == 0) { return; } @@ -783,18 +785,18 @@ void Combat::CombatConditionFunc(std::shared_ptr caster, std::shared_p } } -void Combat::CombatDispelFunc(std::shared_ptr, std::shared_ptr target, const CombatParams ¶ms, CombatDamage*) { +void Combat::CombatDispelFunc(const std::shared_ptr &, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage*) { if (target) { target->removeCombatCondition(params.dispelType); } } -void Combat::CombatNullFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage*) { +void Combat::CombatNullFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage*) { CombatConditionFunc(caster, target, params, nullptr); CombatDispelFunc(caster, target, params, nullptr); } -void Combat::combatTileEffects(const CreatureVector &spectators, std::shared_ptr caster, std::shared_ptr tile, const CombatParams ¶ms) { +void Combat::combatTileEffects(const CreatureVector &spectators, const std::shared_ptr &caster, const std::shared_ptr &tile, const CombatParams ¶ms) { if (params.itemId != 0) { uint16_t itemId = params.itemId; switch (itemId) { @@ -857,7 +859,7 @@ void Combat::combatTileEffects(const CreatureVector &spectators, std::shared_ptr } } - std::shared_ptr item = Item::CreateItem(itemId); + const auto item = Item::CreateItem(itemId); if (caster) { item->setOwner(caster); } @@ -883,7 +885,7 @@ void Combat::combatTileEffects(const CreatureVector &spectators, std::shared_ptr } } -void Combat::postCombatEffects(std::shared_ptr caster, const Position &origin, const Position &pos, const CombatParams ¶ms) { +void Combat::postCombatEffects(const std::shared_ptr &caster, const Position &origin, const Position &pos, const CombatParams ¶ms) { if (caster && params.distanceEffect != CONST_ANI_NONE) { addDistanceEffect(caster, origin, pos, params.distanceEffect); } @@ -895,13 +897,13 @@ void Combat::postCombatEffects(std::shared_ptr caster, const Position } } -void Combat::addDistanceEffect(std::shared_ptr caster, const Position &fromPos, const Position &toPos, uint16_t effect) { +void Combat::addDistanceEffect(const std::shared_ptr &caster, const Position &fromPos, const Position &toPos, uint16_t effect) { if (effect == CONST_ANI_WEAPONTYPE) { if (!caster) { return; } - std::shared_ptr player = caster->getPlayer(); + const auto player = caster->getPlayer(); if (!player) { return; } @@ -1030,7 +1032,7 @@ void Combat::setupChain(const std::shared_ptr &weapon) { } } -bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptr target, bool aggressive) const { +bool Combat::doCombatChain(const std::shared_ptr &caster, const std::shared_ptr &target, bool aggressive) const { metrics::method_latency measure(__METHOD_NAME__); if (!params.chainCallback) { return false; @@ -1040,7 +1042,7 @@ bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptrgetChainValues(caster, maxTargets, chainDistance, backtracking); - auto targets = pickChainTargets(caster, params, chainDistance, maxTargets, aggressive, backtracking, std::move(target)); + auto targets = pickChainTargets(caster, params, chainDistance, maxTargets, aggressive, backtracking, target); g_logger().debug("[{}] Chain targets: {}", __FUNCTION__, targets.size()); if (targets.empty() || (targets.size() == 1 && targets.begin()->second.empty())) { @@ -1049,8 +1051,8 @@ bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptr(50, g_configManager().getNumber(COMBAT_CHAIN_DELAY, __FUNCTION__)); ++i; for (auto to : toVector) { @@ -1061,7 +1063,7 @@ bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptrdoChainEffect(from, nextTarget->getPosition(), combat->params.chainEffect); + Combat::doChainEffect(from, nextTarget->getPosition(), combat->params.chainEffect); combat->doCombat(caster, nextTarget, from, affected); } }, @@ -1073,7 +1075,7 @@ bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptr caster, std::shared_ptr target) const { +bool Combat::doCombat(const std::shared_ptr &caster, const std::shared_ptr &target) const { if (caster != nullptr && params.chainCallback) { return doCombatChain(caster, target, params.aggressive); } @@ -1081,7 +1083,7 @@ bool Combat::doCombat(std::shared_ptr caster, std::shared_ptrgetPosition() : Position()); } -bool Combat::doCombat(std::shared_ptr caster, std::shared_ptr target, const Position &origin, int affected /* = 1 */) const { +bool Combat::doCombat(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, int affected /* = 1 */) const { // target combat callback function if (params.combatType != COMBAT_NONE) { CombatDamage damage = getCombatDamage(caster, target); @@ -1098,7 +1100,7 @@ bool Combat::doCombat(std::shared_ptr caster, std::shared_ptr caster, const Position &position) const { +bool Combat::doCombat(const std::shared_ptr &caster, const Position &position) const { if (caster != nullptr && params.chainCallback) { return doCombatChain(caster, caster, params.aggressive); } @@ -1119,7 +1121,7 @@ bool Combat::doCombat(std::shared_ptr caster, const Position &position return true; } -void Combat::CombatFunc(std::shared_ptr caster, const Position &origin, const Position &pos, const std::unique_ptr &area, const CombatParams ¶ms, CombatFunction func, CombatDamage* data) { +void Combat::CombatFunc(const std::shared_ptr &caster, const Position &origin, const Position &pos, const std::unique_ptr &area, const CombatParams ¶ms, const CombatFunction &func, CombatDamage* data) { std::vector> tileList; if (caster) { @@ -1250,11 +1252,11 @@ void Combat::CombatFunc(std::shared_ptr caster, const Position &origin postCombatEffects(caster, origin, pos, params); } -void Combat::doCombatHealth(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms) { - doCombatHealth(caster, std::move(target), caster ? caster->getPosition() : Position(), damage, params); +void Combat::doCombatHealth(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms) { + doCombatHealth(caster, target, caster ? caster->getPosition() : Position(), damage, params); } -void Combat::doCombatHealth(std::shared_ptr caster, std::shared_ptr target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::doCombatHealth(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster && target) && (caster == target || canCombat) @@ -1288,17 +1290,17 @@ void Combat::doCombatHealth(std::shared_ptr caster, std::shared_ptr caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::doCombatHealth(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms) { applyExtensions(caster, nullptr, damage, params); const auto origin = caster ? caster->getPosition() : Position(); CombatFunc(caster, origin, position, area, params, CombatHealthFunc, &damage); } -void Combat::doCombatMana(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::doCombatMana(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms) { doCombatMana(caster, target, caster ? caster->getPosition() : Position(), damage, params); } -void Combat::doCombatMana(std::shared_ptr caster, std::shared_ptr target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::doCombatMana(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster && target) && (caster == target || canCombat) @@ -1326,18 +1328,18 @@ void Combat::doCombatMana(std::shared_ptr caster, std::shared_ptr caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::doCombatMana(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms) { applyExtensions(caster, nullptr, damage, params); const auto origin = caster ? caster->getPosition() : Position(); CombatFunc(caster, origin, position, area, params, CombatManaFunc, &damage); } -void Combat::doCombatCondition(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms) { +void Combat::doCombatCondition(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms) { const auto origin = caster ? caster->getPosition() : Position(); CombatFunc(caster, origin, position, area, params, CombatConditionFunc, nullptr); } -void Combat::doCombatCondition(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms) { +void Combat::doCombatCondition(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster == target || canCombat) && params.impactEffect != CONST_ME_NONE) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); @@ -1361,12 +1363,12 @@ void Combat::doCombatCondition(std::shared_ptr caster, std::shared_ptr } } -void Combat::doCombatDispel(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms) { +void Combat::doCombatDispel(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms) { const auto origin = caster ? caster->getPosition() : Position(); CombatFunc(caster, origin, position, area, params, CombatDispelFunc, nullptr); } -void Combat::doCombatDispel(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms) { +void Combat::doCombatDispel(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms) { bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster && target) && (caster == target || canCombat) @@ -1392,11 +1394,11 @@ void Combat::doCombatDispel(std::shared_ptr caster, std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms) { +[[maybe_unused]] void Combat::doCombatDefault(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms) { doCombatDefault(caster, target, caster ? caster->getPosition() : Position(), params); } -void Combat::doCombatDefault(std::shared_ptr caster, std::shared_ptr target, const Position &origin, const CombatParams ¶ms) { +void Combat::doCombatDefault(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, const CombatParams ¶ms) { if (!params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR)) { auto spectators = Spectators().find(target->getPosition(), true); @@ -1433,7 +1435,7 @@ void Combat::setRuneSpellName(const std::string &value) { runeSpellName = value; } -std::vector>> Combat::pickChainTargets(std::shared_ptr caster, const CombatParams ¶ms, uint8_t chainDistance, uint8_t maxTargets, bool backtracking, bool aggressive, std::shared_ptr initialTarget /* = nullptr */) { +std::vector>> Combat::pickChainTargets(const std::shared_ptr &caster, const CombatParams ¶ms, uint8_t chainDistance, uint8_t maxTargets, bool backtracking, bool aggressive, const std::shared_ptr &initialTarget /* = nullptr */) { Benchmark bm_pickChain; metrics::method_latency measure(__METHOD_NAME__); if (!caster) { @@ -1508,7 +1510,7 @@ std::vector>> Combat::pickChainTargets return resultMap; } -bool Combat::isValidChainTarget(std::shared_ptr caster, std::shared_ptr currentTarget, std::shared_ptr potentialTarget, const CombatParams ¶ms, bool aggressive) { +bool Combat::isValidChainTarget(const std::shared_ptr &caster, const std::shared_ptr ¤tTarget, const std::shared_ptr &potentialTarget, const CombatParams ¶ms, bool aggressive) { bool canCombat = canDoCombat(caster, potentialTarget, aggressive) == RETURNVALUE_NOERROR; bool pick = params.chainPickerCallback ? params.chainPickerCallback->onChainCombat(caster, potentialTarget) : true; bool hasSight = g_game().isSightClear(currentTarget->getPosition(), potentialTarget->getPosition(), true); @@ -1517,7 +1519,7 @@ bool Combat::isValidChainTarget(std::shared_ptr caster, std::shared_pt //**********************************************************// -uint32_t ValueCallback::getMagicLevelSkill(std::shared_ptr player, const CombatDamage &damage) const { +uint32_t ValueCallback::getMagicLevelSkill(const std::shared_ptr &player, const CombatDamage &damage) const { if (!player) { return 0; } @@ -1537,18 +1539,18 @@ uint32_t ValueCallback::getMagicLevelSkill(std::shared_ptr player, const return magicLevelSkill + player->getSpecializedMagicLevel(damage.primary.type, true); } -void ValueCallback::getMinMaxValues(std::shared_ptr player, CombatDamage &damage, bool useCharges) const { +void ValueCallback::getMinMaxValues(const std::shared_ptr &player, CombatDamage &damage, bool useCharges) const { // onGetPlayerMinMaxValues(...) - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[ValueCallback::getMinMaxValues - Player {} formula {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), fmt::underlying(type)); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); if (!env->setCallbackId(scriptId, scriptInterface)) { - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return; } @@ -1592,7 +1594,7 @@ void ValueCallback::getMinMaxValues(std::shared_ptr player, CombatDamage default: { g_logger().warn("[ValueCallback::getMinMaxValues] - Unknown callback type"); - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return; } } @@ -1625,23 +1627,23 @@ void ValueCallback::getMinMaxValues(std::shared_ptr player, CombatDamage LuaScriptInterface::reportError(nullptr, "Stack size changed!"); } - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } //**********************************************************// -void TileCallback::onTileCombat(std::shared_ptr creature, std::shared_ptr tile) const { +void TileCallback::onTileCombat(const std::shared_ptr &creature, const std::shared_ptr &tile) const { // onTileCombat(creature, pos) - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[TileCallback::onTileCombat - Creature {} type {} on tile x: {} y: {} z: {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), fmt::underlying(type), (tile->getPosition()).getX(), (tile->getPosition()).getY(), (tile->getPosition()).getZ()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); if (!env->setCallbackId(scriptId, scriptInterface)) { - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return; } @@ -1661,18 +1663,18 @@ void TileCallback::onTileCombat(std::shared_ptr creature, std::shared_ //**********************************************************// -void TargetCallback::onTargetCombat(std::shared_ptr creature, std::shared_ptr target) const { +void TargetCallback::onTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const { // onTargetCombat(creature, target) - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[TargetCallback::onTargetCombat - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); if (!env->setCallbackId(scriptId, scriptInterface)) { - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return; } @@ -1704,7 +1706,7 @@ void TargetCallback::onTargetCombat(std::shared_ptr creature, std::sha LuaScriptInterface::reportError(nullptr, "Stack size changed!"); } - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } //**********************************************************// @@ -1721,18 +1723,18 @@ void ChainCallback::getChainValues(const std::shared_ptr &creature, ui backtracking = m_backtracking; } } -void ChainCallback::onChainCombat(std::shared_ptr creature, uint8_t &maxTargets, uint8_t &chainDistance, bool &backtracking) { +void ChainCallback::onChainCombat(const std::shared_ptr &creature, uint8_t &maxTargets, uint8_t &chainDistance, bool &backtracking) { // onChainCombat(creature) - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[ChainCallback::onTargetCombat - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); if (!env->setCallbackId(scriptId, scriptInterface)) { - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return; } @@ -1760,21 +1762,21 @@ void ChainCallback::onChainCombat(std::shared_ptr creature, uint8_t &m LuaScriptInterface::reportError(nullptr, "Stack size changed!"); } - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); } -bool ChainPickerCallback::onChainCombat(std::shared_ptr creature, std::shared_ptr target) const { +bool ChainPickerCallback::onChainCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const { // onChainCombat(creature, target) - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[ChainPickerCallback::onTargetCombat - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return true; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); if (!env->setCallbackId(scriptId, scriptInterface)) { - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return true; } @@ -1809,7 +1811,7 @@ bool ChainPickerCallback::onChainCombat(std::shared_ptr creature, std: LuaScriptInterface::reportError(nullptr, "Stack size changed!"); } - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return result; } @@ -1854,7 +1856,7 @@ void AreaCombat::getList(const Position ¢erPos, const Position &targetPos, s } } -void AreaCombat::copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op) const { +void AreaCombat::copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op) { uint32_t centerY, centerX; input->getCenter(centerY, centerX); @@ -1923,8 +1925,8 @@ void AreaCombat::copyArea(const std::unique_ptr &input, const std::u int32_t newY = y - centerY; // perform rotation - int32_t rotatedX = static_cast(round(newX * a + newY * b)); - int32_t rotatedY = static_cast(round(newX * c + newY * d)); + auto rotatedX = static_cast(round(newX * a + newY * b)); + auto rotatedY = static_cast(round(newX * c + newY * d)); // write in the output matrix using rotated coordinates (*output)[rotatedY + rotateCenterY][rotatedX + rotateCenterX] = (*input)[y][x]; @@ -2136,7 +2138,7 @@ void MagicField::onStepInField(const std::shared_ptr &creature) { } } -void Combat::applyExtensions(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms) { +void Combat::applyExtensions(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms) { metrics::method_latency measure(__METHOD_NAME__); if (damage.extension || !caster || damage.primary.type == COMBAT_HEALING) { return; diff --git a/src/creatures/combat/combat.hpp b/src/creatures/combat/combat.hpp index 304a709135d..71a1e08069b 100644 --- a/src/creatures/combat/combat.hpp +++ b/src/creatures/combat/combat.hpp @@ -35,27 +35,27 @@ class ValueCallback final : public CallBack { * @param damage The combat damage information. * @return The magic level skill of the player. */ - uint32_t getMagicLevelSkill(std::shared_ptr player, const CombatDamage &damage) const; - void getMinMaxValues(std::shared_ptr player, CombatDamage &damage, bool useCharges) const; + uint32_t getMagicLevelSkill(const std::shared_ptr &player, const CombatDamage &damage) const; + void getMinMaxValues(const std::shared_ptr &player, CombatDamage &damage, bool useCharges) const; private: - formulaType_t type; + formulaType_t type {}; }; class TileCallback final : public CallBack { public: - void onTileCombat(std::shared_ptr creature, std::shared_ptr tile) const; + void onTileCombat(const std::shared_ptr &creature, const std::shared_ptr &tile) const; protected: - formulaType_t type; + formulaType_t type {}; }; class TargetCallback final : public CallBack { public: - void onTargetCombat(std::shared_ptr creature, std::shared_ptr target) const; + void onTargetCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const; protected: - formulaType_t type; + formulaType_t type {}; }; class ChainCallback final : public CallBack { @@ -70,7 +70,7 @@ class ChainCallback final : public CallBack { } private: - void onChainCombat(std::shared_ptr creature, uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking); + void onChainCombat(const std::shared_ptr &creature, uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking); uint8_t m_chainDistance = 0; uint8_t m_chainTargets = 0; @@ -80,7 +80,7 @@ class ChainCallback final : public CallBack { class ChainPickerCallback final : public CallBack { public: - bool onChainCombat(std::shared_ptr creature, std::shared_ptr target) const; + bool onChainCombat(const std::shared_ptr &creature, const std::shared_ptr &target) const; }; struct CombatParams { @@ -232,7 +232,7 @@ class AreaCombat { private: std::unique_ptr createArea(const std::list &list, uint32_t rows); - void copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op) const; + void copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op); const std::unique_ptr &getArea(const Position ¢erPos, const Position &targetPos) const { int32_t dx = Position::getOffsetX(targetPos, centerPos); @@ -276,41 +276,41 @@ class Combat { Combat(const Combat &) = delete; Combat &operator=(const Combat &) = delete; - static void applyExtensions(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms); + static void applyExtensions(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatHealth(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatHealth(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatHealth(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatHealth(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatMana(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatMana(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatMana(const std::shared_ptr &caster, const std::shared_ptr &target, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatMana(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatCondition(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms); - static void doCombatCondition(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms); + static void doCombatCondition(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms); + static void doCombatCondition(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms); - static void doCombatDispel(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms); - static void doCombatDispel(std::shared_ptr caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms); + static void doCombatDispel(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms); + static void doCombatDispel(const std::shared_ptr &caster, const Position &position, const std::unique_ptr &area, const CombatParams ¶ms); static void getCombatArea(const Position ¢erPos, const Position &targetPos, const std::unique_ptr &area, std::vector> &list); - static bool isInPvpZone(std::shared_ptr attacker, std::shared_ptr target); - static bool isProtected(std::shared_ptr attacker, std::shared_ptr target); - static bool isPlayerCombat(std::shared_ptr target); + static bool isInPvpZone(const std::shared_ptr &attacker, const std::shared_ptr &target); + static bool isProtected(const std::shared_ptr &attacker, const std::shared_ptr &target); + static bool isPlayerCombat(const std::shared_ptr &target); static CombatType_t ConditionToDamageType(ConditionType_t type); static ConditionType_t DamageToConditionType(CombatType_t type); - static ReturnValue canTargetCreature(std::shared_ptr attacker, std::shared_ptr target); - static ReturnValue canDoCombat(std::shared_ptr caster, std::shared_ptr tile, bool aggressive); - static ReturnValue canDoCombat(std::shared_ptr attacker, std::shared_ptr target, bool aggressive); - static void postCombatEffects(std::shared_ptr caster, const Position &origin, const Position &pos, const CombatParams ¶ms); + static ReturnValue canTargetCreature(const std::shared_ptr &attacker, const std::shared_ptr &target); + static ReturnValue canDoCombat(const std::shared_ptr &caster, const std::shared_ptr &tile, bool aggressive); + static ReturnValue canDoCombat(const std::shared_ptr &attacker, const std::shared_ptr &target, bool aggressive); + static void postCombatEffects(const std::shared_ptr &caster, const Position &origin, const Position &pos, const CombatParams ¶ms); - static void addDistanceEffect(std::shared_ptr caster, const Position &fromPos, const Position &toPos, uint16_t effect); + static void addDistanceEffect(const std::shared_ptr &caster, const Position &fromPos, const Position &toPos, uint16_t effect); - bool doCombat(std::shared_ptr caster, std::shared_ptr target) const; - bool doCombat(std::shared_ptr caster, std::shared_ptr target, const Position &origin, int affected = 1) const; - bool doCombat(std::shared_ptr caster, const Position &pos) const; + bool doCombat(const std::shared_ptr &caster, const std::shared_ptr &target) const; + bool doCombat(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, int affected = 1) const; + bool doCombat(const std::shared_ptr &caster, const Position &pos) const; bool setCallback(CallBackParam_t key); void setChainCallback(uint8_t chainTargets, uint8_t chainDistance, bool backtracking); - CallBack* getCallback(CallBackParam_t key); + CallBack* getCallback(CallBackParam_t key) const; bool setParam(CombatParam_t param, uint32_t value); void setArea(std::unique_ptr &newArea) { @@ -319,12 +319,12 @@ class Combat { bool hasArea() const { return area != nullptr; } - void addCondition(const std::shared_ptr condition) { + void addCondition(const std::shared_ptr &condition) { params.conditionList.emplace_back(condition); } void setPlayerCombatValues(formulaType_t formulaType, double mina, double minb, double maxa, double maxb); - void postCombatEffects(std::shared_ptr caster, const Position &origin, const Position &pos) const { - postCombatEffects(std::move(caster), origin, pos, params); + void postCombatEffects(const std::shared_ptr &caster, const Position &origin, const Position &pos) const { + postCombatEffects(caster, origin, pos, params); } void setOrigin(CombatOrigin origin) { @@ -346,24 +346,24 @@ class Combat { void setRuneSpellName(const std::string &value); void setupChain(const std::shared_ptr &weapon); - bool doCombatChain(std::shared_ptr caster, std::shared_ptr target, bool aggressive) const; + bool doCombatChain(const std::shared_ptr &caster, const std::shared_ptr &target, bool aggressive) const; private: static void doChainEffect(const Position &origin, const Position &pos, uint8_t effect); - static std::vector>> pickChainTargets(std::shared_ptr caster, const CombatParams ¶ms, uint8_t chainDistance, uint8_t maxTargets, bool aggressive, bool backtracking, std::shared_ptr initialTarget = nullptr); - static bool isValidChainTarget(std::shared_ptr caster, std::shared_ptr currentTarget, std::shared_ptr potentialTarget, const CombatParams ¶ms, bool aggressive); + static std::vector>> pickChainTargets(const std::shared_ptr &caster, const CombatParams ¶ms, uint8_t chainDistance, uint8_t maxTargets, bool aggressive, bool backtracking, const std::shared_ptr &initialTarget = nullptr); + static bool isValidChainTarget(const std::shared_ptr &caster, const std::shared_ptr ¤tTarget, const std::shared_ptr &potentialTarget, const CombatParams ¶ms, bool aggressive); - static void doCombatDefault(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms); + static void doCombatDefault(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms); - static void doCombatHealth(std::shared_ptr caster, std::shared_ptr target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatMana(std::shared_ptr caster, std::shared_ptr target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms); - static void doCombatDefault(std::shared_ptr caster, std::shared_ptr target, const Position &origin, const CombatParams ¶ms); + static void doCombatHealth(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatMana(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms); + static void doCombatDefault(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, const CombatParams ¶ms); - static void CombatFunc(std::shared_ptr caster, const Position &origin, const Position &pos, const std::unique_ptr &area, const CombatParams ¶ms, CombatFunction func, CombatDamage* data); + static void CombatFunc(const std::shared_ptr &caster, const Position &origin, const Position &pos, const std::unique_ptr &area, const CombatParams ¶ms, const CombatFunction &func, CombatDamage* data); - static void CombatHealthFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data); - static CombatDamage applyImbuementElementalDamage(std::shared_ptr attackerPlayer, std::shared_ptr item, CombatDamage damage); - static void CombatManaFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* damage); + static void CombatHealthFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data); + static CombatDamage applyImbuementElementalDamage(const std::shared_ptr &attackerPlayer, std::shared_ptr item, CombatDamage damage); + static void CombatManaFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* damage); /** * @brief Checks if a fear condition can be applied to a player. * @@ -378,12 +378,12 @@ class Combat { * @param player Pointer to the Player object to be checked. * @return true if the fear condition can be applied, false otherwise. */ - static bool checkFearConditionAffected(std::shared_ptr player); - static void CombatConditionFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data); - static void CombatDispelFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data); - static void CombatNullFunc(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms, CombatDamage* data); + static bool checkFearConditionAffected(const std::shared_ptr &player); + static void CombatConditionFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data); + static void CombatDispelFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data); + static void CombatNullFunc(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms, CombatDamage* data); - static void combatTileEffects(const CreatureVector &spectators, std::shared_ptr caster, std::shared_ptr tile, const CombatParams ¶ms); + static void combatTileEffects(const CreatureVector &spectators, const std::shared_ptr &caster, const std::shared_ptr &tile, const CombatParams ¶ms); /** * @brief Calculate the level formula for combat. @@ -393,8 +393,8 @@ class Combat { * @param damage The combat damage. * @return The calculated level formula. */ - int32_t getLevelFormula(std::shared_ptr player, std::shared_ptr wheelSpell, const CombatDamage &damage) const; - CombatDamage getCombatDamage(std::shared_ptr creature, std::shared_ptr target) const; + int32_t getLevelFormula(const std::shared_ptr &player, const std::shared_ptr &wheelSpell, const CombatDamage &damage) const; + CombatDamage getCombatDamage(const std::shared_ptr &creature, const std::shared_ptr &target) const; // configureable CombatParams params; diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index c06d9a792d5..8cd4a3f9c4d 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -466,7 +466,7 @@ void ConditionAttributes::addCondition(std::shared_ptr creature, const updateCharmChanceModifier(creature); disableDefense = conditionAttrs->disableDefense; - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -570,7 +570,7 @@ bool ConditionAttributes::startCondition(std::shared_ptr creature) { updatePercentIncreases(creature); updateIncreases(creature); updateCharmChanceModifier(creature); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -580,7 +580,7 @@ bool ConditionAttributes::startCondition(std::shared_ptr creature) { return true; } -void ConditionAttributes::updatePercentStats(std::shared_ptr player) { +void ConditionAttributes::updatePercentStats(const std::shared_ptr &player) { for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { if (statsPercent[i] == 0) { continue; @@ -606,7 +606,7 @@ void ConditionAttributes::updatePercentStats(std::shared_ptr player) { } } -void ConditionAttributes::updateStats(std::shared_ptr player) { +void ConditionAttributes::updateStats(const std::shared_ptr &player) { bool needUpdate = false; for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { @@ -622,9 +622,9 @@ void ConditionAttributes::updateStats(std::shared_ptr player) { } } -void ConditionAttributes::updatePercentSkills(std::shared_ptr player) { +void ConditionAttributes::updatePercentSkills(const std::shared_ptr &player) { for (uint8_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { - skills_t skill = static_cast(i); + auto skill = static_cast(i); if (skillsPercent[skill] == 0) { continue; } @@ -634,7 +634,7 @@ void ConditionAttributes::updatePercentSkills(std::shared_ptr player) { } } -void ConditionAttributes::updateSkills(std::shared_ptr player) { +void ConditionAttributes::updateSkills(const std::shared_ptr &player) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { @@ -649,7 +649,7 @@ void ConditionAttributes::updateSkills(std::shared_ptr player) { } } -void ConditionAttributes::updatePercentAbsorbs(std::shared_ptr creature) { +void ConditionAttributes::updatePercentAbsorbs(const std::shared_ptr &creature) { for (uint8_t i = 0; i < COMBAT_COUNT; i++) { auto value = getAbsorbPercentByIndex(i); if (value == 0) { @@ -659,7 +659,7 @@ void ConditionAttributes::updatePercentAbsorbs(std::shared_ptr creatur } } -void ConditionAttributes::updateAbsorbs(std::shared_ptr creature) const { +void ConditionAttributes::updateAbsorbs(const std::shared_ptr &creature) const { for (uint8_t i = 0; i < COMBAT_COUNT; i++) { auto value = getAbsorbByIndex(i); if (value == 0) { @@ -670,7 +670,7 @@ void ConditionAttributes::updateAbsorbs(std::shared_ptr creature) cons } } -void ConditionAttributes::updatePercentIncreases(std::shared_ptr creature) { +void ConditionAttributes::updatePercentIncreases(const std::shared_ptr &creature) { for (uint8_t i = 0; i < COMBAT_COUNT; i++) { auto increasePercentValue = getIncreasePercentById(i); if (increasePercentValue == 0) { @@ -680,7 +680,7 @@ void ConditionAttributes::updatePercentIncreases(std::shared_ptr creat } } -void ConditionAttributes::updateIncreases(std::shared_ptr creature) const { +void ConditionAttributes::updateIncreases(const std::shared_ptr &creature) const { for (uint8_t i = 0; i < COMBAT_COUNT; i++) { auto increaseValue = getIncreaseByIndex(i); if (increaseValue == 0) { @@ -690,11 +690,11 @@ void ConditionAttributes::updateIncreases(std::shared_ptr creature) co } } -void ConditionAttributes::updateCharmChanceModifier(std::shared_ptr creature) const { +void ConditionAttributes::updateCharmChanceModifier(const std::shared_ptr &creature) const { creature->setCharmChanceModifier(creature->getCharmChanceModifier() + charmChanceModifier); } -void ConditionAttributes::updatePercentBuffs(std::shared_ptr creature) { +void ConditionAttributes::updatePercentBuffs(const std::shared_ptr &creature) { for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { if (buffsPercent[i] == 0) { continue; @@ -705,7 +705,7 @@ void ConditionAttributes::updatePercentBuffs(std::shared_ptr creature) } } -void ConditionAttributes::updateBuffs(std::shared_ptr creature) { +void ConditionAttributes::updateBuffs(const std::shared_ptr &creature) { bool needUpdate = false; for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { if (buffs[i]) { @@ -723,7 +723,7 @@ bool ConditionAttributes::executeCondition(std::shared_ptr creature, i } void ConditionAttributes::endCondition(std::shared_ptr creature) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { bool needUpdate = false; @@ -1130,14 +1130,14 @@ bool ConditionRegeneration::startCondition(std::shared_ptr creature) { return false; } - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } return true; } void ConditionRegeneration::endCondition(std::shared_ptr creature) { - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } } @@ -1272,8 +1272,8 @@ bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) { } } -uint32_t ConditionRegeneration::getHealthTicks(std::shared_ptr creature) const { - std::shared_ptr player = creature->getPlayer(); +uint32_t ConditionRegeneration::getHealthTicks(const std::shared_ptr &creature) const { + const auto player = creature->getPlayer(); if (player != nullptr && isBuff) { return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); @@ -1282,8 +1282,8 @@ uint32_t ConditionRegeneration::getHealthTicks(std::shared_ptr creatur return healthTicks; } -uint32_t ConditionRegeneration::getManaTicks(std::shared_ptr creature) const { - std::shared_ptr player = creature->getPlayer(); +uint32_t ConditionRegeneration::getManaTicks(const std::shared_ptr &creature) const { + const auto player = creature->getPlayer(); if (player != nullptr && isBuff) { return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); @@ -1304,7 +1304,7 @@ bool ConditionManaShield::startCondition(std::shared_ptr creature) { creature->setManaShield(manaShield); creature->setMaxManaShield(manaShield); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } @@ -1314,7 +1314,7 @@ bool ConditionManaShield::startCondition(std::shared_ptr creature) { void ConditionManaShield::endCondition(std::shared_ptr creature) { creature->setManaShield(0); creature->setMaxManaShield(0); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } } @@ -1329,7 +1329,7 @@ void ConditionManaShield::addCondition(std::shared_ptr creature, const creature->setManaShield(manaShield); creature->setMaxManaShield(manaShield); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { player->sendStats(); } } @@ -1407,7 +1407,7 @@ void ConditionSoul::serialize(PropWriteStream &propWriteStream) { bool ConditionSoul::executeCondition(std::shared_ptr creature, int32_t interval) { internalSoulTicks += interval; - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (player->getZoneType() != ZONE_PROTECTION) { if (internalSoulTicks >= soulTicks) { internalSoulTicks = 0; @@ -1671,7 +1671,7 @@ bool ConditionDamage::getNextDamage(int32_t &damage) { return false; } -bool ConditionDamage::doDamage(std::shared_ptr creature, int32_t healthChange) { +bool ConditionDamage::doDamage(const std::shared_ptr &creature, int32_t healthChange) { auto attacker = g_game().getPlayerByGUID(owner) ? g_game().getPlayerByGUID(owner)->getCreature() : g_game().getCreatureByID(owner); bool isPlayer = attacker && attacker->getPlayer(); if (creature->isSuppress(getType(), isPlayer)) { @@ -1836,7 +1836,7 @@ bool ConditionFeared::isStuck(std::shared_ptr creature, Position pos) }); } -bool ConditionFeared::getRandomDirection(std::shared_ptr creature, Position pos) { +bool ConditionFeared::getRandomDirection(const std::shared_ptr &creature, Position pos) { static std::vector directions { DIRECTION_NORTH, DIRECTION_NORTHEAST, @@ -1859,7 +1859,7 @@ bool ConditionFeared::getRandomDirection(std::shared_ptr creature, Pos return false; } -bool ConditionFeared::canWalkTo(std::shared_ptr creature, Position pos, Direction moveDirection) const { +bool ConditionFeared::canWalkTo(const std::shared_ptr &creature, Position pos, Direction moveDirection) const { pos = getNextPosition(moveDirection, pos); if (!creature) { g_logger().error("[{}] creature is nullptr", __FUNCTION__); @@ -1878,7 +1878,7 @@ bool ConditionFeared::canWalkTo(std::shared_ptr creature, Position pos return false; } -bool ConditionFeared::getFleeDirection(std::shared_ptr creature) { +bool ConditionFeared::getFleeDirection(const std::shared_ptr &creature) { Position creaturePos = creature->getPosition(); int_fast32_t offx = Position::getOffsetX(creaturePos, fleeingFromPos); @@ -1954,7 +1954,7 @@ bool ConditionFeared::getFleeDirection(std::shared_ptr creature) { return false; } -bool ConditionFeared::getFleePath(std::shared_ptr creature, const Position &pos, std::vector &dirList) { +bool ConditionFeared::getFleePath(const std::shared_ptr &creature, const Position &pos, std::vector &dirList) { const std::vector walkSize { 15, 9, 3, 1 }; bool found = false; std::ptrdiff_t found_size = 0; @@ -2084,7 +2084,7 @@ void ConditionFeared::endCondition(std::shared_ptr creature) { /* * After a player is feared there's a 10 seconds before they can can feared again. */ - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->setImmuneFear(); } @@ -2339,7 +2339,7 @@ void ConditionOutfit::addCondition(std::shared_ptr creature, const std setTicks(addCondition->getTicks()); const std::shared_ptr &conditionOutfit = addCondition->static_self_cast(); - if (!conditionOutfit->monsterName.empty() && conditionOutfit->monsterName.compare(monsterName) != 0) { + if (!conditionOutfit->monsterName.empty() && conditionOutfit->monsterName != monsterName) { const auto monsterType = g_monsters().getMonsterType(conditionOutfit->monsterName); if (monsterType) { setOutfit(monsterType->info.outfit); @@ -2480,7 +2480,7 @@ void ConditionSpellCooldown::addCondition(std::shared_ptr creature, co setTicks(addCondition->getTicks()); if (subId != 0 && ticks > 0) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendSpellCooldown(subId, ticks); } @@ -2494,7 +2494,7 @@ bool ConditionSpellCooldown::startCondition(std::shared_ptr creature) } if (subId != 0 && ticks > 0) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendSpellCooldown(subId, ticks); } @@ -2511,7 +2511,7 @@ void ConditionSpellGroupCooldown::addCondition(std::shared_ptr creatur setTicks(addCondition->getTicks()); if (subId != 0 && ticks > 0) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } @@ -2525,7 +2525,7 @@ bool ConditionSpellGroupCooldown::startCondition(std::shared_ptr creat } if (subId != 0 && ticks > 0) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index ea59943e5c7..f4777f0ef5d 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -24,7 +24,7 @@ class Condition : public SharedObject { Condition(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0, bool isPersistent = false) : endTime(initTicks == -1 ? std::numeric_limits::max() : 0), subId(initSubId), ticks(initTicks), conditionType(initType), id(initId), isBuff(initBuff), m_isPersistent(isPersistent) { } - virtual ~Condition() = default; + ~Condition() override = default; virtual bool startCondition(std::shared_ptr creature); virtual bool executeCondition(std::shared_ptr creature, int32_t interval); @@ -153,19 +153,19 @@ class ConditionAttributes final : public ConditionGeneric { bool disableDefense = false; - void updatePercentStats(std::shared_ptr player); - void updateStats(std::shared_ptr player); - void updatePercentSkills(std::shared_ptr player); - void updateSkills(std::shared_ptr player); - void updateBuffs(std::shared_ptr creature); + void updatePercentStats(const std::shared_ptr &player); + void updateStats(const std::shared_ptr &player); + void updatePercentSkills(const std::shared_ptr &player); + void updateSkills(const std::shared_ptr &player); + void updateBuffs(const std::shared_ptr &creature); // 12.72 mechanics - void updatePercentAbsorbs(std::shared_ptr creature); - void updateAbsorbs(std::shared_ptr creature) const; - void updatePercentIncreases(std::shared_ptr creature); - void updateIncreases(std::shared_ptr creature) const; - void updateCharmChanceModifier(std::shared_ptr creature) const; - void updatePercentBuffs(std::shared_ptr creature); + void updatePercentAbsorbs(const std::shared_ptr &creature); + void updateAbsorbs(const std::shared_ptr &creature) const; + void updatePercentIncreases(const std::shared_ptr &creature); + void updateIncreases(const std::shared_ptr &creature) const; + void updateCharmChanceModifier(const std::shared_ptr &creature) const; + void updatePercentBuffs(const std::shared_ptr &creature); }; class ConditionRegeneration final : public ConditionGeneric { @@ -180,8 +180,8 @@ class ConditionRegeneration final : public ConditionGeneric { bool setParam(ConditionParam_t param, int32_t value) override; - uint32_t getHealthTicks(std::shared_ptr creature) const; - uint32_t getManaTicks(std::shared_ptr creature) const; + uint32_t getHealthTicks(const std::shared_ptr &creature) const; + uint32_t getManaTicks(const std::shared_ptr &creature) const; std::shared_ptr clone() const override { return std::make_shared(*this); @@ -310,7 +310,7 @@ class ConditionDamage final : public Condition { std::list damageList; bool getNextDamage(int32_t &damage); - bool doDamage(std::shared_ptr creature, int32_t healthChange); + bool doDamage(const std::shared_ptr &creature, int32_t healthChange); bool updateCondition(std::shared_ptr addCondition) override; }; @@ -334,10 +334,10 @@ class ConditionFeared final : public Condition { bool setPositionParam(ConditionParam_t param, const Position &pos) override; private: - bool canWalkTo(std::shared_ptr creature, Position pos, Direction moveDirection) const; - bool getFleeDirection(std::shared_ptr creature); - bool getFleePath(std::shared_ptr creature, const Position &pos, std::vector &dirList); - bool getRandomDirection(std::shared_ptr creature, Position pos); + bool canWalkTo(const std::shared_ptr &creature, Position pos, Direction moveDirection) const; + bool getFleeDirection(const std::shared_ptr &creature); + bool getFleePath(const std::shared_ptr &creature, const Position &pos, std::vector &dirList); + bool getRandomDirection(const std::shared_ptr &creature, Position pos); bool isStuck(std::shared_ptr creature, Position pos) const; std::vector m_directionsVector { diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index 105bf734c23..bf52b7dcef1 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -24,7 +24,7 @@ Spells::Spells() = default; Spells::~Spells() = default; -TalkActionResult_t Spells::playerSaySpell(std::shared_ptr player, std::string &words) { +TalkActionResult_t Spells::playerSaySpell(const std::shared_ptr &player, std::string &words) { auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); auto tile = player->getTile(); if (maxOnline > 1 && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE)) { @@ -114,7 +114,7 @@ bool Spells::hasInstantSpell(const std::string &word) const { return false; } -bool Spells::registerInstantLuaEvent(const std::shared_ptr instant) { +bool Spells::registerInstantLuaEvent(const std::shared_ptr &instant) { if (instant) { // If the spell not have the "spell:words()" return a error message const std::string &instantName = instant->getName(); @@ -138,7 +138,7 @@ bool Spells::registerInstantLuaEvent(const std::shared_ptr instant return false; } -bool Spells::registerRuneLuaEvent(const std::shared_ptr rune) { +bool Spells::registerRuneLuaEvent(const std::shared_ptr &rune) { if (rune) { uint16_t id = rune->getRuneItemId(); auto result = runes.emplace(rune->getRuneItemId(), rune); @@ -256,11 +256,11 @@ std::shared_ptr Spells::getInstantSpellByName(const std::string &n return nullptr; } -Position Spells::getCasterPosition(std::shared_ptr creature, Direction dir) { +Position Spells::getCasterPosition(const std::shared_ptr &creature, Direction dir) { return getNextPosition(dir, creature->getPosition()); } -CombatSpell::CombatSpell(const std::shared_ptr newCombat, bool newNeedTarget, bool newNeedDirection) : +CombatSpell::CombatSpell(const std::shared_ptr &newCombat, bool newNeedTarget, bool newNeedDirection) : Script(&g_spells().getScriptInterface()), m_combat(newCombat), needDirection(newNeedDirection), @@ -357,16 +357,16 @@ bool CombatSpell::castSpell(std::shared_ptr creature, std::shared_ptr< return true; } -bool CombatSpell::executeCastSpell(std::shared_ptr creature, const LuaVariant &var) const { +bool CombatSpell::executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const { // onCastSpell(creature, var) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[CombatSpell::executeCastSpell - Creature {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -381,7 +381,7 @@ bool CombatSpell::executeCastSpell(std::shared_ptr creature, const Lua return getScriptInterface()->callFunction(2); } -bool Spell::playerSpellCheck(std::shared_ptr player) const { +bool Spell::playerSpellCheck(const std::shared_ptr &player) const { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return false; } @@ -485,7 +485,7 @@ bool Spell::playerSpellCheck(std::shared_ptr player) const { return true; } -bool Spell::playerInstantSpellCheck(std::shared_ptr player, const Position &toPos) const { +bool Spell::playerInstantSpellCheck(const std::shared_ptr &player, const Position &toPos) const { if (toPos.x == 0xFFFF) { return true; } @@ -525,7 +525,7 @@ bool Spell::playerInstantSpellCheck(std::shared_ptr player, const Positi return true; } -bool Spell::playerRuneSpellCheck(std::shared_ptr player, const Position &toPos) { +bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos) { if (!playerSpellCheck(player)) { return false; } @@ -630,7 +630,7 @@ void Spell::setWheelOfDestinyBoost(WheelSpellBoost_t boost, WheelSpellGrade_t gr } } -void Spell::getCombatDataAugment(std::shared_ptr player, CombatDamage &damage) { +void Spell::getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage) { if (!(damage.instantSpellName).empty()) { const auto equippedAugmentItems = player->getEquippedAugmentItems(); for (const auto &item : equippedAugmentItems) { @@ -654,7 +654,7 @@ void Spell::getCombatDataAugment(std::shared_ptr player, CombatDamage &d } }; -int32_t Spell::calculateAugmentSpellCooldownReduction(std::shared_ptr player) const { +int32_t Spell::calculateAugmentSpellCooldownReduction(const std::shared_ptr &player) const { int32_t spellCooldown = 0; const auto equippedAugmentItems = player->getEquippedAugmentItemsByType(Augment_t::Cooldown); for (const auto &item : equippedAugmentItems) { @@ -667,7 +667,7 @@ int32_t Spell::calculateAugmentSpellCooldownReduction(std::shared_ptr pl return spellCooldown; } -void Spell::applyCooldownConditions(std::shared_ptr player) const { +void Spell::applyCooldownConditions(const std::shared_ptr &player) const { WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); bool isUpgraded = getWheelOfDestinyUpgraded() && static_cast(spellGrade) > 0; // Safety check to prevent division by zero @@ -714,7 +714,7 @@ void Spell::applyCooldownConditions(std::shared_ptr player) const { } } -void Spell::postCastSpell(std::shared_ptr player, bool finishedCast /*= true*/, bool payCost /*= true*/) const { +void Spell::postCastSpell(const std::shared_ptr &player, bool finishedCast /*= true*/, bool payCost /*= true*/) const { if (finishedCast) { if (!player->hasFlag(PlayerFlags_t::HasNoExhaustion)) { applyCooldownConditions(player); @@ -735,7 +735,7 @@ void Spell::postCastSpell(std::shared_ptr player, bool finishedCast /*= } } -void Spell::postCastSpell(std::shared_ptr player, uint32_t manaCost, uint32_t soulCost) { +void Spell::postCastSpell(const std::shared_ptr &player, uint32_t manaCost, uint32_t soulCost) { if (manaCost > 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast(manaCost)); @@ -748,7 +748,7 @@ void Spell::postCastSpell(std::shared_ptr player, uint32_t manaCost, uin } } -uint32_t Spell::getManaCost(std::shared_ptr player) const { +uint32_t Spell::getManaCost(const std::shared_ptr &player) const { WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); uint32_t manaRedution = 0; if (getWheelOfDestinyUpgraded() && static_cast(spellGrade) > 0) { @@ -897,7 +897,7 @@ bool InstantSpell::playerCastInstant(std::shared_ptr player, std::string return result; } -bool InstantSpell::canThrowSpell(std::shared_ptr creature, std::shared_ptr target) const { +bool InstantSpell::canThrowSpell(const std::shared_ptr &creature, const std::shared_ptr &target) const { const Position &fromPos = creature->getPosition(); const Position &toPos = target->getPosition(); if (fromPos.z != toPos.z || (range == -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight ? SightLine_CheckSightLineAndFloor : SightLine_NoCheck)) || (range != -1 && !g_game().canThrowObjectTo(fromPos, toPos, checkLineOfSight ? SightLine_CheckSightLineAndFloor : SightLine_NoCheck, range, range))) { @@ -946,16 +946,16 @@ bool InstantSpell::castSpell(std::shared_ptr creature, std::shared_ptr } } -bool InstantSpell::executeCastSpell(std::shared_ptr creature, const LuaVariant &var) const { +bool InstantSpell::executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const { // onCastSpell(creature, var) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[InstantSpell::executeCastSpell - Creature {} words {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), getWords()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -970,7 +970,7 @@ bool InstantSpell::executeCastSpell(std::shared_ptr creature, const Lu return getScriptInterface()->callFunction(2); } -bool InstantSpell::canCast(std::shared_ptr player) const { +bool InstantSpell::canCast(const std::shared_ptr &player) const { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return false; } @@ -992,7 +992,7 @@ bool InstantSpell::canCast(std::shared_ptr player) const { return false; } -ReturnValue RuneSpell::canExecuteAction(std::shared_ptr player, const Position &toPos) { +ReturnValue RuneSpell::canExecuteAction(const std::shared_ptr &player, const Position &toPos) { if (player->hasFlag(PlayerFlags_t::CannotUseSpells)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } @@ -1013,7 +1013,7 @@ ReturnValue RuneSpell::canExecuteAction(std::shared_ptr player, const Po return RETURNVALUE_NOERROR; } -bool RuneSpell::executeUse(std::shared_ptr player, std::shared_ptr item, const Position &, std::shared_ptr target, const Position &toPosition, bool isHotkey) { +bool RuneSpell::executeUse(const std::shared_ptr &player, const std::shared_ptr &item, const Position &, const std::shared_ptr &target, const Position &toPosition, bool isHotkey) { if (!playerRuneSpellCheck(player, toPosition)) { return false; } @@ -1081,26 +1081,26 @@ bool RuneSpell::castSpell(std::shared_ptr creature, std::shared_ptr creature, const LuaVariant &var, bool isHotkey) { +bool RuneSpell::internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) { bool result; if (isLoadedCallback()) { - result = executeCastSpell(std::move(creature), var, isHotkey); + result = executeCastSpell(creature, var, isHotkey); } else { result = false; } return result; } -bool RuneSpell::executeCastSpell(std::shared_ptr creature, const LuaVariant &var, bool isHotkey) const { +bool RuneSpell::executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) const { // onCastSpell(creature, var, isHotkey) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaEnvironment::reserveScriptEnv()) { g_logger().error("[RuneSpell::executeCastSpell - Creature {} runeId {}] " "Call stack overflow. Too many lua script calls being nested.", creature->getName(), getRuneItemId()); return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index fc23bbf9030..4e97db0356d 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -46,9 +46,9 @@ class Spells final : public Scripts { std::shared_ptr getInstantSpellById(uint16_t spellId); - TalkActionResult_t playerSaySpell(std::shared_ptr player, std::string &words); + TalkActionResult_t playerSaySpell(const std::shared_ptr &player, std::string &words); - static Position getCasterPosition(std::shared_ptr creature, Direction dir); + static Position getCasterPosition(const std::shared_ptr &creature, Direction dir); std::list getSpellsByVocation(uint16_t vocationId); @@ -58,13 +58,13 @@ class Spells final : public Scripts { [[nodiscard]] bool hasInstantSpell(const std::string &word) const; - void setInstantSpell(const std::string &word, const std::shared_ptr instant) { + void setInstantSpell(const std::string &word, const std::shared_ptr &instant) { instants.try_emplace(word, instant); } void clear(); - bool registerInstantLuaEvent(std::shared_ptr instant); - bool registerRuneLuaEvent(std::shared_ptr rune); + bool registerInstantLuaEvent(const std::shared_ptr &instant); + bool registerRuneLuaEvent(const std::shared_ptr &rune); private: std::map> runes; @@ -75,7 +75,7 @@ class Spells final : public Scripts { constexpr auto g_spells = Spells::getInstance; -using RuneSpellFunction = std::function spell, std::shared_ptr player, const Position &posTo)>; +using RuneSpellFunction = std::function spell, const auto player, const Position &posTo)>; class BaseSpell { public: @@ -92,7 +92,7 @@ class BaseSpell { class CombatSpell final : public Script, public BaseSpell, public std::enable_shared_from_this { public: // Constructor - CombatSpell(std::shared_ptr newCombat, bool newNeedTarget, bool newNeedDirection); + CombatSpell(const std::shared_ptr &newCombat, bool newNeedTarget, bool newNeedDirection); // The copy constructor and the assignment operator have been deleted to prevent accidental copying. CombatSpell(const CombatSpell &) = delete; @@ -102,7 +102,7 @@ class CombatSpell final : public Script, public BaseSpell, public std::enable_sh bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; // Scripting spell - bool executeCastSpell(std::shared_ptr creature, const LuaVariant &var) const; + bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const; bool loadScriptCombat(); std::shared_ptr getCombat() const { @@ -137,14 +137,14 @@ class Spell : public BaseSpell { m_spellId = id; } - void postCastSpell(std::shared_ptr player, bool finishedCast = true, bool payCost = true) const; - static void postCastSpell(std::shared_ptr player, uint32_t manaCost, uint32_t soulCost); + void postCastSpell(const std::shared_ptr &player, bool finishedCast = true, bool payCost = true) const; + static void postCastSpell(const std::shared_ptr &player, uint32_t manaCost, uint32_t soulCost); [[nodiscard]] virtual bool isInstant() const = 0; [[nodiscard]] bool isLearnable() const { return learnable; } - uint32_t getManaCost(std::shared_ptr player) const; + uint32_t getManaCost(const std::shared_ptr &player) const; [[nodiscard]] uint32_t getSoulCost() const { return soul; } @@ -345,14 +345,14 @@ class Spell : public BaseSpell { m_separator = newSeparator.data(); } - void getCombatDataAugment(std::shared_ptr player, CombatDamage &damage); - int32_t calculateAugmentSpellCooldownReduction(std::shared_ptr player) const; + void getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage); + int32_t calculateAugmentSpellCooldownReduction(const std::shared_ptr &player) const; protected: - void applyCooldownConditions(std::shared_ptr player) const; - bool playerSpellCheck(std::shared_ptr player) const; - bool playerInstantSpellCheck(std::shared_ptr player, const Position &toPos) const; - bool playerRuneSpellCheck(std::shared_ptr player, const Position &toPos); + void applyCooldownConditions(const std::shared_ptr &player) const; + bool playerSpellCheck(const std::shared_ptr &player) const; + bool playerInstantSpellCheck(const std::shared_ptr &player, const Position &toPos) const; + bool playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos); VocSpellMap vocSpellMap; @@ -405,7 +405,7 @@ class InstantSpell final : public Script, public Spell { bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; // Scripting spell - bool executeCastSpell(std::shared_ptr creature, const LuaVariant &var) const; + bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const; [[nodiscard]] bool isInstant() const override { return true; @@ -440,8 +440,8 @@ class InstantSpell final : public Script, public Spell { void setBlockWalls(bool w) { checkLineOfSight = w; } - bool canCast(std::shared_ptr player) const; - bool canThrowSpell(std::shared_ptr creature, std::shared_ptr target) const; + bool canCast(const std::shared_ptr &player) const; + bool canThrowSpell(const std::shared_ptr &creature, const std::shared_ptr &target) const; private: [[nodiscard]] std::string getScriptTypeName() const override { @@ -459,21 +459,21 @@ class RuneSpell final : public Action, public Spell { public: using Action::Action; - ReturnValue canExecuteAction(std::shared_ptr player, const Position &toPos) override; + ReturnValue canExecuteAction(const std::shared_ptr &player, const Position &toPos) override; bool hasOwnErrorHandler() override { return true; } - std::shared_ptr getTarget(std::shared_ptr, std::shared_ptr targetCreature, const Position &, uint8_t) const override { + std::shared_ptr getTarget(const std::shared_ptr &, std::shared_ptr targetCreature, const Position &, uint8_t) const override { return targetCreature; } - bool executeUse(std::shared_ptr player, std::shared_ptr item, const Position &fromPosition, std::shared_ptr target, const Position &toPosition, bool isHotkey) override; + bool executeUse(const std::shared_ptr &player, const std::shared_ptr &item, const Position &fromPosition, const std::shared_ptr &target, const Position &toPosition, bool isHotkey) override; bool castSpell(std::shared_ptr creature) override; bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; // Scripting spell - bool executeCastSpell(std::shared_ptr creature, const LuaVariant &var, bool isHotkey) const; + bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) const; [[nodiscard]] bool isInstant() const override { return false; @@ -499,7 +499,7 @@ class RuneSpell final : public Action, public Spell { return "onCastSpell"; } - bool internalCastSpell(std::shared_ptr creature, const LuaVariant &var, bool isHotkey); + bool internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey); uint16_t runeId = 0; uint32_t charges = 0; diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 6c15f6cf1fe..8d0a92dc389 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -168,7 +168,7 @@ void Creature::onCreatureWalk() { if (getNextStep(dir, flags)) { ReturnValue ret = g_game().internalMoveCreature(static_self_cast(), dir, flags); if (ret != RETURNVALUE_NOERROR) { - if (std::shared_ptr player = getPlayer()) { + if (const auto player = getPlayer()) { player->sendCancelMessage(ret); player->sendCancelWalk(); } @@ -287,19 +287,19 @@ void Creature::updateMapCache() { } } -void Creature::updateTileCache(std::shared_ptr newTile, int32_t dx, int32_t dy) { +void Creature::updateTileCache(const std::shared_ptr &newTile, int32_t dx, int32_t dy) { metrics::method_latency measure(__METHOD_NAME__); if (std::abs(dx) <= maxWalkCacheWidth && std::abs(dy) <= maxWalkCacheHeight) { localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx] = newTile && newTile->queryAdd(0, getCreature(), 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR; } } -void Creature::updateTileCache(std::shared_ptr upTile, const Position &pos) { +void Creature::updateTileCache(const std::shared_ptr &upTile, const Position &pos) { const Position &myPos = getPosition(); if (pos.z == myPos.z) { int32_t dx = Position::getOffsetX(pos, myPos); int32_t dy = Position::getOffsetY(pos, myPos); - updateTileCache(std::move(upTile), dx, dy); + updateTileCache(upTile, dx, dy); } } @@ -330,9 +330,9 @@ int32_t Creature::getWalkCache(const Position &pos) { return 2; } -void Creature::onAddTileItem(std::shared_ptr tileItem, const Position &pos) { +void Creature::onAddTileItem(const std::shared_ptr &tileItem, const Position &pos) { if (isMapLoaded && pos.z == getPosition().z) { - updateTileCache(std::move(tileItem), pos); + updateTileCache(tileItem, pos); } } @@ -343,7 +343,7 @@ void Creature::onUpdateTileItem(std::shared_ptr updateTile, const Position if (oldType.blockSolid || oldType.blockPathFind || newType.blockPathFind || newType.blockSolid) { if (pos.z == getPosition().z) { - updateTileCache(std::move(updateTile), pos); + updateTileCache(updateTile, pos); } } } @@ -355,7 +355,7 @@ void Creature::onRemoveTileItem(std::shared_ptr updateTile, const Position if (iType.blockSolid || iType.blockPathFind || iType.isGroundTile()) { if (pos.z == getPosition().z) { - updateTileCache(std::move(updateTile), pos); + updateTileCache(updateTile, pos); } } } @@ -394,7 +394,7 @@ void Creature::onRemoveCreature(std::shared_ptr creature, bool) { } } -void Creature::onCreatureDisappear(std::shared_ptr creature, bool isLogout) { +void Creature::onCreatureDisappear(const std::shared_ptr &creature, bool isLogout) { metrics::method_latency measure(__METHOD_NAME__); if (getAttackedCreature() == creature) { setAttackedCreature(nullptr); @@ -490,7 +490,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s handleLostSummon(configTeleportSummons); } - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (player->isExerciseTraining()) { player->setTraining(false); } @@ -884,7 +884,7 @@ void Creature::changeMana(int32_t manaChange) { } } -void Creature::gainHealth(std::shared_ptr healer, int32_t healthGain) { +void Creature::gainHealth(const std::shared_ptr &healer, int32_t healthGain) { changeHealth(healthGain); if (healer) { healer->onTargetCreatureGainHealth(static_self_cast(), healthGain); @@ -922,7 +922,7 @@ void Creature::mitigateDamage(const CombatType_t &combatType, BlockType_t &block } } -void Creature::applyAbsorbDamageModifications(std::shared_ptr attacker, int32_t &damage, CombatType_t combatType) const { +void Creature::applyAbsorbDamageModifications(const std::shared_ptr &attacker, int32_t &damage, CombatType_t combatType) const { if (combatType != COMBAT_HEALING && damage != 0) { int32_t value = getAbsorbPercent(combatType); if (value != 0) { @@ -1111,7 +1111,7 @@ void Creature::goToFollowCreature() { } } -bool Creature::canFollowMaster() { +bool Creature::canFollowMaster() const { auto master = getMaster(); if (!master) { return false; @@ -1156,7 +1156,7 @@ bool Creature::setFollowCreature(std::shared_ptr creature) { return true; } -double Creature::getDamageRatio(std::shared_ptr attacker) const { +double Creature::getDamageRatio(const std::shared_ptr &attacker) const { uint32_t totalDamage = 0; uint32_t attackerDamage = 0; @@ -1176,10 +1176,10 @@ double Creature::getDamageRatio(std::shared_ptr attacker) const { } uint64_t Creature::getGainedExperience(std::shared_ptr attacker) const { - return std::floor(getDamageRatio(std::move(attacker)) * getLostExperience()); + return std::floor(getDamageRatio(attacker) * getLostExperience()); } -void Creature::addDamagePoints(std::shared_ptr attacker, int32_t damagePoints) { +void Creature::addDamagePoints(const std::shared_ptr &attacker, int32_t damagePoints) { if (damagePoints <= 0) { return; } @@ -1254,7 +1254,7 @@ void Creature::onTickCondition(ConditionType_t type, bool &bRemove) { } void Creature::onCombatRemoveCondition(std::shared_ptr condition) { - removeCondition(std::move(condition)); + removeCondition(condition); } void Creature::onAttacked() { @@ -1265,7 +1265,7 @@ void Creature::onAttackedCreatureDrainHealth(std::shared_ptr target, i target->addDamagePoints(static_self_cast(), points); } -void Creature::onAttackedCreatureKilled(std::shared_ptr target) { +void Creature::onAttackedCreatureKilled(const std::shared_ptr &target) { metrics::method_latency measure(__METHOD_NAME__); if (target != getCreature()) { uint64_t gainExp = target->getGainedExperience(static_self_cast()); @@ -1273,7 +1273,7 @@ void Creature::onAttackedCreatureKilled(std::shared_ptr target) { } } -bool Creature::deprecatedOnKilledCreature(std::shared_ptr target, bool lastHit) { +bool Creature::deprecatedOnKilledCreature(const std::shared_ptr &target, bool lastHit) { metrics::method_latency measure(__METHOD_NAME__); auto master = getMaster(); if (master) { @@ -1319,7 +1319,7 @@ void Creature::onGainExperience(uint64_t gainExp, std::shared_ptr targ } } -bool Creature::setMaster(std::shared_ptr newMaster, bool reloadCreature /* = false*/) { +bool Creature::setMaster(const std::shared_ptr &newMaster, bool reloadCreature /* = false*/) { metrics::method_latency measure(__METHOD_NAME__); // Persists if this creature has ever been a summon this->summoned = true; @@ -1352,7 +1352,7 @@ bool Creature::setMaster(std::shared_ptr newMaster, bool reloadCreatur return true; } -bool Creature::addCondition(std::shared_ptr condition, bool attackerPlayer /* = false*/) { +bool Creature::addCondition(const std::shared_ptr &condition, bool attackerPlayer /* = false*/) { metrics::method_latency measure(__METHOD_NAME__); if (condition == nullptr) { return false; @@ -1375,7 +1375,7 @@ bool Creature::addCondition(std::shared_ptr condition, bool attackerP return false; } -bool Creature::addCombatCondition(std::shared_ptr condition, bool attackerPlayer /* = false*/) { +bool Creature::addCombatCondition(const std::shared_ptr &condition, bool attackerPlayer /* = false*/) { // Caution: condition variable could be deleted after the call to addCondition ConditionType_t type = condition->getType(); @@ -1446,7 +1446,7 @@ void Creature::removeCombatCondition(ConditionType_t type) { } } -void Creature::removeCondition(std::shared_ptr condition) { +void Creature::removeCondition(const std::shared_ptr &condition) { auto it = std::find(conditions.begin(), conditions.end(), condition); if (it == conditions.end()) { return; diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index 138e8b364c8..697d50089bc 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -40,7 +40,7 @@ static constexpr int32_t EVENT_CHECK_CREATURE_INTERVAL = (EVENT_CREATURE_THINK_I class FrozenPathingConditionCall { public: explicit FrozenPathingConditionCall(Position newTargetPos) : - targetPos(std::move(newTargetPos)) { } + targetPos(newTargetPos) { } bool operator()(const Position &startPos, const Position &testPos, const FindPathParams &fpp, int32_t &bestMatchDist) const; @@ -67,19 +67,19 @@ class Creature : virtual public Thing, public SharedObject { static constexpr double speedB = 261.29; static constexpr double speedC = -4795.01; - virtual ~Creature(); + ~Creature() override; // non-copyable Creature(const Creature &) = delete; Creature &operator=(const Creature &) = delete; - std::shared_ptr getCreature() override final { + std::shared_ptr getCreature() final { return static_self_cast(); } - std::shared_ptr getCreature() const override final { + std::shared_ptr getCreature() const final { return static_self_cast(); } - virtual std::shared_ptr getPlayer() { + std::shared_ptr getPlayer() override { return nullptr; } virtual std::shared_ptr getPlayer() const { @@ -158,13 +158,13 @@ class Creature : virtual public Thing, public SharedObject { directionLocked = locked; } - int32_t getThrowRange() const override final { + int32_t getThrowRange() const final { return 1; } bool isPushable() override { return getWalkDelay() <= 0; } - bool isRemoved() override final { + bool isRemoved() final { return isInternalRemoved; } virtual bool canSeeInvisibility() const { @@ -272,13 +272,13 @@ class Creature : virtual public Thing, public SharedObject { void iconChanged(); - const Outfit_t getCurrentOutfit() const { + Outfit_t getCurrentOutfit() const { return currentOutfit; } void setCurrentOutfit(Outfit_t outfit) { currentOutfit = outfit; } - const Outfit_t getDefaultOutfit() const { + Outfit_t getDefaultOutfit() const { return defaultOutfit; } bool isWearingSupportOutfit() const { @@ -344,9 +344,9 @@ class Creature : virtual public Thing, public SharedObject { void mitigateDamage(const CombatType_t &combatType, BlockType_t &blockType, int32_t &damage) const; virtual BlockType_t blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false); - void applyAbsorbDamageModifications(std::shared_ptr attacker, int32_t &damage, CombatType_t combatType) const; + void applyAbsorbDamageModifications(const std::shared_ptr &attacker, int32_t &damage, CombatType_t combatType) const; - bool setMaster(std::shared_ptr newMaster, bool reloadCreature = false); + bool setMaster(const std::shared_ptr &newMaster, bool reloadCreature = false); void removeMaster() { if (getMaster()) { @@ -392,11 +392,11 @@ class Creature : virtual public Thing, public SharedObject { return SPEECHBUBBLE_NONE; } - bool addCondition(std::shared_ptr condition, bool attackerPlayer = false); - bool addCombatCondition(std::shared_ptr condition, bool attackerPlayer = false); + bool addCondition(const std::shared_ptr &condition, bool attackerPlayer = false); + bool addCombatCondition(const std::shared_ptr &condition, bool attackerPlayer = false); void removeCondition(ConditionType_t conditionType, ConditionId_t conditionId, bool force = false); void removeCondition(ConditionType_t type); - void removeCondition(std::shared_ptr condition); + void removeCondition(const std::shared_ptr &condition); void removeCombatCondition(ConditionType_t type); std::shared_ptr getCondition(ConditionType_t type) const; std::shared_ptr getCondition(ConditionType_t type, ConditionId_t conditionId, uint32_t subId = 0) const; @@ -424,7 +424,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void changeHealth(int32_t healthChange, bool sendHealthChange = true); virtual void changeMana(int32_t manaChange); - void gainHealth(std::shared_ptr attacker, int32_t healthGain); + void gainHealth(const std::shared_ptr &attacker, int32_t healthGain); virtual void drainHealth(std::shared_ptr attacker, int32_t damage); virtual void drainMana(std::shared_ptr attacker, int32_t manaLoss); @@ -434,7 +434,7 @@ class Creature : virtual public Thing, public SharedObject { void onDeath(); virtual uint64_t getGainedExperience(std::shared_ptr attacker) const; - void addDamagePoints(std::shared_ptr attacker, int32_t damagePoints); + void addDamagePoints(const std::shared_ptr &attacker, int32_t damagePoints); bool hasBeenAttacked(uint32_t attackerId); // combat event functions @@ -447,11 +447,11 @@ class Creature : virtual public Thing, public SharedObject { virtual void onAttacked(); virtual void onAttackedCreatureDrainHealth(std::shared_ptr target, int32_t points); virtual void onTargetCreatureGainHealth(std::shared_ptr, int32_t) { } - void onAttackedCreatureKilled(std::shared_ptr target); + void onAttackedCreatureKilled(const std::shared_ptr &target); /** * @deprecated -- This is here to trigger the deprecated onKill events in lua */ - bool deprecatedOnKilledCreature(std::shared_ptr target, bool lastHit); + bool deprecatedOnKilledCreature(const std::shared_ptr &target, bool lastHit); virtual bool onKilledPlayer([[maybe_unused]] const std::shared_ptr &target, [[maybe_unused]] bool lastHit) { return false; }; @@ -477,7 +477,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void turnToCreature(std::shared_ptr creature); - void onAddTileItem(std::shared_ptr tile, const Position &pos); + void onAddTileItem(const std::shared_ptr &tile, const Position &pos); virtual void onUpdateTileItem(std::shared_ptr tile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType); virtual void onRemoveTileItem(std::shared_ptr tile, const Position &pos, const ItemType &iType, std::shared_ptr item); @@ -537,11 +537,11 @@ class Creature : virtual public Thing, public SharedObject { bool registerCreatureEvent(const std::string &name); bool unregisterCreatureEvent(const std::string &name); - std::shared_ptr getParent() override final { + std::shared_ptr getParent() final { return getTile(); } - void setParent(std::weak_ptr cylinder) override final { + void setParent(std::weak_ptr cylinder) final { const auto oldGroundSpeed = walk.groundSpeed; walk.groundSpeed = 150; @@ -563,11 +563,11 @@ class Creature : virtual public Thing, public SharedObject { } } - const Position &getPosition() override final { + const Position &getPosition() final { return position; } - std::shared_ptr getTile() override final { + std::shared_ptr getTile() final { return m_tile.lock(); } @@ -582,7 +582,7 @@ class Creature : virtual public Thing, public SharedObject { static bool canSee(const Position &myPos, const Position &pos, int32_t viewRangeX, int32_t viewRangeY); - double getDamageRatio(std::shared_ptr attacker) const; + double getDamageRatio(const std::shared_ptr &attacker) const; bool getPathTo(const Position &targetPos, std::vector &dirList, const FindPathParams &fpp); bool getPathTo(const Position &targetPos, std::vector &dirList, int32_t minTargetDist, int32_t maxTargetDist, bool fullPathSearch = true, bool clearSight = true, int32_t maxSearchDist = 7); @@ -804,9 +804,9 @@ class Creature : virtual public Thing, public SharedObject { CreatureEventList getCreatureEvents(CreatureEventType_t type); void updateMapCache(); - void updateTileCache(std::shared_ptr tile, int32_t dx, int32_t dy); - void updateTileCache(std::shared_ptr tile, const Position &pos); - void onCreatureDisappear(std::shared_ptr creature, bool isLogout); + void updateTileCache(const std::shared_ptr &tile, int32_t dx, int32_t dy); + void updateTileCache(const std::shared_ptr &tile, const Position &pos); + void onCreatureDisappear(const std::shared_ptr &creature, bool isLogout); virtual void doAttacking(uint32_t) { } virtual bool hasExtraSwing() { return false; @@ -829,7 +829,7 @@ class Creature : virtual public Thing, public SharedObject { friend class CreatureFunctions; private: - bool canFollowMaster(); + bool canFollowMaster() const; bool isLostSummon(); void handleLostSummon(bool teleportSummons); diff --git a/src/creatures/creatures_definitions.hpp b/src/creatures/creatures_definitions.hpp index 410349a67fb..0eeeef7fc1d 100644 --- a/src/creatures/creatures_definitions.hpp +++ b/src/creatures/creatures_definitions.hpp @@ -11,6 +11,7 @@ #ifndef USE_PRECOMPILED_HEADERS #include + #include #include #include #include @@ -1370,7 +1371,7 @@ struct CreatureIcon { explicit constexpr CreatureIcon(CreatureIconQuests_t quest, uint16_t count = 0) : category(CreatureIconCategory_t::Quests), quest(quest), count(count) { } - CreatureIconCategory_t category; + CreatureIconCategory_t category {}; CreatureIconModifications_t modification = CreatureIconModifications_t::None; CreatureIconQuests_t quest = CreatureIconQuests_t::None; uint16_t count = 0; @@ -1399,7 +1400,7 @@ struct CreatureIcon { struct Position; struct VIPEntry { - VIPEntry(uint32_t initGuid, const std::string &initName, const std::string &initDescription, uint32_t initIcon, bool initNotify) : + VIPEntry(uint32_t initGuid, std::string initName, std::string initDescription, uint32_t initIcon, bool initNotify) : guid(initGuid), name(std::move(initName)), description(std::move(initDescription)), @@ -1407,20 +1408,20 @@ struct VIPEntry { notify(initNotify) { } uint32_t guid = 0; - std::string name = ""; - std::string description = ""; + std::string name; + std::string description; uint32_t icon = 0; bool notify = false; }; struct VIPGroupEntry { - VIPGroupEntry(uint8_t initId, const std::string &initName, bool initCustomizable) : + VIPGroupEntry(uint8_t initId, std::string initName, bool initCustomizable) : id(initId), name(std::move(initName)), customizable(initCustomizable) { } uint8_t id = 0; - std::string name = ""; + std::string name; bool customizable = false; }; @@ -1487,7 +1488,7 @@ struct MarketOffer { struct MarketOfferEx { MarketOfferEx() = default; - MarketOfferEx(MarketOfferEx &&other) : + MarketOfferEx(MarketOfferEx &&other) noexcept : id(other.id), playerId(other.playerId), timestamp(other.timestamp), @@ -1499,15 +1500,15 @@ struct MarketOfferEx { tier(other.tier), playerName(std::move(other.playerName)) { } - uint32_t id; - uint32_t playerId; - uint32_t timestamp; - uint64_t price; - uint16_t amount; - uint16_t counter; - uint16_t itemId; - MarketAction_t type; - uint8_t tier; + uint32_t id {}; + uint32_t playerId {}; + uint32_t timestamp {}; + uint64_t price {}; + uint16_t amount {}; + uint16_t counter {}; + uint16_t itemId {}; + MarketAction_t type {}; + uint8_t tier {}; std::string playerName; }; diff --git a/src/creatures/interactions/chat.cpp b/src/creatures/interactions/chat.cpp index 900247e457a..70b46c34246 100644 --- a/src/creatures/interactions/chat.cpp +++ b/src/creatures/interactions/chat.cpp @@ -136,21 +136,21 @@ bool ChatChannel::talk(const std::shared_ptr &fromPlayer, SpeakClasses t return true; } -bool ChatChannel::executeCanJoinEvent(const std::shared_ptr &player) { +bool ChatChannel::executeCanJoinEvent(const std::shared_ptr &player) const { if (canJoinEvent == -1) { return true; } // canJoin(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[CanJoinChannelEvent::execute - Player {}, on channel {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(canJoinEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -162,21 +162,21 @@ bool ChatChannel::executeCanJoinEvent(const std::shared_ptr &player) { return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnJoinEvent(const std::shared_ptr &player) { +bool ChatChannel::executeOnJoinEvent(const std::shared_ptr &player) const { if (onJoinEvent == -1) { return true; } // onJoin(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[OnJoinChannelEvent::execute - Player {}, on channel {}] " "Call stack overflow. Too many lua script calls being nested", player->getName(), getName()); return false; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(onJoinEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -188,21 +188,21 @@ bool ChatChannel::executeOnJoinEvent(const std::shared_ptr &player) { return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnLeaveEvent(const std::shared_ptr &player) { +bool ChatChannel::executeOnLeaveEvent(const std::shared_ptr &player) const { if (onLeaveEvent == -1) { return true; } // onLeave(player) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[OnLeaveChannelEvent::execute - Player {}, on channel {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), getName()); return false; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(onLeaveEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -214,21 +214,21 @@ bool ChatChannel::executeOnLeaveEvent(const std::shared_ptr &player) { return scriptInterface->callFunction(1); } -bool ChatChannel::executeOnSpeakEvent(const std::shared_ptr &player, SpeakClasses &type, const std::string &message) { +bool ChatChannel::executeOnSpeakEvent(const std::shared_ptr &player, SpeakClasses &type, const std::string &message) const { if (onSpeakEvent == -1) { return true; } // onSpeak(player, type, message) LuaScriptInterface* scriptInterface = g_chat().getScriptInterface(); - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[OnSpeakChannelEvent::execute - Player {}, type {}] " "Call stack overflow. Too many lua script calls being nested.", player->getName(), fmt::underlying(type)); return false; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(onSpeakEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -242,7 +242,7 @@ bool ChatChannel::executeOnSpeakEvent(const std::shared_ptr &player, Spe bool result = false; int size0 = lua_gettop(L); - int ret = scriptInterface->protectedCall(L, 3, 1); + int ret = LuaScriptInterface::protectedCall(L, 3, 1); if (ret != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else if (lua_gettop(L) > 0) { @@ -258,7 +258,7 @@ bool ChatChannel::executeOnSpeakEvent(const std::shared_ptr &player, Spe if ((lua_gettop(L) + 4) != size0) { LuaScriptInterface::reportError(nullptr, "Stack size changed!"); } - scriptInterface->resetScriptEnv(); + LuaScriptInterface::resetScriptEnv(); return result; } @@ -279,7 +279,7 @@ bool Chat::load() { } for (auto channelNode : doc.child("channels").children()) { - uint16_t channelId = pugi::cast(channelNode.attribute("id").value()); + auto channelId = pugi::cast(channelNode.attribute("id").value()); std::string channelName = channelNode.attribute("name").as_string(); bool isPublic = channelNode.attribute("public").as_bool(); pugi::xml_attribute scriptAttribute = channelNode.attribute("script"); diff --git a/src/creatures/interactions/chat.hpp b/src/creatures/interactions/chat.hpp index 3643086184c..59c190fe2c1 100644 --- a/src/creatures/interactions/chat.hpp +++ b/src/creatures/interactions/chat.hpp @@ -56,10 +56,10 @@ class ChatChannel { return publicChannel; } - bool executeOnJoinEvent(const std::shared_ptr &player); - bool executeCanJoinEvent(const std::shared_ptr &player); - bool executeOnLeaveEvent(const std::shared_ptr &player); - bool executeOnSpeakEvent(const std::shared_ptr &player, SpeakClasses &type, const std::string &message); + bool executeOnJoinEvent(const std::shared_ptr &player) const; + bool executeCanJoinEvent(const std::shared_ptr &player) const; + bool executeOnLeaveEvent(const std::shared_ptr &player) const; + bool executeOnSpeakEvent(const std::shared_ptr &player, SpeakClasses &type, const std::string &message) const; protected: UsersMap users; diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index 3ae73f8dc7c..98a08e33c5a 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -31,7 +31,7 @@ std::shared_ptr Monster::createMonster(const std::string &name) { return std::make_shared(mType); } -Monster::Monster(const std::shared_ptr mType) : +Monster::Monster(const std::shared_ptr &mType) : Creature(), nameDescription(asLowerCaseString(mType->nameDescription)), mType(mType) { @@ -403,7 +403,7 @@ void Monster::clearFriendList() { friendList.clear(); } -void Monster::onCreatureFound(std::shared_ptr creature, bool pushFront /* = false*/) { +void Monster::onCreatureFound(const std::shared_ptr &creature, bool pushFront /* = false*/) { if (isFriend(creature)) { addFriend(creature); } @@ -415,8 +415,8 @@ void Monster::onCreatureFound(std::shared_ptr creature, bool pushFront updateIdleStatus(); } -void Monster::onCreatureEnter(std::shared_ptr creature) { - onCreatureFound(std::move(creature), true); +void Monster::onCreatureEnter(const std::shared_ptr &creature) { + onCreatureFound(creature, true); } bool Monster::isFriend(const std::shared_ptr &creature) const { @@ -463,7 +463,7 @@ bool Monster::isOpponent(const std::shared_ptr &creature) const { return false; } -void Monster::onCreatureLeave(std::shared_ptr creature) { +void Monster::onCreatureLeave(const std::shared_ptr &creature) { // update friendList if (isFriend(creature)) { removeFriend(creature); @@ -647,7 +647,7 @@ BlockType_t Monster::blockHit(std::shared_ptr attacker, CombatType_t c } // Wheel of destiny - std::shared_ptr player = attacker ? attacker->getPlayer() : nullptr; + const auto player = attacker ? attacker->getPlayer() : nullptr; if (player && player->wheel()->getInstant("Ballistic Mastery")) { elementMod -= player->wheel()->checkElementSensitiveReduction(combatType); } @@ -664,7 +664,7 @@ BlockType_t Monster::blockHit(std::shared_ptr attacker, CombatType_t c return blockType; } -bool Monster::isTarget(std::shared_ptr creature) { +bool Monster::isTarget(const std::shared_ptr &creature) { if (creature->isRemoved() || !creature->isAttackable() || creature->getZoneType() == ZONE_PROTECTION || !canSeeCreature(creature)) { return false; } @@ -1113,7 +1113,7 @@ void Monster::onThinkSound(uint32_t interval) { } } -bool Monster::pushItem(std::shared_ptr item, const Direction &nextDirection) { +bool Monster::pushItem(const std::shared_ptr &item, const Direction &nextDirection) { const Position ¢erPos = item->getPosition(); for (const auto &[x, y] : getPushItemLocationOptions(nextDirection)) { Position tryPos(centerPos.x + x, centerPos.y + y, centerPos.z); @@ -1125,7 +1125,7 @@ bool Monster::pushItem(std::shared_ptr item, const Direction &nextDirectio return false; } -void Monster::pushItems(std::shared_ptr tile, const Direction &nextDirection) { +void Monster::pushItems(const std::shared_ptr &tile, const Direction &nextDirection) { // We can not use iterators here since we can push the item to another tile // which will invalidate the iterator. // start from the end to minimize the amount of traffic @@ -1149,7 +1149,7 @@ void Monster::pushItems(std::shared_ptr tile, const Direction &nextDirecti } } -bool Monster::pushCreature(std::shared_ptr creature) { +bool Monster::pushCreature(const std::shared_ptr &creature) { static std::vector dirList { DIRECTION_NORTH, DIRECTION_WEST, DIRECTION_EAST, @@ -1167,7 +1167,7 @@ bool Monster::pushCreature(std::shared_ptr creature) { return false; } -void Monster::pushCreatures(std::shared_ptr tile) { +void Monster::pushCreatures(const std::shared_ptr &tile) { // We can not use iterators here since we can push a creature to another tile // which will invalidate the iterator. if (CreatureVector* creatures = tile->getCreatures()) { @@ -2094,7 +2094,7 @@ bool Monster::challengeCreature(std::shared_ptr creature, int targetCh challengeFocusDuration = targetChangeCooldown; targetChangeTicks = 0; // Wheel of destiny - std::shared_ptr player = creature ? creature->getPlayer() : nullptr; + const auto player = creature ? creature->getPlayer() : nullptr; if (player && !player->isRemoved()) { player->wheel()->healIfBattleHealingActive(); } diff --git a/src/creatures/monsters/monster.hpp b/src/creatures/monsters/monster.hpp index 061ad2b9879..9a43bc614ad 100644 --- a/src/creatures/monsters/monster.hpp +++ b/src/creatures/monsters/monster.hpp @@ -22,7 +22,7 @@ class Monster final : public Creature { static int32_t despawnRange; static int32_t despawnRadius; - explicit Monster(std::shared_ptr mType); + explicit Monster(const std::shared_ptr &mType); // non-copyable Monster(const Monster &) = delete; @@ -217,7 +217,7 @@ class Monster final : public Creature { return list; } - bool isTarget(std::shared_ptr creature); + bool isTarget(const std::shared_ptr &creature); bool isFleeing() const { return !isSummon() && getHealth() <= runAwayHealth && challengeFocusDuration <= 0 && challengeMeleeDuration <= 0; } @@ -402,9 +402,9 @@ class Monster final : public Creature { bool hazardDamageBoost = false; bool hazardDefenseBoost = false; - void onCreatureEnter(std::shared_ptr creature); - void onCreatureLeave(std::shared_ptr creature); - void onCreatureFound(std::shared_ptr creature, bool pushFront = false); + void onCreatureEnter(const std::shared_ptr &creature); + void onCreatureLeave(const std::shared_ptr &creature); + void onCreatureFound(const std::shared_ptr &creature, bool pushFront = false); void updateLookDirection(); @@ -433,10 +433,10 @@ class Monster final : public Creature { bool isInSpawnRange(const Position &pos) const; bool canWalkTo(Position pos, Direction direction); - static bool pushItem(std::shared_ptr item, const Direction &nextDirection); - static void pushItems(std::shared_ptr tile, const Direction &nextDirection); - static bool pushCreature(std::shared_ptr creature); - static void pushCreatures(std::shared_ptr tile); + static bool pushItem(const std::shared_ptr &item, const Direction &nextDirection); + static void pushItems(const std::shared_ptr &tile, const Direction &nextDirection); + static bool pushCreature(const std::shared_ptr &creature); + static void pushCreatures(const std::shared_ptr &tile); void onThinkTarget(uint32_t interval); void onThinkYell(uint32_t interval); diff --git a/src/creatures/monsters/monsters.cpp b/src/creatures/monsters/monsters.cpp index 78358f69d87..c0d36694363 100644 --- a/src/creatures/monsters/monsters.cpp +++ b/src/creatures/monsters/monsters.cpp @@ -16,7 +16,7 @@ #include "game/game.hpp" #include "items/weapons/weapons.hpp" -void MonsterType::loadLoot(const std::shared_ptr monsterType, LootBlock lootBlock) { +void MonsterType::loadLoot(const std::shared_ptr &monsterType, LootBlock lootBlock) { if (lootBlock.childLoot.empty()) { bool isContainer = Item::items[lootBlock.id].isContainer(); if (isContainer) { @@ -30,7 +30,7 @@ void MonsterType::loadLoot(const std::shared_ptr monsterType, LootB } } -bool MonsterType::canSpawn(const Position &pos) { +bool MonsterType::canSpawn(const Position &pos) const { bool canSpawn = true; bool isDay = g_game().gameIsDay(); @@ -52,7 +52,7 @@ std::shared_ptr Monsters::getDamageCondition(ConditionType_t co return condition; } -bool Monsters::deserializeSpell(const std::shared_ptr spell, spellBlock_t &sb, const std::string &description) { +bool Monsters::deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description) { if (!spell->scriptName.empty()) { spell->isScripted = true; } else if (!spell->name.empty()) { @@ -321,7 +321,7 @@ std::shared_ptr Monsters::getMonsterTypeByRaceId(uint16_t raceId, b return g_monsters().getMonsterType(it->second); } -bool Monsters::tryAddMonsterType(const std::string &name, const std::shared_ptr mType) { +bool Monsters::tryAddMonsterType(const std::string &name, const std::shared_ptr &mType) { std::string lowerName = asLowerCaseString(name); if (monsters.find(lowerName) != monsters.end()) { g_logger().debug("[{}] the monster with name '{}' already exist", __FUNCTION__, name); diff --git a/src/creatures/monsters/monsters.hpp b/src/creatures/monsters/monsters.hpp index 171bef68e38..fa6dedd41a8 100644 --- a/src/creatures/monsters/monsters.hpp +++ b/src/creatures/monsters/monsters.hpp @@ -203,9 +203,9 @@ class MonsterType { return !info.bosstiaryClass.empty(); } - void loadLoot(std::shared_ptr monsterType, LootBlock lootblock); + void loadLoot(const std::shared_ptr &monsterType, LootBlock lootblock); - bool canSpawn(const Position &pos); + bool canSpawn(const Position &pos) const; }; class MonsterSpell { @@ -215,8 +215,8 @@ class MonsterSpell { MonsterSpell(const MonsterSpell &) = delete; MonsterSpell &operator=(const MonsterSpell &) = delete; - std::string name = ""; - std::string scriptName = ""; + std::string name; + std::string scriptName; uint8_t chance = 100; uint8_t range = 0; @@ -244,7 +244,7 @@ class MonsterSpell { bool isMelee = false; Outfit_t outfit = {}; - std::string outfitMonster = ""; + std::string outfitMonster; uint16_t outfitItem = 0; ShootType_t shoot = CONST_ANI_NONE; @@ -273,8 +273,8 @@ class Monsters { std::shared_ptr getMonsterType(const std::string &name, bool silent = false) const; std::shared_ptr getMonsterTypeByRaceId(uint16_t raceId, bool isBoss = false) const; - bool tryAddMonsterType(const std::string &name, std::shared_ptr mType); - bool deserializeSpell(std::shared_ptr spell, spellBlock_t &sb, const std::string &description = ""); + bool tryAddMonsterType(const std::string &name, const std::shared_ptr &mType); + bool deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description = ""); std::unique_ptr scriptInterface; std::map> monsters; diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index ca8f4584775..960cb98acf2 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -166,7 +166,7 @@ bool SpawnMonster::isInSpawnMonsterZone(const Position &pos) { return SpawnsMonster::isInZone(centerPos, radius, pos); } -bool SpawnMonster::spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr monsterType, bool startup /*= false*/) { +bool SpawnMonster::spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr &monsterType, bool startup /*= false*/) { if (spawnedMonsterMap.contains(spawnMonsterId)) { return false; } @@ -271,7 +271,7 @@ void SpawnMonster::checkSpawnMonster() { } } -void SpawnMonster::scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr mType, uint16_t interval, bool startup /*= false*/) { +void SpawnMonster::scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr &mType, uint16_t interval, bool startup /*= false*/) { if (interval <= 0) { spawnMonster(spawnMonsterId, sb, mType, startup); } else { @@ -360,7 +360,7 @@ bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Dire return true; } -void SpawnMonster::removeMonster(std::shared_ptr monster) { +void SpawnMonster::removeMonster(const std::shared_ptr &monster) { uint32_t spawnMonsterId = 0; for (const auto &[id, m] : spawnedMonsterMap) { if (m == monster) { diff --git a/src/creatures/monsters/spawns/spawn_monster.hpp b/src/creatures/monsters/spawns/spawn_monster.hpp index 81a08973cb7..ef2ef23efcd 100644 --- a/src/creatures/monsters/spawns/spawn_monster.hpp +++ b/src/creatures/monsters/spawns/spawn_monster.hpp @@ -56,7 +56,7 @@ class SpawnMonster { } bool addMonster(const std::string &name, const Position &pos, Direction dir, uint32_t interval, uint32_t weight = 1); - void removeMonster(std::shared_ptr monster); + void removeMonster(const std::shared_ptr &monster); void removeMonsters(); uint32_t getInterval() const { @@ -90,9 +90,9 @@ class SpawnMonster { uint32_t checkSpawnMonsterEvent = 0; static bool findPlayer(const Position &pos); - bool spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, std::shared_ptr monsterType, bool startup = false); + bool spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr &monsterType, bool startup = false); void checkSpawnMonster(); - void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, std::shared_ptr monsterType, uint16_t interval, bool startup = false); + void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr &monsterType, uint16_t interval, bool startup = false); }; class SpawnsMonster { diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 6d38524aef3..39be8029dce 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -144,7 +144,7 @@ void Npc::manageIdle() { } } -void Npc::onPlayerAppear(std::shared_ptr player) { +void Npc::onPlayerAppear(const std::shared_ptr &player) { if (player->hasFlag(PlayerFlags_t::IgnoredByNpcs) || playerSpectators.contains(player)) { return; } @@ -152,7 +152,7 @@ void Npc::onPlayerAppear(std::shared_ptr player) { manageIdle(); } -void Npc::onPlayerDisappear(std::shared_ptr player) { +void Npc::onPlayerDisappear(const std::shared_ptr &player) { removePlayerInteraction(player); if (!player->hasFlag(PlayerFlags_t::IgnoredByNpcs) && playerSpectators.contains(player)) { playerSpectators.erase(player); @@ -228,7 +228,7 @@ void Npc::onThink(uint32_t interval) { } } -void Npc::onPlayerBuyItem(std::shared_ptr player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore, bool inBackpacks) { +void Npc::onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore, bool inBackpacks) { if (player == nullptr) { g_logger().error("[Npc::onPlayerBuyItem] - Player is nullptr"); return; @@ -302,13 +302,13 @@ void Npc::onPlayerBuyItem(std::shared_ptr player, uint16_t itemId, uint8 } } -void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore) { +void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore) { uint64_t totalPrice = 0; - onPlayerSellItem(std::move(player), itemId, subType, amount, ignore, totalPrice); + onPlayerSellItem(player, itemId, subType, amount, ignore, totalPrice); } void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, uint64_t totalPrice) { - std::shared_ptr player = g_game().getPlayerByID(playerId); + const auto player = g_game().getPlayerByID(playerId); if (!player) { return; } @@ -358,7 +358,7 @@ void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, u } } -void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore, uint64_t &totalPrice, std::shared_ptr parent /*= nullptr*/) { +void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemId, uint8_t subType, uint16_t amount, bool ignore, uint64_t &totalPrice, const std::shared_ptr &parent /*= nullptr*/) { if (!player) { return; } @@ -442,7 +442,7 @@ void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint } } -void Npc::onPlayerCheckItem(std::shared_ptr player, uint16_t itemId, uint8_t subType) { +void Npc::onPlayerCheckItem(const std::shared_ptr &player, uint16_t itemId, uint8_t subType) { if (!player) { return; } @@ -461,8 +461,8 @@ void Npc::onPlayerCheckItem(std::shared_ptr player, uint16_t itemId, uin } } -void Npc::onPlayerCloseChannel(std::shared_ptr creature) { - std::shared_ptr player = creature->getPlayer(); +void Npc::onPlayerCloseChannel(const std::shared_ptr &creature) { + const auto player = creature->getPlayer(); if (!player) { return; } @@ -582,7 +582,7 @@ void Npc::setPlayerInteraction(uint32_t playerId, uint16_t topicId /*= 0*/) { playerInteractions[playerId] = topicId; } -void Npc::removePlayerInteraction(std::shared_ptr player) { +void Npc::removePlayerInteraction(const std::shared_ptr &player) { if (playerInteractions.contains(player->getID())) { playerInteractions.erase(player->getID()); player->closeShopWindow(); @@ -664,7 +664,7 @@ void Npc::closeAllShopWindows() { shopPlayers.clear(); } -void Npc::handlePlayerMove(std::shared_ptr player, const Position &newPos) { +void Npc::handlePlayerMove(const std::shared_ptr &player, const Position &newPos) { if (!canInteract(newPos)) { removePlayerInteraction(player); } diff --git a/src/creatures/npcs/npc.hpp b/src/creatures/npcs/npc.hpp index c246aa4b68d..7f5fc7d54aa 100644 --- a/src/creatures/npcs/npc.hpp +++ b/src/creatures/npcs/npc.hpp @@ -126,7 +126,7 @@ class Npc final : public Creature { } void setPlayerInteraction(uint32_t playerId, uint16_t topicId = 0); - void removePlayerInteraction(std::shared_ptr player); + void removePlayerInteraction(const std::shared_ptr &player); void resetPlayerInteractions(); bool isInteractingWithPlayer(uint32_t playerId) { @@ -149,12 +149,12 @@ class Npc final : public Creature { void onCreatureMove(const std::shared_ptr &creature, const std::shared_ptr &newTile, const Position &newPos, const std::shared_ptr &oldTile, const Position &oldPos, bool teleport) override; void onCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text) override; void onThink(uint32_t interval) override; - void onPlayerBuyItem(std::shared_ptr player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, bool inBackpacks); + void onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, bool inBackpacks); void onPlayerSellAllLoot(uint32_t playerId, uint16_t itemid, bool ignore, uint64_t totalPrice); - void onPlayerSellItem(std::shared_ptr player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore); - void onPlayerSellItem(std::shared_ptr player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, uint64_t &totalPrice, std::shared_ptr parent = nullptr); - void onPlayerCheckItem(std::shared_ptr player, uint16_t itemid, uint8_t count); - void onPlayerCloseChannel(std::shared_ptr creature); + void onPlayerSellItem(const std::shared_ptr &player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore); + void onPlayerSellItem(const std::shared_ptr &player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, uint64_t &totalPrice, const std::shared_ptr &parent = nullptr); + void onPlayerCheckItem(const std::shared_ptr &player, uint16_t itemid, uint8_t count); + void onPlayerCloseChannel(const std::shared_ptr &creature); void onPlacedCreature() override; bool canWalkTo(const Position &fromPos, Direction dir); @@ -205,10 +205,10 @@ class Npc final : public Creature { friend class LuaScriptInterface; friend class Map; - void onPlayerAppear(std::shared_ptr player); - void onPlayerDisappear(std::shared_ptr player); + void onPlayerAppear(const std::shared_ptr &player); + void onPlayerDisappear(const std::shared_ptr &player); void manageIdle(); - void handlePlayerMove(std::shared_ptr player, const Position &newPos); + void handlePlayerMove(const std::shared_ptr &player, const Position &newPos); void loadPlayerSpectators(); }; diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index 6fe7f0b8320..bb29b2b1bec 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -17,7 +17,7 @@ #include "lua/scripts/scripts.hpp" #include "game/game.hpp" -bool NpcType::canSpawn(const Position &pos) { +bool NpcType::canSpawn(const Position &pos) const { bool canSpawn = true; bool isDay = g_game().gameIsDay(); diff --git a/src/creatures/npcs/npcs.hpp b/src/creatures/npcs/npcs.hpp index ab5e700caea..d97ec6435e2 100644 --- a/src/creatures/npcs/npcs.hpp +++ b/src/creatures/npcs/npcs.hpp @@ -90,7 +90,7 @@ class NpcType : public SharedObject { void loadShop(const std::shared_ptr &npcType, ShopBlock shopBlock); bool loadCallback(LuaScriptInterface* scriptInterface); - bool canSpawn(const Position &pos); + bool canSpawn(const Position &pos) const; }; class Npcs { diff --git a/src/creatures/npcs/spawns/spawn_npc.cpp b/src/creatures/npcs/spawns/spawn_npc.cpp index 694822c2386..8f7d32aff98 100644 --- a/src/creatures/npcs/spawns/spawn_npc.cpp +++ b/src/creatures/npcs/spawns/spawn_npc.cpp @@ -268,7 +268,7 @@ bool SpawnNpc::addNpc(const std::string &name, const Position &pos, Direction di return true; } -void SpawnNpc::removeNpc(std::shared_ptr npc) { +void SpawnNpc::removeNpc(const std::shared_ptr &npc) { for (auto it = spawnedNpcMap.begin(), end = spawnedNpcMap.end(); it != end; ++it) { if (it->second == npc) { spawnedNpcMap.erase(it); diff --git a/src/creatures/npcs/spawns/spawn_npc.hpp b/src/creatures/npcs/spawns/spawn_npc.hpp index b0d0ab8622a..8b2b7c7e591 100644 --- a/src/creatures/npcs/spawns/spawn_npc.hpp +++ b/src/creatures/npcs/spawns/spawn_npc.hpp @@ -27,14 +27,14 @@ class SpawnNpc : public SharedObject { public: SpawnNpc(Position initPos, int32_t initRadius) : centerPos(initPos), radius(initRadius) { } - ~SpawnNpc(); + ~SpawnNpc() override; // non-copyable SpawnNpc(const SpawnNpc &) = delete; SpawnNpc &operator=(const SpawnNpc &) = delete; bool addNpc(const std::string &name, const Position &pos, Direction dir, uint32_t interval); - void removeNpc(std::shared_ptr npc); + void removeNpc(const std::shared_ptr &npc); uint32_t getInterval() const { return interval; diff --git a/src/creatures/players/cyclopedia/player_badge.hpp b/src/creatures/players/cyclopedia/player_badge.hpp index 7bf28c0c302..ed37a69faa8 100644 --- a/src/creatures/players/cyclopedia/player_badge.hpp +++ b/src/creatures/players/cyclopedia/player_badge.hpp @@ -16,7 +16,7 @@ class KV; struct Badge { uint8_t m_id = 0; - CyclopediaBadge_t m_type; + CyclopediaBadge_t m_type {}; std::string m_name; uint16_t m_amount = 0; diff --git a/src/creatures/players/cyclopedia/player_cyclopedia.cpp b/src/creatures/players/cyclopedia/player_cyclopedia.cpp index eb7e05d2338..c74d385f964 100644 --- a/src/creatures/players/cyclopedia/player_cyclopedia.cpp +++ b/src/creatures/players/cyclopedia/player_cyclopedia.cpp @@ -42,7 +42,7 @@ void PlayerCyclopedia::loadDeathHistory(uint16_t page, uint16_t entriesPerPage) uint32_t playerID = m_player.getID(); std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { - std::shared_ptr player = g_game().getPlayerByID(playerID); + const auto player = g_game().getPlayerByID(playerID); if (!player) { return; } @@ -92,7 +92,7 @@ void PlayerCyclopedia::loadRecentKills(uint16_t page, uint16_t entriesPerPage) { uint32_t playerID = m_player.getID(); std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { - std::shared_ptr player = g_game().getPlayerByID(playerID); + const auto player = g_game().getPlayerByID(playerID); if (!player) { return; } diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index 76f1d955f10..3cf7936e69d 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -17,7 +17,7 @@ #include "lua/callbacks/event_callback.hpp" #include "lua/callbacks/events_callbacks.hpp" -std::shared_ptr Party::create(std::shared_ptr leader) { +std::shared_ptr Party::create(const std::shared_ptr &leader) { auto party = std::make_shared(); party->m_leader = leader; leader->setParty(party); @@ -77,7 +77,7 @@ void Party::disband() { membersData.clear(); } -bool Party::leaveParty(std::shared_ptr player) { +bool Party::leaveParty(const std::shared_ptr &player) { if (!player) { return false; } @@ -163,7 +163,7 @@ bool Party::leaveParty(std::shared_ptr player) { return true; } -bool Party::passPartyLeadership(std::shared_ptr player) { +bool Party::passPartyLeadership(const std::shared_ptr &player) { auto leader = getLeader(); if (!leader || !player || leader == player || player->getParty().get() != this) { return false; @@ -179,7 +179,7 @@ bool Party::passPartyLeadership(std::shared_ptr player) { ss << player->getName() << " is now the leader of the party."; broadcastPartyMessage(MESSAGE_PARTY_MANAGEMENT, ss.str(), true); - auto oldLeader = leader; + const auto &oldLeader = leader; m_leader = player; memberList.insert(memberList.begin(), oldLeader); @@ -418,7 +418,7 @@ const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) { } } -bool Party::setSharedExperience(std::shared_ptr player, bool newSharedExpActive, bool silent /*= false*/) { +bool Party::setSharedExperience(const std::shared_ptr &player, bool newSharedExpActive, bool silent /*= false*/) { auto leader = getLeader(); if (!player || leader != player) { return false; @@ -446,7 +446,7 @@ bool Party::setSharedExperience(std::shared_ptr player, bool newSharedEx return true; } -void Party::shareExperience(uint64_t experience, std::shared_ptr target /* = nullptr*/) { +void Party::shareExperience(uint64_t experience, const std::shared_ptr &target /* = nullptr*/) { auto leader = getLeader(); if (!leader) { return; @@ -462,11 +462,11 @@ void Party::shareExperience(uint64_t experience, std::shared_ptr targe leader->onGainSharedExperience(shareExperience, target); } -bool Party::canUseSharedExperience(std::shared_ptr player) { - return getMemberSharedExperienceStatus(std::move(player)) == SHAREDEXP_OK; +bool Party::canUseSharedExperience(const std::shared_ptr &player) { + return getMemberSharedExperienceStatus(player) == SHAREDEXP_OK; } -SharedExpStatus_t Party::getMemberSharedExperienceStatus(std::shared_ptr player) { +SharedExpStatus_t Party::getMemberSharedExperienceStatus(const std::shared_ptr &player) { auto leader = getLeader(); if (!leader) { return SHAREDEXP_EMPTYPARTY; @@ -533,7 +533,7 @@ uint32_t Party::getMaxLevel() { return static_cast(std::floor(static_cast(getLowestLevel()) * shareRangeMultiplier())); } -bool Party::isPlayerActive(std::shared_ptr player) { +bool Party::isPlayerActive(const std::shared_ptr &player) { auto it = ticksMap.find(player->getID()); if (it == ticksMap.end()) { return false; @@ -561,14 +561,14 @@ SharedExpStatus_t Party::getSharedExperienceStatus() { return SHAREDEXP_OK; } -void Party::updatePlayerTicks(std::shared_ptr player, uint32_t points) { +void Party::updatePlayerTicks(const std::shared_ptr &player, uint32_t points) { if (points != 0 && !player->hasFlag(PlayerFlags_t::NotGainInFight)) { ticksMap[player->getID()] = OTSYS_TIME(); updateSharedExperience(); } } -void Party::clearPlayerPoints(std::shared_ptr player) { +void Party::clearPlayerPoints(const std::shared_ptr &player) { auto it = ticksMap.find(player->getID()); if (it != ticksMap.end()) { ticksMap.erase(it); @@ -582,13 +582,13 @@ bool Party::canOpenCorpse(uint32_t ownerId) const { return false; } - if (std::shared_ptr player = g_game().getPlayerByID(ownerId)) { + if (const auto player = g_game().getPlayerByID(ownerId)) { return leader->getID() == ownerId || player->getParty().get() == this; } return false; } -void Party::showPlayerStatus(std::shared_ptr player, std::shared_ptr member, bool showStatus) { +void Party::showPlayerStatus(const std::shared_ptr &player, const std::shared_ptr &member, bool showStatus) { player->sendPartyCreatureShowStatus(member, showStatus); member->sendPartyCreatureShowStatus(player, showStatus); if (showStatus) { @@ -614,7 +614,7 @@ void Party::showPlayerStatus(std::shared_ptr player, std::shared_ptr player) { +void Party::updatePlayerStatus(const std::shared_ptr &player) { auto leader = getLeader(); if (!leader) { return; @@ -637,7 +637,7 @@ void Party::updatePlayerStatus(std::shared_ptr player) { } } -void Party::updatePlayerStatus(std::shared_ptr player, const Position &oldPos, const Position &newPos) { +void Party::updatePlayerStatus(const std::shared_ptr &player, const Position &oldPos, const Position &newPos) { auto leader = getLeader(); if (!leader) { return; @@ -665,7 +665,7 @@ void Party::updatePlayerStatus(std::shared_ptr player, const Position &o } } -void Party::updatePlayerHealth(std::shared_ptr player, std::shared_ptr target, uint8_t healthPercent) { +void Party::updatePlayerHealth(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t healthPercent) { auto leader = getLeader(); if (!leader) { return; @@ -687,7 +687,7 @@ void Party::updatePlayerHealth(std::shared_ptr player, std::shared_ptr player, uint8_t manaPercent) { +void Party::updatePlayerMana(const std::shared_ptr &player, uint8_t manaPercent) { auto leader = getLeader(); if (!leader) { return; @@ -706,7 +706,7 @@ void Party::updatePlayerMana(std::shared_ptr player, uint8_t manaPercent } } -void Party::updatePlayerVocation(std::shared_ptr player) { +void Party::updatePlayerVocation(const std::shared_ptr &player) { auto leader = getLeader(); if (!leader) { return; @@ -738,7 +738,7 @@ void Party::updateTrackerAnalyzer() { leader->updatePartyTrackerAnalyzer(); } -void Party::addPlayerLoot(std::shared_ptr player, std::shared_ptr item) { +void Party::addPlayerLoot(const std::shared_ptr &player, const std::shared_ptr &item) { auto leader = getLeader(); if (!leader) { return; @@ -766,7 +766,7 @@ void Party::addPlayerLoot(std::shared_ptr player, std::shared_ptr updateTrackerAnalyzer(); } -void Party::addPlayerSupply(std::shared_ptr player, std::shared_ptr item) { +void Party::addPlayerSupply(const std::shared_ptr &player, const std::shared_ptr &item) { auto leader = getLeader(); if (!leader) { return; @@ -793,7 +793,7 @@ void Party::addPlayerSupply(std::shared_ptr player, std::shared_ptr player, uint64_t amount) { +void Party::addPlayerDamage(const std::shared_ptr &player, uint64_t amount) { auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared(player->getID(), player->getName()); @@ -804,7 +804,7 @@ void Party::addPlayerDamage(std::shared_ptr player, uint64_t amount) { updateTrackerAnalyzer(); } -void Party::addPlayerHealing(std::shared_ptr player, uint64_t amount) { +void Party::addPlayerHealing(const std::shared_ptr &player, uint64_t amount) { auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared(player->getID(), player->getName()); diff --git a/src/creatures/players/grouping/party.hpp b/src/creatures/players/grouping/party.hpp index 6aaecc56190..f0b9a0c1e10 100644 --- a/src/creatures/players/grouping/party.hpp +++ b/src/creatures/players/grouping/party.hpp @@ -26,7 +26,7 @@ class Party; class Party : public SharedObject { public: - static std::shared_ptr create(std::shared_ptr leader); + static std::shared_ptr create(const std::shared_ptr &leader); std::shared_ptr getParty() { return static_self_cast(); @@ -60,8 +60,8 @@ class Party : public SharedObject { bool invitePlayer(const std::shared_ptr &player); bool joinParty(const std::shared_ptr &player); void revokeInvitation(const std::shared_ptr &player); - bool passPartyLeadership(std::shared_ptr player); - bool leaveParty(std::shared_ptr player); + bool passPartyLeadership(const std::shared_ptr &player); + bool leaveParty(const std::shared_ptr &player); bool removeInvite(const std::shared_ptr &player, bool removeFromPlayer = true); @@ -73,33 +73,33 @@ class Party : public SharedObject { } bool canOpenCorpse(uint32_t ownerId) const; - void shareExperience(uint64_t experience, std::shared_ptr target = nullptr); - bool setSharedExperience(std::shared_ptr player, bool sharedExpActive, bool silent = false); + void shareExperience(uint64_t experience, const std::shared_ptr &target = nullptr); + bool setSharedExperience(const std::shared_ptr &player, bool sharedExpActive, bool silent = false); bool isSharedExperienceActive() const { return sharedExpActive; } bool isSharedExperienceEnabled() const { return sharedExpEnabled; } - bool canUseSharedExperience(std::shared_ptr player); - SharedExpStatus_t getMemberSharedExperienceStatus(std::shared_ptr player); + bool canUseSharedExperience(const std::shared_ptr &player); + SharedExpStatus_t getMemberSharedExperienceStatus(const std::shared_ptr &player); void updateSharedExperience(); - void updatePlayerTicks(std::shared_ptr player, uint32_t points); - void clearPlayerPoints(std::shared_ptr player); + void updatePlayerTicks(const std::shared_ptr &player, uint32_t points); + void clearPlayerPoints(const std::shared_ptr &player); - void showPlayerStatus(std::shared_ptr player, std::shared_ptr member, bool showStatus); - void updatePlayerStatus(std::shared_ptr player); - void updatePlayerStatus(std::shared_ptr player, const Position &oldPos, const Position &newPos); - void updatePlayerHealth(std::shared_ptr player, std::shared_ptr target, uint8_t healthPercent); - void updatePlayerMana(std::shared_ptr player, uint8_t manaPercent); - void updatePlayerVocation(std::shared_ptr player); + void showPlayerStatus(const std::shared_ptr &player, const std::shared_ptr &member, bool showStatus); + void updatePlayerStatus(const std::shared_ptr &player); + void updatePlayerStatus(const std::shared_ptr &player, const Position &oldPos, const Position &newPos); + void updatePlayerHealth(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t healthPercent); + void updatePlayerMana(const std::shared_ptr &player, uint8_t manaPercent); + void updatePlayerVocation(const std::shared_ptr &player); void updateTrackerAnalyzer(); - void addPlayerLoot(std::shared_ptr player, std::shared_ptr item); - void addPlayerSupply(std::shared_ptr player, std::shared_ptr item); - void addPlayerDamage(std::shared_ptr player, uint64_t amount); - void addPlayerHealing(std::shared_ptr player, uint64_t amount); + void addPlayerLoot(const std::shared_ptr &player, const std::shared_ptr &item); + void addPlayerSupply(const std::shared_ptr &player, const std::shared_ptr &item); + void addPlayerDamage(const std::shared_ptr &player, uint64_t amount); + void addPlayerHealing(const std::shared_ptr &player, uint64_t amount); void switchAnalyzerPriceType(); void resetAnalyzer(); void reloadPrices(); @@ -127,7 +127,7 @@ class Party : public SharedObject { private: const char* getSharedExpReturnMessage(SharedExpStatus_t value); - bool isPlayerActive(std::shared_ptr player); + bool isPlayerActive(const std::shared_ptr &player); SharedExpStatus_t getSharedExperienceStatus(); uint32_t getHighestLevel(); uint32_t getLowestLevel(); diff --git a/src/creatures/players/imbuements/imbuements.cpp b/src/creatures/players/imbuements/imbuements.cpp index 4bfb0de836b..261b348aa61 100644 --- a/src/creatures/players/imbuements/imbuements.cpp +++ b/src/creatures/players/imbuements/imbuements.cpp @@ -123,7 +123,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - uint16_t category = pugi::cast(categorybase.value()); + auto category = pugi::cast(categorybase.value()); auto category_p = getCategoryByID(category); if (category_p == nullptr) { g_logger().warn("Category imbuement {} not exist", category); @@ -151,7 +151,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { g_logger().warn("Missing item ID for imbuement name '{}'", imbuement.name); continue; } - uint16_t sourceId = pugi::cast(attr.value()); + auto sourceId = pugi::cast(attr.value()); uint16_t count = 1; if ((attr = childNode.attribute("count"))) { @@ -230,7 +230,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { g_logger().warn("Missing skill bonus for imbuement name {}", imbuement.name); continue; } - int32_t bonus = pugi::cast(attr.value()); + auto bonus = pugi::cast(attr.value()); if (usenormalskill == 1) { imbuement.skills[skillId] = bonus; @@ -336,7 +336,7 @@ CategoryImbuement* Imbuements::getCategoryByID(uint16_t id) { return categoryImbuements != categoriesImbuement.end() ? &*categoryImbuements : nullptr; } -std::vector Imbuements::getImbuements(std::shared_ptr player, std::shared_ptr item) { +std::vector Imbuements::getImbuements(const std::shared_ptr &player, const std::shared_ptr &item) { std::vector imbuements; for (auto &[key, value] : imbuementMap) { diff --git a/src/creatures/players/imbuements/imbuements.hpp b/src/creatures/players/imbuements/imbuements.hpp index 265e813aa1c..1aa93eff67c 100644 --- a/src/creatures/players/imbuements/imbuements.hpp +++ b/src/creatures/players/imbuements/imbuements.hpp @@ -60,7 +60,7 @@ class Imbuements { BaseImbuement* getBaseByID(uint16_t id); CategoryImbuement* getCategoryByID(uint16_t id); - std::vector getImbuements(std::shared_ptr player, std::shared_ptr item); + std::vector getImbuements(const std::shared_ptr &player, const std::shared_ptr &item); protected: friend class Imbuement; @@ -94,7 +94,7 @@ class Imbuement { return storage; } - bool isPremium() { + bool isPremium() const { return premium; } std::string getName() const { @@ -116,7 +116,7 @@ class Imbuement { return items; } - uint16_t getIconID() { + uint16_t getIconID() const { return icon + (baseid - 1); } @@ -139,7 +139,7 @@ class Imbuement { bool premium = false; uint32_t storage = 0; uint16_t id, baseid, category = 0; - std::string name, description, subgroup = ""; + std::string name, description, subgroup; std::vector> items; }; diff --git a/src/creatures/players/management/ban.cpp b/src/creatures/players/management/ban.cpp index d81045c5344..70b9a80dd2d 100644 --- a/src/creatures/players/management/ban.cpp +++ b/src/creatures/players/management/ban.cpp @@ -58,7 +58,7 @@ bool IOBan::isAccountBanned(uint32_t accountId, BanInfo &banInfo) { return false; } - int64_t expiresAt = result->getNumber("expires_at"); + auto expiresAt = result->getNumber("expires_at"); if (expiresAt != 0 && time(nullptr) > expiresAt) { // Move the ban to history if it has expired query.str(std::string()); @@ -92,7 +92,7 @@ bool IOBan::isIpBanned(uint32_t clientIP, BanInfo &banInfo) { return false; } - int64_t expiresAt = result->getNumber("expires_at"); + auto expiresAt = result->getNumber("expires_at"); if (expiresAt != 0 && time(nullptr) > expiresAt) { query.str(std::string()); query << "DELETE FROM `ip_bans` WHERE `ip` = " << clientIP; diff --git a/src/creatures/players/management/waitlist.cpp b/src/creatures/players/management/waitlist.cpp index 345c20f2650..59c6fc84ab3 100644 --- a/src/creatures/players/management/waitlist.cpp +++ b/src/creatures/players/management/waitlist.cpp @@ -61,7 +61,7 @@ std::size_t WaitingList::getTime(std::size_t slot) { } } -bool WaitingList::clientLogin(std::shared_ptr player) { +bool WaitingList::clientLogin(const std::shared_ptr &player) { if (player->hasFlag(PlayerFlags_t::CanAlwaysLogin) || player->getAccountType() >= ACCOUNT_TYPE_GAMEMASTER) { return true; } @@ -87,7 +87,7 @@ bool WaitingList::clientLogin(std::shared_ptr player) { return false; } -void WaitingList::addPlayerToList(std::shared_ptr player) { +void WaitingList::addPlayerToList(const std::shared_ptr &player) { auto it = info->playerReferences.find(player->getGUID()); if (it != info->playerReferences.end()) { std::size_t slot; @@ -113,7 +113,7 @@ void WaitingList::addPlayerToList(std::shared_ptr player) { } } -std::size_t WaitingList::getClientSlot(std::shared_ptr player) { +std::size_t WaitingList::getClientSlot(const std::shared_ptr &player) { auto it = info->playerReferences.find(player->getGUID()); if (it == info->playerReferences.end()) { return 0; diff --git a/src/creatures/players/management/waitlist.hpp b/src/creatures/players/management/waitlist.hpp index 24752f2647d..dfe34122196 100644 --- a/src/creatures/players/management/waitlist.hpp +++ b/src/creatures/players/management/waitlist.hpp @@ -34,13 +34,13 @@ class WaitingList { public: WaitingList(); static WaitingList &getInstance(); - bool clientLogin(std::shared_ptr player); - std::size_t getClientSlot(std::shared_ptr player); + bool clientLogin(const std::shared_ptr &player); + std::size_t getClientSlot(const std::shared_ptr &player); static std::size_t getTime(std::size_t slot); private: void cleanupList(WaitList &list); std::size_t getTimeout(std::size_t slot); - void addPlayerToList(std::shared_ptr player); + void addPlayerToList(const std::shared_ptr &player); std::unique_ptr info; }; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 9ba9f3b74d6..33d9ce6f021 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -98,8 +98,8 @@ bool Player::isPushable() { return Creature::isPushable(); } -std::shared_ptr Player::createPlayerTask(uint32_t delay, std::function f, std::string context) { - return std::make_shared(std::move(f), std::move(context), delay); +std::shared_ptr Player::createPlayerTask(uint32_t delay, std::function f, const std::string &context) { + return std::make_shared(std::move(f), context, delay); } uint32_t Player::playerFirstID = 0x10000000; @@ -250,7 +250,7 @@ void Player::removeConditionSuppressions() { } std::shared_ptr Player::getWeapon(Slots_t slot, bool ignoreAmmo) const { - std::shared_ptr item = inventory[slot]; + auto item = inventory[slot]; if (!item) { return nullptr; } @@ -276,7 +276,7 @@ bool Player::hasQuiverEquipped() const { } bool Player::hasWeaponDistanceEquipped() const { - std::shared_ptr item = inventory[CONST_SLOT_LEFT]; + const auto item = inventory[CONST_SLOT_LEFT]; return item && item->getWeaponType() == WEAPON_DISTANCE; } @@ -298,7 +298,7 @@ std::shared_ptr Player::getQuiverAmmoOfType(const ItemType &it) const { } std::shared_ptr Player::getWeapon(bool ignoreAmmo /* = false*/) const { - std::shared_ptr item = getWeapon(CONST_SLOT_LEFT, ignoreAmmo); + auto item = getWeapon(CONST_SLOT_LEFT, ignoreAmmo); if (item) { return item; } @@ -311,14 +311,14 @@ std::shared_ptr Player::getWeapon(bool ignoreAmmo /* = false*/) const { } WeaponType_t Player::getWeaponType() const { - std::shared_ptr item = getWeapon(); + const auto item = getWeapon(); if (!item) { return WEAPON_NONE; } return item->getWeaponType(); } -int32_t Player::getWeaponSkill(std::shared_ptr item) const { +int32_t Player::getWeaponSkill(const std::shared_ptr &item) const { if (!item) { return getSkillLevel(SKILL_FIST); } @@ -374,7 +374,7 @@ void Player::getShieldAndWeapon(std::shared_ptr &shield, std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (!item) { continue; } @@ -499,7 +499,7 @@ std::unordered_set Player::getClientIcons() { return icons; } -void Player::addMonsterToCyclopediaTrackerList(const std::shared_ptr mtype, bool isBoss, bool reloadClient /* = false */) { +void Player::addMonsterToCyclopediaTrackerList(const std::shared_ptr &mtype, bool isBoss, bool reloadClient /* = false */) { if (!client) { return; } @@ -519,7 +519,7 @@ void Player::addMonsterToCyclopediaTrackerList(const std::shared_ptr mtype, bool isBoss, bool reloadClient /* = false */) { +void Player::removeMonsterFromCyclopediaTrackerList(const std::shared_ptr &mtype, bool isBoss, bool reloadClient /* = false */) { if (!client) { return; } @@ -551,7 +551,7 @@ void Player::updateInventoryWeight() { inventoryWeight = 0; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (item) { inventoryWeight += item->getWeight(); } @@ -568,7 +568,7 @@ void Player::updateInventoryImbuement() { bool nonAggressiveFightOnly = g_configManager().getBoolean(TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY, __FUNCTION__); // Iterate through all items in the player's inventory - for (auto [key, item] : getAllSlotItems()) { + for (const auto &[key, item] : getAllSlotItems()) { // Iterate through all imbuement slots on the item for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { @@ -620,7 +620,7 @@ void Player::updateInventoryImbuement() { phmap::flat_hash_map> Player::getAllSlotItems() const { phmap::flat_hash_map> itemMap; for (uint8_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -770,7 +770,7 @@ int32_t Player::getDefaultStats(stats_t stat) const { } } -void Player::addContainer(uint8_t cid, std::shared_ptr container) { +void Player::addContainer(uint8_t cid, const std::shared_ptr &container) { if (cid > 0xF) { return; } @@ -846,7 +846,7 @@ std::shared_ptr Player::getContainerByID(uint8_t cid) { return it->second.container; } -int8_t Player::getContainerID(std::shared_ptr container) const { +int8_t Player::getContainerID(const std::shared_ptr &container) const { for (const auto &it : openContainers) { if (it.second.container == container) { return it.first; @@ -963,12 +963,12 @@ bool Player::canSeeCreature(std::shared_ptr creature) const { return true; } -bool Player::canWalkthrough(std::shared_ptr creature) { +bool Player::canWalkthrough(const std::shared_ptr &creature) { if (group->access || creature->isInGhostMode()) { return true; } - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); std::shared_ptr monster = creature->getMonster(); std::shared_ptr npc = creature->getNpc(); if (monster) { @@ -1011,7 +1011,7 @@ bool Player::canWalkthrough(std::shared_ptr creature) { return false; } -bool Player::canWalkthroughEx(std::shared_ptr creature) { +bool Player::canWalkthroughEx(const std::shared_ptr &creature) { if (group->access) { return true; } @@ -1024,7 +1024,7 @@ bool Player::canWalkthroughEx(std::shared_ptr creature) { return true; } - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); std::shared_ptr npc = creature->getNpc(); if (player) { std::shared_ptr playerTile = player->getTile(); @@ -1044,7 +1044,7 @@ void Player::onReceiveMail() { } } -std::shared_ptr Player::refreshManagedContainer(ObjectCategory_t category, std::shared_ptr container, bool isLootContainer, bool loading /* = false*/) { +std::shared_ptr Player::refreshManagedContainer(ObjectCategory_t category, const std::shared_ptr &container, bool isLootContainer, bool loading /* = false*/) { std::shared_ptr previousContainer = nullptr; auto toSetAttribute = isLootContainer ? ItemAttribute_t::QUICKLOOTCONTAINER : ItemAttribute_t::OBTAINCONTAINER; if (auto it = m_managedContainers.find(category); it != m_managedContainers.end() && !loading) { @@ -1119,7 +1119,7 @@ std::shared_ptr Player::getManagedContainer(ObjectCategory_t category return container; } -void Player::checkLootContainers(std::shared_ptr container) { +void Player::checkLootContainers(const std::shared_ptr &container) { if (!container) { return; } @@ -1162,7 +1162,7 @@ void Player::checkLootContainers(std::shared_ptr container) { } } -void Player::setMainBackpackUnassigned(std::shared_ptr container) { +void Player::setMainBackpackUnassigned(const std::shared_ptr &container) { if (!container) { return; } @@ -1183,7 +1183,7 @@ void Player::setMainBackpackUnassigned(std::shared_ptr container) { } } -void Player::sendLootStats(std::shared_ptr item, uint8_t count) { +void Player::sendLootStats(const std::shared_ptr &item, uint8_t count) { uint64_t value = 0; if (item->getID() == ITEM_GOLD_COIN || item->getID() == ITEM_PLATINUM_COIN || item->getID() == ITEM_CRYSTAL_COIN) { if (item->getID() == ITEM_PLATINUM_COIN) { @@ -1322,7 +1322,7 @@ void Player::getRewardList(std::vector &rewards) const { } } -std::vector> Player::getRewardsFromContainer(std::shared_ptr container) const { +std::vector> Player::getRewardsFromContainer(const std::shared_ptr &container) const { std::vector> rewardItemsVector; if (container) { for (const auto &item : container->getItems(false)) { @@ -1349,7 +1349,7 @@ void Player::sendStats() { } } -void Player::updateSupplyTracker(std::shared_ptr item) { +void Player::updateSupplyTracker(const std::shared_ptr &item) { const auto &iType = Item::items.getItemType(item->getID()); auto value = iType.buyPrice; g_metrics().addCounter("player_supply", value, { { "player", getName() } }); @@ -1405,10 +1405,10 @@ std::shared_ptr Player::getWriteItem(uint32_t &retWindowTextId, uint16_t & } void Player::setImbuingItem(std::shared_ptr item) { - imbuingItem = item; + imbuingItem = std::move(item); } -void Player::setWriteItem(std::shared_ptr item, uint16_t maxWriteLength /*= 0*/) { +void Player::setWriteItem(const std::shared_ptr &item, uint16_t maxWriteLength /*= 0*/) { windowTextId++; if (item) { @@ -1428,11 +1428,11 @@ std::shared_ptr Player::getEditHouse(uint32_t &retWindowTextId, uint32_t void Player::setEditHouse(std::shared_ptr house, uint32_t listId /*= 0*/) { windowTextId++; - editHouse = house; + editHouse = std::move(house); editListId = listId; } -void Player::sendHouseWindow(std::shared_ptr house, uint32_t listId) const { +void Player::sendHouseWindow(const std::shared_ptr &house, uint32_t listId) const { if (!client) { return; } @@ -1443,7 +1443,7 @@ void Player::sendHouseWindow(std::shared_ptr house, uint32_t listId) cons } } -void Player::onApplyImbuement(Imbuement* imbuement, std::shared_ptr item, uint8_t slot, bool protectionCharm) { +void Player::onApplyImbuement(Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm) { if (!imbuement || !item) { return; } @@ -1519,7 +1519,7 @@ void Player::onApplyImbuement(Imbuement* imbuement, std::shared_ptr item, openImbuementWindow(item); } -void Player::onClearImbuement(std::shared_ptr item, uint8_t slot) { +void Player::onClearImbuement(const std::shared_ptr &item, uint8_t slot) { if (!item) { return; } @@ -1554,7 +1554,7 @@ void Player::onClearImbuement(std::shared_ptr item, uint8_t slot) { this->openImbuementWindow(item); } -void Player::openImbuementWindow(std::shared_ptr item) { +void Player::openImbuementWindow(const std::shared_ptr &item) { if (!client || !item) { return; } @@ -1588,7 +1588,7 @@ void Player::sendMarketEnter(uint32_t depotId) { } // container -void Player::sendAddContainerItem(std::shared_ptr container, std::shared_ptr item) { +void Player::sendAddContainerItem(const std::shared_ptr &container, std::shared_ptr item) { if (!client) { return; } @@ -1620,7 +1620,7 @@ void Player::sendAddContainerItem(std::shared_ptr container, std::sha } } -void Player::sendUpdateContainerItem(std::shared_ptr container, uint16_t slot, std::shared_ptr newItem) { +void Player::sendUpdateContainerItem(const std::shared_ptr &container, uint16_t slot, const std::shared_ptr &newItem) { if (!client) { return; } @@ -1644,7 +1644,7 @@ void Player::sendUpdateContainerItem(std::shared_ptr container, uint1 } } -void Player::sendRemoveContainerItem(std::shared_ptr container, uint16_t slot) { +void Player::sendRemoveContainerItem(const std::shared_ptr &container, uint16_t slot) { if (!client) { return; } @@ -1883,7 +1883,7 @@ void Player::onRemoveCreature(std::shared_ptr creature, bool isLogout) } } -bool Player::openShopWindow(std::shared_ptr npc, const std::vector &shopItems) { +bool Player::openShopWindow(const std::shared_ptr &npc, const std::vector &shopItems) { Benchmark brenchmark; if (!npc) { g_logger().error("[Player::openShopWindow] - Npc is wrong or nullptr"); @@ -1998,7 +1998,7 @@ void Player::onCreatureMove(const std::shared_ptr &creature, const std void Player::onEquipInventory() { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (item) { item->startDecaying(); g_moveEvents().onPlayerEquip(getPlayer(), item, static_cast(slot), false); @@ -2008,7 +2008,7 @@ void Player::onEquipInventory() { void Player::onDeEquipInventory() { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (item) { g_moveEvents().onPlayerDeEquip(getPlayer(), item, static_cast(slot)); } @@ -2016,11 +2016,11 @@ void Player::onDeEquipInventory() { } // container -void Player::onAddContainerItem(std::shared_ptr item) { +void Player::onAddContainerItem(const std::shared_ptr &item) { checkTradeState(item); } -void Player::onUpdateContainerItem(std::shared_ptr container, std::shared_ptr oldItem, std::shared_ptr newItem) { +void Player::onUpdateContainerItem(const std::shared_ptr &container, const std::shared_ptr &oldItem, const std::shared_ptr &newItem) { if (oldItem != newItem) { onRemoveContainerItem(container, oldItem); } @@ -2030,7 +2030,7 @@ void Player::onUpdateContainerItem(std::shared_ptr container, std::sh } } -void Player::onRemoveContainerItem(std::shared_ptr container, std::shared_ptr item) { +void Player::onRemoveContainerItem(const std::shared_ptr &container, const std::shared_ptr &item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); @@ -2044,7 +2044,7 @@ void Player::onRemoveContainerItem(std::shared_ptr container, std::sh checkLootContainers(item->getContainer()); } -void Player::onCloseContainer(std::shared_ptr container) { +void Player::onCloseContainer(const std::shared_ptr &container) { if (!client) { return; } @@ -2056,7 +2056,7 @@ void Player::onCloseContainer(std::shared_ptr container) { } } -void Player::onSendContainer(std::shared_ptr container) { +void Player::onSendContainer(const std::shared_ptr &container) { if (!client || !container) { return; } @@ -2071,7 +2071,7 @@ void Player::onSendContainer(std::shared_ptr container) { } // inventory -void Player::onUpdateInventoryItem(std::shared_ptr oldItem, std::shared_ptr newItem) { +void Player::onUpdateInventoryItem(const std::shared_ptr &oldItem, const std::shared_ptr &newItem) { if (oldItem != newItem) { onRemoveInventoryItem(oldItem); } @@ -2081,7 +2081,7 @@ void Player::onUpdateInventoryItem(std::shared_ptr oldItem, std::shared_pt } } -void Player::onRemoveInventoryItem(std::shared_ptr item) { +void Player::onRemoveInventoryItem(const std::shared_ptr &item) { if (tradeState != TRADE_TRANSFER) { checkTradeState(item); @@ -2096,7 +2096,7 @@ void Player::onRemoveInventoryItem(std::shared_ptr item) { checkLootContainers(item->getContainer()); } -void Player::checkTradeState(std::shared_ptr item) { +void Player::checkTradeState(const std::shared_ptr &item) { if (!tradeItem || tradeState == TRADE_TRANSFER) { return; } @@ -2122,10 +2122,10 @@ void Player::setNextWalkActionTask(std::shared_ptr task) { walkTaskEvent = 0; } - walkTask = task; + walkTask = std::move(task); } -void Player::setNextWalkTask(std::shared_ptr task) { +void Player::setNextWalkTask(const std::shared_ptr &task) { if (nextStepEvent != 0) { g_dispatcher().stopEvent(nextStepEvent); nextStepEvent = 0; @@ -2137,7 +2137,7 @@ void Player::setNextWalkTask(std::shared_ptr task) { } } -void Player::setNextActionTask(std::shared_ptr task, bool resetIdleTime /*= true */) { +void Player::setNextActionTask(const std::shared_ptr &task, bool resetIdleTime /*= true */) { if (actionTaskEvent != 0) { g_dispatcher().stopEvent(actionTaskEvent); actionTaskEvent = 0; @@ -2155,7 +2155,7 @@ void Player::setNextActionTask(std::shared_ptr task, bool resetIdleTime /* } } -void Player::setNextActionPushTask(std::shared_ptr task) { +void Player::setNextActionPushTask(const std::shared_ptr &task) { if (actionTaskEventPush != 0) { g_dispatcher().stopEvent(actionTaskEventPush); actionTaskEventPush = 0; @@ -2166,7 +2166,7 @@ void Player::setNextActionPushTask(std::shared_ptr task) { } } -void Player::setNextPotionActionTask(std::shared_ptr task) { +void Player::setNextPotionActionTask(const std::shared_ptr &task) { if (actionPotionTaskEvent != 0) { g_dispatcher().stopEvent(actionPotionTaskEvent); actionPotionTaskEvent = 0; @@ -2358,7 +2358,7 @@ void Player::addManaSpent(uint64_t amount) { } } -void Player::addExperience(std::shared_ptr target, uint64_t exp, bool sendText /* = false*/) { +void Player::addExperience(const std::shared_ptr &target, uint64_t exp, bool sendText /* = false*/) { uint64_t currLevelExp = Player::getExpForLevel(level); uint64_t nextLevelExp = Player::getExpForLevel(level + 1); uint64_t rawExp = exp; @@ -2621,7 +2621,7 @@ void Player::onAttackedCreatureBlockHit(BlockType_t blockType) { } bool Player::hasShield() const { - std::shared_ptr item = inventory[CONST_SLOT_LEFT]; + auto item = inventory[CONST_SLOT_LEFT]; if (item && item->getWeaponType() == WEAPON_SHIELD) { return true; } @@ -2649,7 +2649,7 @@ BlockType_t Player::blockHit(std::shared_ptr attacker, CombatType_t co continue; } - std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (!item) { continue; } @@ -2779,7 +2779,7 @@ void Player::death(std::shared_ptr lastHitCreature) { } // Level loss - uint64_t expLoss = static_cast(experience * deathLossPercent); + auto expLoss = static_cast(experience * deathLossPercent); g_events().eventPlayerOnLoseExperience(static_self_cast(), expLoss); g_callbacks().executeCallback(EventCallback_t::playerOnLoseExperience, &EventCallback::playerOnLoseExperience, getPlayer(), expLoss); @@ -2796,7 +2796,7 @@ void Player::death(std::shared_ptr lastHitCreature) { sumSkillTries += skills[i].tries; - uint32_t lostSkillTries = static_cast(sumSkillTries * deathLossPercent); + auto lostSkillTries = static_cast(sumSkillTries * deathLossPercent); while (lostSkillTries > skills[i].tries) { lostSkillTries -= skills[i].tries; @@ -3076,7 +3076,7 @@ void Player::removePlayer(bool displayEffect, bool forced /*= true*/) { } // close container and its child containers -void Player::autoCloseContainers(std::shared_ptr container) { +void Player::autoCloseContainers(const std::shared_ptr &container) { std::vector closeList; for (const auto &it : openContainers) { std::shared_ptr tmpContainer = it.second.container; @@ -3098,7 +3098,7 @@ void Player::autoCloseContainers(std::shared_ptr container) { } } -bool Player::hasCapacity(std::shared_ptr item, uint32_t count) const { +bool Player::hasCapacity(const std::shared_ptr &item, uint32_t count) const { if (hasFlag(PlayerFlags_t::CannotPickupItem)) { return false; } @@ -3115,7 +3115,7 @@ bool Player::hasCapacity(std::shared_ptr item, uint32_t count) const { } ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { g_logger().error("[Player::queryAdd] - Item is nullptr"); return RETURNVALUE_NOTPOSSIBLE; @@ -3412,7 +3412,7 @@ ReturnValue Player::queryRemove(const std::shared_ptr &thing, uint32_t co return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -3432,7 +3432,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh if (index == 0 /*drop to capacity window*/ || index == INDEX_WHEREEVER) { *destItem = nullptr; - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return getPlayer(); } @@ -3541,7 +3541,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh *destItem = destThing->getItem(); } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); bool movingAmmoToQuiver = item && *destItem && (*destItem)->isQuiver() && item->isAmmo(); // force shield any slot right to player cylinder if (index == CONST_SLOT_RIGHT && !movingAmmoToQuiver) { @@ -3567,7 +3567,7 @@ void Player::addThing(int32_t index, std::shared_ptr thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3585,7 +3585,7 @@ void Player::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3610,7 +3610,7 @@ void Player::replaceThing(uint32_t index, std::shared_ptr thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3627,7 +3627,7 @@ void Player::replaceThing(uint32_t index, std::shared_ptr thing) { } void Player::removeThing(std::shared_ptr thing, uint32_t count) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3689,7 +3689,7 @@ size_t Player::getLastIndex() const { uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const { uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -3709,7 +3709,7 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con return count; } -void Player::stashContainer(StashContainerList itemDict) { +void Player::stashContainer(const StashContainerList &itemDict) { StashItemList stashItemDict; // ItemID - Count for (const auto &it_dict : itemDict) { stashItemDict[(it_dict.first)->getID()] = it_dict.second; @@ -3769,7 +3769,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -3784,7 +3784,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, count += itemCount; if (count >= amount) { - g_game().internalRemoveItems(std::move(itemList), amount, Item::items[itemId].stackable); + g_game().internalRemoveItems(itemList, amount, Item::items[itemId].stackable); return true; } } else if (std::shared_ptr container = item->getContainer()) { @@ -3803,7 +3803,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, // If the amount of items in the backpack is equal to or greater than the amount // It will remove items and stop the iteration if (count >= amount) { - g_game().internalRemoveItems(std::move(itemList), amount, stackable); + g_game().internalRemoveItems(itemList, amount, stackable); return true; } } @@ -3875,7 +3875,7 @@ bool Player::removeItemCountById(uint16_t itemId, uint32_t itemAmount, bool remo ItemsTierCountList Player::getInventoryItemsId(bool ignoreStoreInbox /* false */) const { ItemsTierCountList itemMap; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -3900,7 +3900,7 @@ ItemsTierCountList Player::getInventoryItemsId(bool ignoreStoreInbox /* false */ std::vector> Player::getInventoryItemsFromId(uint16_t itemId, bool ignore /*= true*/) const { std::vector> itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -3923,7 +3923,7 @@ std::vector> Player::getInventoryItemsFromId(uint16_t item } std::array Player::getFinalDamageReduction() const { - std::array combatReductionArray; + std::array combatReductionArray {}; combatReductionArray.fill(0); calculateDamageReductionFromEquipedItems(combatReductionArray); for (int combatTypeIndex = 0; combatTypeIndex < COMBAT_COUNT; combatTypeIndex++) { @@ -3938,14 +3938,14 @@ std::array Player::getFinalDamageReduction() const { void Player::calculateDamageReductionFromEquipedItems(std::array &combatReductionArray) const { for (uint8_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (item) { calculateDamageReductionFromItem(combatReductionArray, item); } } } -void Player::calculateDamageReductionFromItem(std::array &combatReductionArray, std::shared_ptr item) const { +void Player::calculateDamageReductionFromItem(std::array &combatReductionArray, const std::shared_ptr &item) const { for (uint16_t combatTypeIndex = 0; combatTypeIndex < COMBAT_COUNT; combatTypeIndex++) { updateDamageReductionFromItemImbuement(combatReductionArray, item, combatTypeIndex); updateDamageReductionFromItemAbility(combatReductionArray, item, combatTypeIndex); @@ -3953,7 +3953,7 @@ void Player::calculateDamageReductionFromItem(std::array } void Player::updateDamageReductionFromItemImbuement( - std::array &combatReductionArray, std::shared_ptr item, uint16_t combatTypeIndex + std::array &combatReductionArray, const std::shared_ptr &item, uint16_t combatTypeIndex ) const { for (uint8_t imbueSlotId = 0; imbueSlotId < item->getImbuementSlot(); imbueSlotId++) { ImbuementInfo imbuementInfo; @@ -3967,7 +3967,7 @@ void Player::updateDamageReductionFromItemImbuement( } void Player::updateDamageReductionFromItemAbility( - std::array &combatReductionArray, std::shared_ptr item, uint16_t combatTypeIndex + std::array &combatReductionArray, const std::shared_ptr &item, uint16_t combatTypeIndex ) const { if (!item) { return; @@ -3991,7 +3991,7 @@ ItemsTierCountList Player::getStoreInboxItemsId() const { const auto &container = getStoreInbox(); if (container) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; (itemMap[item->getID()])[item->getTier()] += Item::countByType(item, -1); } } @@ -4005,7 +4005,7 @@ ItemsTierCountList Player::getDepotChestItemsId() const { for (const auto &[index, depot] : depotChests) { const std::shared_ptr &container = depot->getContainer(); for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; (itemMap[item->getID()])[item->getTier()] += Item::countByType(item, -1); } } @@ -4016,8 +4016,8 @@ ItemsTierCountList Player::getDepotChestItemsId() const { ItemsTierCountList Player::getDepotInboxItemsId() const { ItemsTierCountList itemMap; - const std::shared_ptr &inbox = getInbox(); - const std::shared_ptr &container = inbox->getContainer(); + const auto &inbox = getInbox(); + const auto &container = inbox->getContainer(); if (container) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { const auto &item = *it; @@ -4031,7 +4031,7 @@ ItemsTierCountList Player::getDepotInboxItemsId() const { std::vector> Player::getAllInventoryItems(bool ignoreEquiped /*= false*/, bool ignoreItemWithTier /* false*/) const { std::vector> itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -4074,7 +4074,7 @@ std::vector> Player::getEquippedAugmentItems() const { const auto equippedItems = getEquippedItems(); for (const auto &item : equippedItems) { - if (item->getAugments().size() < 1) { + if (item->getAugments().empty()) { continue; } equippedAugmentItems.push_back(item); @@ -4098,7 +4098,7 @@ std::vector> Player::getEquippedItems() const { std::vector> valid_items; for (const auto &slot : valid_slots) { - std::shared_ptr item = inventory[slot]; + const auto item = inventory[slot]; if (!item) { continue; } @@ -4135,7 +4135,7 @@ void Player::getAllItemTypeCountAndSubtype(std::map &countMa } } -std::shared_ptr Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) { +std::shared_ptr Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) const { for (auto item : getAllInventoryItems(true)) { if (item->hasImbuements()) { continue; @@ -4178,7 +4178,7 @@ void Player::postAddNotification(std::shared_ptr thing, std::shared_ptr item = thing->getItem()) { + if (const auto item = thing->getItem()) { if (std::shared_ptr container = item->getContainer()) { onSendContainer(container); } @@ -4232,7 +4232,7 @@ void Player::postRemoveNotification(std::shared_ptr thing, std::shared_pt sendStats(); } - if (std::shared_ptr item = thing->getItem()) { + if (const auto item = thing->getItem()) { if (std::shared_ptr container = item->getContainer()) { checkLootContainers(container); @@ -4275,7 +4275,7 @@ void Player::postRemoveNotification(std::shared_ptr thing, std::shared_pt } // i will keep this function so it can be reviewed -bool Player::updateSaleShopList(std::shared_ptr item) { +bool Player::updateSaleShopList(const std::shared_ptr &item) { uint16_t itemId = item->getID(); if (!itemId || !item) { return true; @@ -4307,7 +4307,7 @@ void Player::internalAddThing(uint32_t index, std::shared_ptr thing) { return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return; } @@ -4504,7 +4504,7 @@ void Player::updateItemsLight(bool internal /*=false*/) { LightInfo maxLight; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (item) { LightInfo curLight = item->getLightInfo(); @@ -4617,7 +4617,7 @@ void Player::onCombatRemoveCondition(std::shared_ptr condition) { if (condition->getId() > 0) { // Means the condition is from an item, id == slot if (g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { - std::shared_ptr item = getInventoryItem(static_cast(condition->getId())); + const auto item = getInventoryItem(static_cast(condition->getId())); if (item) { // 25% chance to destroy the item if (25 >= uniform_random(1, 100)) { @@ -4829,7 +4829,7 @@ bool Player::onKilledMonster(const std::shared_ptr &monster) { return false; } -void Player::gainExperience(uint64_t gainExp, std::shared_ptr target) { +void Player::gainExperience(uint64_t gainExp, const std::shared_ptr &target) { if (hasFlag(PlayerFlags_t::NotGainExperience) || gainExp == 0 || staminaMinutes == 0) { return; } @@ -4852,7 +4852,7 @@ void Player::onGainExperience(uint64_t gainExp, std::shared_ptr target gainExperience(gainExp, target); } -void Player::onGainSharedExperience(uint64_t gainExp, std::shared_ptr target) { +void Player::onGainSharedExperience(uint64_t gainExp, const std::shared_ptr &target) { gainExperience(gainExp, target); } @@ -4875,7 +4875,7 @@ bool Player::isAttackable() const { return !hasFlag(PlayerFlags_t::CannotBeAttacked); } -bool Player::lastHitIsPlayer(std::shared_ptr lastHitCreature) { +bool Player::lastHitIsPlayer(const std::shared_ptr &lastHitCreature) { if (!lastHitCreature) { return false; } @@ -5125,7 +5125,7 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { return SKULL_NONE; } - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player && player->getSkull() == SKULL_NONE) { if (player.get() == this) { for (const auto &kill : unjustifiedKills) { @@ -5150,7 +5150,7 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { return Creature::getSkullClient(creature); } -bool Player::hasKilled(std::shared_ptr player) const { +bool Player::hasKilled(const std::shared_ptr &player) const { for (const auto &kill : unjustifiedKills) { if (kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, __FUNCTION__) * 24 * 60 * 60 && kill.unavenged) { return true; @@ -5160,7 +5160,7 @@ bool Player::hasKilled(std::shared_ptr player) const { return false; } -bool Player::hasAttacked(std::shared_ptr attacked) const { +bool Player::hasAttacked(const std::shared_ptr &attacked) const { if (hasFlag(PlayerFlags_t::NotGainInFight) || !attacked) { return false; } @@ -5168,7 +5168,7 @@ bool Player::hasAttacked(std::shared_ptr attacked) const { return attackedSet.contains(attacked->guid); } -void Player::addAttacked(std::shared_ptr attacked) { +void Player::addAttacked(const std::shared_ptr &attacked) { if (hasFlag(PlayerFlags_t::NotGainInFight) || !attacked || attacked == getPlayer()) { return; } @@ -5176,7 +5176,7 @@ void Player::addAttacked(std::shared_ptr attacked) { attackedSet.emplace(attacked->guid); } -void Player::removeAttacked(std::shared_ptr attacked) { +void Player::removeAttacked(const std::shared_ptr &attacked) { if (!attacked || attacked == getPlayer()) { return; } @@ -5188,7 +5188,7 @@ void Player::clearAttacked() { attackedSet.clear(); } -void Player::addUnjustifiedDead(std::shared_ptr attacked) { +void Player::addUnjustifiedDead(const std::shared_ptr &attacked) { if (hasFlag(PlayerFlags_t::NotGainInFight) || attacked == getPlayer() || g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { return; } @@ -5310,7 +5310,7 @@ bool Player::hasLearnedInstantSpell(const std::string &spellName) const { return false; } -bool Player::isInWar(std::shared_ptr player) const { +bool Player::isInWar(const std::shared_ptr &player) const { if (!player || !guild) { return false; } @@ -5610,7 +5610,7 @@ void Player::setTransferableTibiaCoins(int32_t v) { coinTransferableBalance = v; } -PartyShields_t Player::getPartyShield(std::shared_ptr player) { +PartyShields_t Player::getPartyShield(const std::shared_ptr &player) { if (!player) { return SHIELD_NONE; } @@ -5664,33 +5664,33 @@ PartyShields_t Player::getPartyShield(std::shared_ptr player) { return SHIELD_NONE; } -bool Player::isInviting(std::shared_ptr player) const { +bool Player::isInviting(const std::shared_ptr &player) const { if (!player || !m_party || m_party->getLeader().get() != this) { return false; } return m_party->isPlayerInvited(player); } -bool Player::isPartner(std::shared_ptr player) const { +bool Player::isPartner(const std::shared_ptr &player) const { if (!player || !m_party || player.get() == this) { return false; } return m_party == player->m_party; } -bool Player::isGuildMate(std::shared_ptr player) const { +bool Player::isGuildMate(const std::shared_ptr &player) const { if (!player || !guild) { return false; } return guild == player->guild; } -void Player::sendPlayerPartyIcons(std::shared_ptr player) { +void Player::sendPlayerPartyIcons(const std::shared_ptr &player) const { sendPartyCreatureShield(player); sendPartyCreatureSkull(player); } -bool Player::addPartyInvitation(std::shared_ptr newParty) { +bool Player::addPartyInvitation(const std::shared_ptr &newParty) { auto it = std::find(invitePartyList.begin(), invitePartyList.end(), newParty); if (it != invitePartyList.end()) { return false; @@ -5700,7 +5700,7 @@ bool Player::addPartyInvitation(std::shared_ptr newParty) { return true; } -void Player::removePartyInvitation(std::shared_ptr remParty) { +void Player::removePartyInvitation(const std::shared_ptr &remParty) { std::erase(invitePartyList, remParty); } @@ -5711,7 +5711,7 @@ void Player::clearPartyInvitations() { invitePartyList.clear(); } -GuildEmblems_t Player::getGuildEmblem(std::shared_ptr player) const { +GuildEmblems_t Player::getGuildEmblem(const std::shared_ptr &player) const { if (!player) { return GUILDEMBLEM_NONE; } @@ -5942,7 +5942,7 @@ bool Player::untameMount(uint8_t mountId) { return true; } -bool Player::hasMount(const std::shared_ptr mount) const { +bool Player::hasMount(const std::shared_ptr &mount) const { if (isAccessPlayer()) { return true; } @@ -6223,7 +6223,7 @@ void Player::removeBakragoreIcon(const IconBakragore icon) { } } -void Player::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, std::vector> achievementsUnlocked) { +void Player::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked) { if (client) { client->sendCyclopediaCharacterAchievements(secretsUnlocked, achievementsUnlocked); } @@ -6234,7 +6234,7 @@ uint64_t Player::getMoney() const { uint64_t moneyCount = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -6318,7 +6318,7 @@ std::vector> Player::getMuteConditions() const { return muteConditions; } -void Player::setGuild(const std::shared_ptr newGuild) { +void Player::setGuild(const std::shared_ptr &newGuild) { if (newGuild == guild) { return; } @@ -6505,7 +6505,7 @@ bool Player::addItemFromStash(uint16_t itemId, uint32_t itemCount) { void sendStowItems(const std::shared_ptr &item, const std::shared_ptr &stowItem, StashContainerList &itemDict) { if (stowItem->getID() == item->getID()) { - itemDict.push_back(std::pair, uint32_t>(stowItem, stowItem->getItemCount())); + itemDict.emplace_back(stowItem, stowItem->getItemCount()); } if (auto container = stowItem->getContainer()) { @@ -6517,7 +6517,7 @@ void sendStowItems(const std::shared_ptr &item, const std::shared_ptr item, uint32_t count, bool allItems) { +void Player::stowItem(const std::shared_ptr &item, uint32_t count, bool allItems) { if (!item || !item->isItemStorable()) { sendCancelMessage("This item cannot be stowed here."); return; @@ -6578,7 +6578,7 @@ void Player::openPlayerContainers() { std::vector>> openContainersList; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - std::shared_ptr item = inventory[i]; + const auto item = inventory[i]; if (!item) { continue; } @@ -6687,7 +6687,7 @@ std::string Player::getBlessingsName() const { return os.str(); } -bool Player::isCreatureUnlockedOnTaskHunting(const std::shared_ptr mtype) const { +bool Player::isCreatureUnlockedOnTaskHunting(const std::shared_ptr &mtype) const { if (!mtype) { return false; } @@ -6876,7 +6876,7 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { } for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; if (!item || item->getID() != itemId || item->getTier() != tier) { continue; } @@ -6917,7 +6917,7 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool } for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; if (!item) { continue; } @@ -6953,7 +6953,7 @@ void Player::openContainerFromDepotSearch(const Position &pos) { return; } - std::shared_ptr item = getItemFromDepotSearch(depotSearchOnItem.first, pos); + const auto item = getItemFromDepotSearch(depotSearchOnItem.first, pos); if (!item) { sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -6983,7 +6983,7 @@ std::shared_ptr Player::getItemFromDepotSearch(uint16_t itemId, const Posi } for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; if (!item || item->getID() != itemId || item->getTier() != depotSearchOnItem.second) { continue; } @@ -6999,7 +6999,7 @@ std::shared_ptr Player::getItemFromDepotSearch(uint16_t itemId, const Posi } std::pair>, std::map>> -Player::requestLockerItems(std::shared_ptr depotLocker, bool sendToClient /*= false*/, uint8_t tier /*= 0*/) const { +Player::requestLockerItems(const std::shared_ptr &depotLocker, bool sendToClient /*= false*/, uint8_t tier /*= 0*/) const { if (!depotLocker) { g_logger().error("{} - Depot locker is nullptr", __FUNCTION__); return {}; @@ -7048,7 +7048,7 @@ Player::requestLockerItems(std::shared_ptr depotLocker, bool sendTo return { itemVector, lockerItems }; } -std::pair>, uint16_t> Player::getLockerItemsAndCountById(const std::shared_ptr &depotLocker, uint8_t tier, uint16_t itemId) { +std::pair>, uint16_t> Player::getLockerItemsAndCountById(const std::shared_ptr &depotLocker, uint8_t tier, uint16_t itemId) const { std::vector> lockerItems; auto [itemVector, itemMap] = requestLockerItems(depotLocker, false, tier); uint16_t totalCount = 0; @@ -7518,7 +7518,7 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { } auto itemCount = static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); - std::shared_ptr item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); + const auto item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); returnValue = g_game().internalPlayerAddItem(static_self_cast(), item); if (returnValue != RETURNVALUE_NOERROR) { g_logger().error("Failed to add {} slivers to player with name {}", itemCount, getName()); @@ -7544,7 +7544,7 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { return; } - if (std::shared_ptr item = Item::CreateItem(ITEM_FORGE_CORE, 1); + if (const auto item = Item::CreateItem(ITEM_FORGE_CORE, 1); item) { returnValue = g_game().internalPlayerAddItem(static_self_cast(), item); } @@ -7907,7 +7907,7 @@ void Player::setHazardSystemPoints(int32_t count) { } } -void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptr monster) { +void Player::parseAttackRecvHazardSystem(CombatDamage &damage, const std::shared_ptr &monster) { if (!monster || !monster->getHazard()) { return; } @@ -7966,7 +7966,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptr monster) { +void Player::parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster) { if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM, __FUNCTION__)) { return; } diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 5a703a1d0bf..13be5603b9a 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "items/containers/container.hpp" #include "creatures/creature.hpp" #include "items/cylinder.hpp" @@ -47,7 +49,6 @@ class Weapon; class ProtocolGame; class Party; class Task; -class Bed; class Guild; class Imbuement; class PreySlot; @@ -124,7 +125,7 @@ class Player final : public Creature, public Cylinder, public Bankable { }; explicit Player(ProtocolGame_ptr p); - ~Player(); + ~Player() override; // non-copyable Player(const Player &) = delete; @@ -137,7 +138,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return static_self_cast(); } - static std::shared_ptr createPlayerTask(uint32_t delay, std::function f, std::string context); + static std::shared_ptr createPlayerTask(uint32_t delay, std::function f, const std::string &context); void setID() override; @@ -180,7 +181,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool toggleMount(bool mount); bool tameMount(uint8_t mountId); bool untameMount(uint8_t mountId); - bool hasMount(const std::shared_ptr mount) const; + bool hasMount(const std::shared_ptr &mount) const; bool hasAnyMount() const; uint8_t getRandomMountId() const; void dismount(); @@ -282,25 +283,25 @@ class Player final : public Creature, public Cylinder, public Bankable { [[nodiscard]] std::shared_ptr getGuild() const { return guild; } - void setGuild(const std::shared_ptr guild); + void setGuild(const std::shared_ptr &guild); [[nodiscard]] GuildRank_ptr getGuildRank() const { return guildRank; } void setGuildRank(GuildRank_ptr newGuildRank) { - guildRank = newGuildRank; + guildRank = std::move(newGuildRank); } - bool isGuildMate(std::shared_ptr player) const; + bool isGuildMate(const std::shared_ptr &player) const; [[nodiscard]] const std::string &getGuildNick() const { return guildNick; } void setGuildNick(std::string nick) { - guildNick = nick; + guildNick = std::move(nick); } - bool isInWar(std::shared_ptr player) const; + bool isInWar(const std::shared_ptr &player) const; bool isInWarList(uint32_t guild_id) const; void setLastWalkthroughAttempt(int64_t walkthroughAttempt) { @@ -324,9 +325,9 @@ class Player final : public Creature, public Cylinder, public Bankable { return isBoss ? m_bosstiaryMonsterTracker : m_bestiaryMonsterTracker; } - void addMonsterToCyclopediaTrackerList(const std::shared_ptr mtype, bool isBoss, bool reloadClient = false); + void addMonsterToCyclopediaTrackerList(const std::shared_ptr &mtype, bool isBoss, bool reloadClient = false); - void removeMonsterFromCyclopediaTrackerList(std::shared_ptr mtype, bool isBoss, bool reloadClient = false); + void removeMonsterFromCyclopediaTrackerList(const std::shared_ptr &mtype, bool isBoss, bool reloadClient = false); void sendBestiaryEntryChanged(uint16_t raceid) { if (client) { @@ -334,7 +335,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } } - void refreshCyclopediaMonsterTracker(bool isBoss = false) { + void refreshCyclopediaMonsterTracker(bool isBoss = false) const { refreshCyclopediaMonsterTracker(getCyclopediaMonsterTrackerSet(isBoss), isBoss); } @@ -374,7 +375,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } void setParty(std::shared_ptr newParty) { - m_party = newParty; + m_party = std::move(newParty); } std::shared_ptr getParty() const { return m_party; @@ -421,17 +422,17 @@ class Player final : public Creature, public Cylinder, public Bankable { int32_t getReflectFlat(CombatType_t combat, bool useCharges = false) const override; - PartyShields_t getPartyShield(std::shared_ptr player); - bool isInviting(std::shared_ptr player) const; - bool isPartner(std::shared_ptr player) const; - void sendPlayerPartyIcons(std::shared_ptr player); - bool addPartyInvitation(std::shared_ptr party); - void removePartyInvitation(std::shared_ptr party); + PartyShields_t getPartyShield(const std::shared_ptr &player); + bool isInviting(const std::shared_ptr &player) const; + bool isPartner(const std::shared_ptr &player) const; + void sendPlayerPartyIcons(const std::shared_ptr &player) const; + bool addPartyInvitation(const std::shared_ptr &party); + void removePartyInvitation(const std::shared_ptr &party); void clearPartyInvitations(); void sendUnjustifiedPoints(); - GuildEmblems_t getGuildEmblem(std::shared_ptr player) const; + GuildEmblems_t getGuildEmblem(const std::shared_ptr &player) const; uint64_t getSpentMana() const { return manaSpent; @@ -453,7 +454,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return bedItem; } void setBedItem(std::shared_ptr b) { - bedItem = b; + bedItem = std::move(b); } bool hasImbuingItem() { @@ -510,21 +511,21 @@ class Player final : public Creature, public Cylinder, public Bankable { return getIP() == 0; } - void addContainer(uint8_t cid, std::shared_ptr container); + void addContainer(uint8_t cid, const std::shared_ptr &container); void closeContainer(uint8_t cid); void setContainerIndex(uint8_t cid, uint16_t index); std::shared_ptr getContainerByID(uint8_t cid); - int8_t getContainerID(std::shared_ptr container) const; + int8_t getContainerID(const std::shared_ptr &container) const; uint16_t getContainerIndex(uint8_t cid) const; bool canOpenCorpse(uint32_t ownerId) const; - void addStorageValue(const uint32_t key, const int32_t value, const bool isLogin = false); - int32_t getStorageValue(const uint32_t key) const; + void addStorageValue(uint32_t key, int32_t value, bool isLogin = false); + int32_t getStorageValue(uint32_t key) const; int32_t getStorageValueByName(const std::string &storageName) const; - void addStorageValueByName(const std::string &storageName, const int32_t value, const bool isLogin = false); + void addStorageValueByName(const std::string &storageName, int32_t value, bool isLogin = false); std::shared_ptr kv() const { return g_kv().scoped("player")->scoped(fmt::format("{}", getGUID())); @@ -533,7 +534,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void genReservedStorageRange(); void setGroup(std::shared_ptr newGroup) { - group = newGroup; + group = std::move(newGroup); } std::shared_ptr getGroup() const { return group; @@ -574,13 +575,13 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isDepotSearchAvailable() const { return depotSearch; } - bool isSupplyStashMenuAvailable() { + bool isSupplyStashMenuAvailable() const { return supplyStash; } - bool isMarketMenuAvailable() { + bool isMarketMenuAvailable() const { return marketMenu; } - bool isExerciseTraining() { + bool isExerciseTraining() const { return exerciseTraining; } void setExerciseTraining(bool isTraining) { @@ -796,27 +797,27 @@ class Player final : public Creature, public Cylinder, public Bankable { void addConditionSuppressions(const std::array &addCondition); void removeConditionSuppressions(); - std::shared_ptr getReward(const uint64_t rewardId, const bool autoCreate); + std::shared_ptr getReward(uint64_t rewardId, bool autoCreate); void removeReward(uint64_t rewardId); void getRewardList(std::vector &rewards) const; std::shared_ptr getRewardChest(); - std::vector> getRewardsFromContainer(std::shared_ptr container) const; + std::vector> getRewardsFromContainer(const std::shared_ptr &container) const; std::shared_ptr getDepotChest(uint32_t depotId, bool autoCreate); std::shared_ptr getDepotLocker(uint32_t depotId); void onReceiveMail(); bool isNearDepotBox(); - std::shared_ptr refreshManagedContainer(ObjectCategory_t category, std::shared_ptr container, bool isLootContainer, bool loading = false); + std::shared_ptr refreshManagedContainer(ObjectCategory_t category, const std::shared_ptr &container, bool isLootContainer, bool loading = false); std::shared_ptr getManagedContainer(ObjectCategory_t category, bool isLootContainer) const; - void setMainBackpackUnassigned(std::shared_ptr container); + void setMainBackpackUnassigned(const std::shared_ptr &container); bool canSee(const Position &pos) override; bool canSeeCreature(std::shared_ptr creature) const override; - bool canWalkthrough(std::shared_ptr creature); - bool canWalkthroughEx(std::shared_ptr creature); + bool canWalkthrough(const std::shared_ptr &creature); + bool canWalkthroughEx(const std::shared_ptr &creature); RaceType_t getRace() const override { return RACE_BLOOD; @@ -838,7 +839,7 @@ class Player final : public Creature, public Cylinder, public Bankable { // shop functions void setShopOwner(std::shared_ptr owner) { - shopOwner = owner; + shopOwner = std::move(owner); } std::shared_ptr getShopOwner() const { @@ -858,9 +859,9 @@ class Player final : public Creature, public Cylinder, public Bankable { void onWalkComplete() override; void stopWalk(); - bool openShopWindow(std::shared_ptr npc, const std::vector &shopItems = {}); + bool openShopWindow(const std::shared_ptr &npc, const std::vector &shopItems = {}); bool closeShopWindow(); - bool updateSaleShopList(std::shared_ptr item); + bool updateSaleShopList(const std::shared_ptr &item); bool hasShopItemForSale(uint16_t itemId, uint8_t subType) const; void setChaseMode(bool mode); @@ -884,11 +885,11 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isImmune(ConditionType_t type) const override; bool hasShield() const; bool isAttackable() const override; - static bool lastHitIsPlayer(std::shared_ptr lastHitCreature); + static bool lastHitIsPlayer(const std::shared_ptr &lastHitCreature); // stash functions bool addItemFromStash(uint16_t itemId, uint32_t itemCount); - void stowItem(std::shared_ptr item, uint32_t count, bool allItems); + void stowItem(const std::shared_ptr &item, uint32_t count, bool allItems); void changeHealth(int32_t healthChange, bool sendHealthChange = true) override; void changeMana(int32_t manaChange) override; @@ -967,12 +968,10 @@ class Player final : public Creature, public Cylinder, public Bankable { lastAggressiveAction = OTSYS_TIME(); } - std::unordered_set getNPCSkips(); - std::shared_ptr getWeapon(Slots_t slot, bool ignoreAmmo) const; std::shared_ptr getWeapon(bool ignoreAmmo = false) const; WeaponType_t getWeaponType() const; - int32_t getWeaponSkill(std::shared_ptr item) const; + int32_t getWeaponSkill(const std::shared_ptr &item) const; void getShieldAndWeapon(std::shared_ptr &shield, std::shared_ptr &weapon) const; void drainHealth(std::shared_ptr attacker, int32_t damage) override; @@ -985,7 +984,6 @@ class Player final : public Creature, public Cylinder, public Bankable { float getAttackFactor() const override; float getDefenseFactor() const override; float getMitigation() const override; - double getMitigationMultiplier() const; void addInFightTicks(bool pzlock = false); @@ -1003,7 +1001,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool onKilledPlayer(const std::shared_ptr &target, bool lastHit) override; bool onKilledMonster(const std::shared_ptr &target) override; void onGainExperience(uint64_t gainExp, std::shared_ptr target) override; - void onGainSharedExperience(uint64_t gainExp, std::shared_ptr target); + void onGainSharedExperience(uint64_t gainExp, const std::shared_ptr &target); void onAttackedCreatureBlockHit(BlockType_t blockType) override; void onBlockHit() override; void onTakeDamage(std::shared_ptr attacker, int32_t damage) override; @@ -1023,17 +1021,17 @@ class Player final : public Creature, public Cylinder, public Bankable { skullTicks = ticks; } - bool hasAttacked(std::shared_ptr attacked) const; - void addAttacked(std::shared_ptr attacked); - void removeAttacked(std::shared_ptr attacked); + bool hasAttacked(const std::shared_ptr &attacked) const; + void addAttacked(const std::shared_ptr &attacked); + void removeAttacked(const std::shared_ptr &attacked); void clearAttacked(); - void addUnjustifiedDead(std::shared_ptr attacked); - void sendCreatureEmblem(std::shared_ptr creature) const { + void addUnjustifiedDead(const std::shared_ptr &attacked); + void sendCreatureEmblem(const std::shared_ptr &creature) const { if (client) { client->sendCreatureEmblem(creature); } } - void sendCreatureSkull(std::shared_ptr creature) const { + void sendCreatureSkull(const std::shared_ptr &creature) const { if (client) { client->sendCreatureSkull(creature); } @@ -1056,13 +1054,13 @@ class Player final : public Creature, public Cylinder, public Bankable { bool canLogout(); - bool hasKilled(std::shared_ptr player) const; + bool hasKilled(const std::shared_ptr &player) const; size_t getMaxDepotItems() const; // tile // send methods - void sendAddTileItem(std::shared_ptr itemTile, const Position &pos, std::shared_ptr item) { + void sendAddTileItem(const std::shared_ptr &itemTile, const Position &pos, const std::shared_ptr &item) { if (client) { int32_t stackpos = itemTile->getStackposOfItem(static_self_cast(), item); if (stackpos != -1) { @@ -1070,7 +1068,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendUpdateTileItem(std::shared_ptr updateTile, const Position &pos, std::shared_ptr item) { + void sendUpdateTileItem(const std::shared_ptr &updateTile, const Position &pos, const std::shared_ptr &item) { if (client) { int32_t stackpos = updateTile->getStackposOfItem(static_self_cast(), item); if (stackpos != -1) { @@ -1083,12 +1081,12 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendRemoveTileThing(pos, stackpos); } } - void sendUpdateTileCreature(const std::shared_ptr creature) { + void sendUpdateTileCreature(const std::shared_ptr &creature) { if (client) { client->sendUpdateTileCreature(creature->getPosition(), creature->getTile()->getClientIndexOfCreature(static_self_cast(), creature), creature); } } - void sendUpdateTile(std::shared_ptr updateTile, const Position &pos) { + void sendUpdateTile(const std::shared_ptr &updateTile, const Position &pos) { if (client) { client->sendUpdateTile(updateTile, pos); } @@ -1104,7 +1102,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendChannelEvent(channelId, playerName, channelEvent); } } - void sendCreatureAppear(std::shared_ptr creature, const Position &pos, bool isLogin) { + void sendCreatureAppear(const std::shared_ptr &creature, const Position &pos, bool isLogin) { if (!creature) { return; } @@ -1118,12 +1116,12 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendAddCreature(creature, pos, tile->getStackposOfCreature(static_self_cast(), creature), isLogin); } } - void sendCreatureMove(std::shared_ptr creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { + void sendCreatureMove(const std::shared_ptr &creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { if (client) { client->sendMoveCreature(creature, newPos, newStackPos, oldPos, oldStackPos, teleport); } } - void sendCreatureTurn(std::shared_ptr creature) { + void sendCreatureTurn(const std::shared_ptr &creature) { if (!creature) { return; } @@ -1140,32 +1138,32 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr) { + void sendCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr) { if (client) { client->sendCreatureSay(creature, type, text, pos); } } - void sendCreatureReload(std::shared_ptr creature) { + void sendCreatureReload(const std::shared_ptr &creature) { if (client) { client->reloadCreature(creature); } } - void sendPrivateMessage(std::shared_ptr speaker, SpeakClasses type, const std::string &text) { + void sendPrivateMessage(const std::shared_ptr &speaker, SpeakClasses type, const std::string &text) { if (client) { client->sendPrivateMessage(speaker, type, text); } } - void sendCreatureSquare(std::shared_ptr creature, SquareColor_t color) { + void sendCreatureSquare(const std::shared_ptr &creature, SquareColor_t color) { if (client) { client->sendCreatureSquare(creature, color); } } - void sendCreatureChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit) { + void sendCreatureChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) { if (client) { client->sendCreatureOutfit(creature, outfit); } } - void sendCreatureChangeVisible(std::shared_ptr creature, bool visible) { + void sendCreatureChangeVisible(const std::shared_ptr &creature, bool visible) { if (!client || !creature) { return; } @@ -1196,32 +1194,32 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendCreatureLight(std::shared_ptr creature) { + void sendCreatureLight(const std::shared_ptr &creature) { if (client) { client->sendCreatureLight(creature); } } - void sendCreatureIcon(std::shared_ptr creature) { + void sendCreatureIcon(const std::shared_ptr &creature) { if (client && !client->oldProtocol) { client->sendCreatureIcon(creature); } } - void sendUpdateCreature(std::shared_ptr creature) const { + void sendUpdateCreature(const std::shared_ptr &creature) const { if (client) { client->sendUpdateCreature(creature); } } - void sendCreatureWalkthrough(std::shared_ptr creature, bool walkthrough) { + void sendCreatureWalkthrough(const std::shared_ptr &creature, bool walkthrough) { if (client) { client->sendCreatureWalkthrough(creature, walkthrough); } } - void sendCreatureShield(std::shared_ptr creature) { + void sendCreatureShield(const std::shared_ptr &creature) { if (client) { client->sendCreatureShield(creature); } } - void sendCreatureType(std::shared_ptr creature, uint8_t creatureType) { + void sendCreatureType(const std::shared_ptr &creature, uint8_t creatureType) { if (client) { client->sendCreatureType(creature, creatureType); } @@ -1241,7 +1239,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendUseItemCooldown(time); } } - void reloadCreature(std::shared_ptr creature) { + void reloadCreature(const std::shared_ptr &creature) { if (client) { client->reloadCreature(creature); } @@ -1250,10 +1248,10 @@ class Player final : public Creature, public Cylinder, public Bankable { // container void closeAllExternalContainers(); - void sendAddContainerItem(std::shared_ptr container, std::shared_ptr item); - void sendUpdateContainerItem(std::shared_ptr container, uint16_t slot, std::shared_ptr newItem); - void sendRemoveContainerItem(std::shared_ptr container, uint16_t slot); - void sendContainer(uint8_t cid, std::shared_ptr container, bool hasParent, uint16_t firstIndex) { + void sendAddContainerItem(const std::shared_ptr &container, std::shared_ptr item); + void sendUpdateContainerItem(const std::shared_ptr &container, uint16_t slot, const std::shared_ptr &newItem); + void sendRemoveContainerItem(const std::shared_ptr &container, uint16_t slot); + void sendContainer(uint8_t cid, const std::shared_ptr &container, bool hasParent, uint16_t firstIndex) { if (client) { client->sendContainer(cid, container, hasParent, firstIndex); } @@ -1280,7 +1278,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendCoinBalance(); } } - void sendInventoryItem(Slots_t slot, std::shared_ptr item) { + void sendInventoryItem(Slots_t slot, const std::shared_ptr &item) { if (client) { client->sendInventoryItem(slot, item); } @@ -1330,17 +1328,17 @@ class Player final : public Creature, public Cylinder, public Bankable { void onFollowCreatureDisappear(bool isLogout) override; // container - void onAddContainerItem(std::shared_ptr item); - void onUpdateContainerItem(std::shared_ptr container, std::shared_ptr oldItem, std::shared_ptr newItem); - void onRemoveContainerItem(std::shared_ptr container, std::shared_ptr item); + void onAddContainerItem(const std::shared_ptr &item); + void onUpdateContainerItem(const std::shared_ptr &container, const std::shared_ptr &oldItem, const std::shared_ptr &newItem); + void onRemoveContainerItem(const std::shared_ptr &container, const std::shared_ptr &item); - void onCloseContainer(std::shared_ptr container); - void onSendContainer(std::shared_ptr container); - void autoCloseContainers(std::shared_ptr container); + void onCloseContainer(const std::shared_ptr &container); + void onSendContainer(const std::shared_ptr &container); + void autoCloseContainers(const std::shared_ptr &container); // inventory - void onUpdateInventoryItem(std::shared_ptr oldItem, std::shared_ptr newItem); - void onRemoveInventoryItem(std::shared_ptr item); + void onUpdateInventoryItem(const std::shared_ptr &oldItem, const std::shared_ptr &newItem); + void onRemoveInventoryItem(const std::shared_ptr &item); void sendCancelMessage(const std::string &msg) const { if (client) { @@ -1358,52 +1356,52 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendCancelWalk(); } } - void sendChangeSpeed(std::shared_ptr creature, uint16_t newSpeed) const { + void sendChangeSpeed(const std::shared_ptr &creature, uint16_t newSpeed) const { if (client) { client->sendChangeSpeed(creature, newSpeed); } } - void sendCreatureHealth(std::shared_ptr creature) const { + void sendCreatureHealth(const std::shared_ptr &creature) const { if (client) { client->sendCreatureHealth(creature); } } - void sendPartyCreatureUpdate(std::shared_ptr creature) const { + void sendPartyCreatureUpdate(const std::shared_ptr &creature) const { if (client) { client->sendPartyCreatureUpdate(creature); } } - void sendPartyCreatureShield(std::shared_ptr creature) const { + void sendPartyCreatureShield(const std::shared_ptr &creature) const { if (client) { client->sendPartyCreatureShield(creature); } } - void sendPartyCreatureSkull(std::shared_ptr creature) const { + void sendPartyCreatureSkull(const std::shared_ptr &creature) const { if (client) { client->sendPartyCreatureSkull(creature); } } - void sendPartyCreatureHealth(std::shared_ptr creature, uint8_t healthPercent) const { + void sendPartyCreatureHealth(const std::shared_ptr &creature, uint8_t healthPercent) const { if (client) { client->sendPartyCreatureHealth(creature, healthPercent); } } - void sendPartyPlayerMana(std::shared_ptr player, uint8_t manaPercent) const { + void sendPartyPlayerMana(const std::shared_ptr &player, uint8_t manaPercent) const { if (client) { client->sendPartyPlayerMana(player, manaPercent); } } - void sendPartyCreatureShowStatus(std::shared_ptr creature, bool showStatus) const { + void sendPartyCreatureShowStatus(const std::shared_ptr &creature, bool showStatus) const { if (client) { client->sendPartyCreatureShowStatus(creature, showStatus); } } - void sendPartyPlayerVocation(std::shared_ptr player) const { + void sendPartyPlayerVocation(const std::shared_ptr &player) const { if (client) { client->sendPartyPlayerVocation(player); } } - void sendPlayerVocation(std::shared_ptr player) const { + void sendPlayerVocation(const std::shared_ptr &player) const { if (client) { client->sendPlayerVocation(player); } @@ -1413,7 +1411,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendDistanceShoot(from, to, type); } } - void sendHouseWindow(std::shared_ptr house, uint32_t listId) const; + void sendHouseWindow(const std::shared_ptr &house, uint32_t listId) const; void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) { if (client) { client->sendCreatePrivateChannel(channelId, channelName); @@ -1481,17 +1479,17 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendReLoginWindow(unfairFightReduction); } } - void sendTextWindow(std::shared_ptr item, uint16_t maxlen, bool canWrite) const { + void sendTextWindow(const std::shared_ptr &item, uint16_t maxlen, bool canWrite) const { if (client) { client->sendTextWindow(windowTextId, item, maxlen, canWrite); } } - void sendToChannel(std::shared_ptr creature, SpeakClasses type, const std::string &text, uint16_t channelId) const { + void sendToChannel(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, uint16_t channelId) const { if (client) { client->sendToChannel(creature, type, text, channelId); } } - void sendShop(std::shared_ptr npc) const { + void sendShop(const std::shared_ptr &npc) const { if (client) { client->sendShop(npc); } @@ -1539,7 +1537,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendMarketCancelOffer(offer); } } - void sendTradeItemRequest(const std::string &traderName, std::shared_ptr item, bool ack) const { + void sendTradeItemRequest(const std::string &traderName, const std::shared_ptr &item, bool ack) const { if (client) { client->sendTradeItemRequest(traderName, item, ack); } @@ -1580,10 +1578,10 @@ class Player final : public Creature, public Cylinder, public Bankable { } } // Imbuements - void onApplyImbuement(Imbuement* imbuement, std::shared_ptr item, uint8_t slot, bool protectionCharm); - void onClearImbuement(std::shared_ptr item, uint8_t slot); - void openImbuementWindow(std::shared_ptr item); - void sendImbuementResult(const std::string message) { + void onApplyImbuement(Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm); + void onClearImbuement(const std::shared_ptr &item, uint8_t slot); + void openImbuementWindow(const std::shared_ptr &item); + void sendImbuementResult(const std::string &message) { if (client) { client->sendImbuementResult(message); } @@ -1593,7 +1591,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->closeImbuementWindow(); } } - void sendPodiumWindow(std::shared_ptr podium, const Position &position, uint16_t itemId, uint8_t stackpos) { + void sendPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos) { if (client) { client->sendPodiumWindow(podium, position, itemId, stackpos); } @@ -1619,7 +1617,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendAddMarker(pos, markType, desc); } } - void sendItemInspection(uint16_t itemId, uint8_t itemCount, std::shared_ptr item, bool cyclopedia) { + void sendItemInspection(uint16_t itemId, uint8_t itemCount, const std::shared_ptr &item, bool cyclopedia) { if (client) { client->sendItemInspection(itemId, itemCount, item, cyclopedia); } @@ -1654,7 +1652,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendCyclopediaCharacterRecentPvPKills(page, pages, entries); } } - void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, std::vector> achievementsUnlocked); + void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked); void sendCyclopediaCharacterItemSummary(const ItemsTierCountList &inventoryItems, const ItemsTierCountList &storeInboxItems, const StashItemList &supplyStashItems, const ItemsTierCountList &depotBoxItems, const ItemsTierCountList &inboxItems) { if (client) { client->sendCyclopediaCharacterItemSummary(inventoryItems, storeInboxItems, supplyStashItems, depotBoxItems, inboxItems); @@ -1776,7 +1774,7 @@ class Player final : public Creature, public Cylinder, public Bankable { uint32_t getNextPotionActionTime() const; std::shared_ptr getWriteItem(uint32_t &windowTextId, uint16_t &maxWriteLen); - void setWriteItem(std::shared_ptr item, uint16_t maxWriteLen = 0); + void setWriteItem(const std::shared_ptr &item, uint16_t maxWriteLen = 0); std::shared_ptr getEditHouse(uint32_t &windowTextId, uint32_t &listId); void setEditHouse(std::shared_ptr house, uint32_t listId = 0); @@ -1791,11 +1789,11 @@ class Player final : public Creature, public Cylinder, public Bankable { scheduledSaleUpdate = scheduled; } - bool getScheduledSaleUpdate() { + bool getScheduledSaleUpdate() const { return scheduledSaleUpdate; } - bool inPushEvent() { + bool inPushEvent() const { return inEventMovePush; } @@ -1859,7 +1857,7 @@ class Player final : public Creature, public Cylinder, public Bankable { xpBoostTime = timeLeft; } - uint16_t getXpBoostTime() { + uint16_t getXpBoostTime() const { return xpBoostTime; } @@ -1876,7 +1874,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isUIExhausted(uint32_t exhaustionTime = 250) const; void updateUIExhausted(); - bool isQuickLootListedItem(std::shared_ptr item) const { + bool isQuickLootListedItem(const std::shared_ptr &item) const { if (!item) { return false; } @@ -1885,7 +1883,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return it != quickLootListItemIds.end(); } - bool updateKillTracker(std::shared_ptr corpse, const std::string &playerName, const Outfit_t creatureOutfit) const { + bool updateKillTracker(const std::shared_ptr &corpse, const std::string &playerName, const Outfit_t creatureOutfit) const { if (client) { client->sendKillTrackerUpdate(corpse, playerName, creatureOutfit); return true; @@ -1900,11 +1898,11 @@ class Player final : public Creature, public Cylinder, public Bankable { } } - void sendLootStats(std::shared_ptr item, uint8_t count); - void updateSupplyTracker(std::shared_ptr item); + void sendLootStats(const std::shared_ptr &item, uint8_t count); + void updateSupplyTracker(const std::shared_ptr &item); void updateImpactTracker(CombatType_t type, int32_t amount) const; - void updateInputAnalyzer(CombatType_t type, int32_t amount, std::string target) { + void updateInputAnalyzer(CombatType_t type, int32_t amount, const std::string &target) { if (client) { client->sendUpdateInputAnalyzer(type, amount, target); } @@ -1934,13 +1932,13 @@ class Player final : public Creature, public Cylinder, public Bankable { void setItemCustomPrice(uint16_t itemId, uint64_t price) { itemPriceMap[itemId] = price; } - uint32_t getCharmPoints() { + uint32_t getCharmPoints() const { return charmPoints; } void setCharmPoints(uint32_t points) { charmPoints = points; } - bool hasCharmExpansion() { + bool hasCharmExpansion() const { return charmExpansion; } void setCharmExpansion(bool onOff) { @@ -1949,20 +1947,20 @@ class Player final : public Creature, public Cylinder, public Bankable { void setUsedRunesBit(int32_t bit) { UsedRunesBit = bit; } - int32_t getUsedRunesBit() { + int32_t getUsedRunesBit() const { return UsedRunesBit; } void setUnlockedRunesBit(int32_t bit) { UnlockedRunesBit = bit; } - int32_t getUnlockedRunesBit() { + int32_t getUnlockedRunesBit() const { return UnlockedRunesBit; } void setImmuneCleanse(ConditionType_t conditiontype) { cleanseCondition.first = conditiontype; cleanseCondition.second = OTSYS_TIME() + 10000; } - bool isImmuneCleanse(ConditionType_t conditiontype) { + bool isImmuneCleanse(ConditionType_t conditiontype) const { uint64_t timenow = OTSYS_TIME(); if ((cleanseCondition.first == conditiontype) && (timenow <= cleanseCondition.second)) { @@ -2239,7 +2237,7 @@ class Player final : public Creature, public Cylinder, public Bankable { // Task hunting system void initializeTaskHunting(); - bool isCreatureUnlockedOnTaskHunting(const std::shared_ptr mtype) const; + bool isCreatureUnlockedOnTaskHunting(const std::shared_ptr &mtype) const; bool setTaskHuntingSlotClass(std::unique_ptr &slot) { if (getTaskHuntingSlotById(slot->id)) { @@ -2346,7 +2344,7 @@ class Player final : public Creature, public Cylinder, public Bankable { sendSkills(); } void setLoyaltyTitle(std::string title) { - loyaltyTitle = title; + loyaltyTitle = std::move(title); } std::string getLoyaltyTitle() const { return loyaltyTitle; @@ -2362,7 +2360,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void openContainerFromDepotSearch(const Position &pos); std::shared_ptr getItemFromDepotSearch(uint16_t itemId, const Position &pos); - std::pair>, std::map>> requestLockerItems(std::shared_ptr depotLocker, bool sendToClient = false, uint8_t tier = 0) const; + std::pair>, std::map>> requestLockerItems(const std::shared_ptr &depotLocker, bool sendToClient = false, uint8_t tier = 0) const; /** This function returns a pair of an array of items and a 16-bit integer from a DepotLocker instance, a 8-bit byte and a 16-bit integer. @@ -2376,7 +2374,7 @@ class Player final : public Creature, public Cylinder, public Bankable { const std::shared_ptr &depotLocker, uint8_t tier, uint16_t itemId - ); + ) const; bool saySpell( SpeakClasses type, @@ -2512,7 +2510,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return bossRemoveTimes; } - void sendMonsterPodiumWindow(std::shared_ptr podium, const Position &position, uint16_t itemId, uint8_t stackpos) const { + void sendMonsterPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos) const { if (client) { client->sendMonsterPodiumWindow(podium, position, itemId, stackpos); } @@ -2524,7 +2522,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } } - void sendInventoryImbuements(const std::map> items) const { + void sendInventoryImbuements(const std::map> &items) const { if (client) { client->sendInventoryImbuements(items); } @@ -2534,8 +2532,8 @@ class Player final : public Creature, public Cylinder, public Bankable { * Hazard system ******************************************************************************/ // Parser - void parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptr monster); - void parseAttackDealtHazardSystem(CombatDamage &damage, std::shared_ptr monster); + void parseAttackRecvHazardSystem(CombatDamage &damage, const std::shared_ptr &monster); + void parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster); // Points increase: void setHazardSystemPoints(int32_t amount); // Points get: @@ -2562,7 +2560,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return activeConcoctions; } bool isConcoctionActive(Concoction_t concotion) const { - uint16_t itemId = static_cast(concotion); + auto itemId = static_cast(concotion); if (!activeConcoctions.contains(itemId)) { return false; } @@ -2666,13 +2664,13 @@ class Player final : public Creature, public Cylinder, public Bankable { std::vector> getMuteConditions() const; - void checkTradeState(std::shared_ptr item); - bool hasCapacity(std::shared_ptr item, uint32_t count) const; + void checkTradeState(const std::shared_ptr &item); + bool hasCapacity(const std::shared_ptr &item, uint32_t count) const; - void checkLootContainers(std::shared_ptr item); + void checkLootContainers(const std::shared_ptr &item); - void gainExperience(uint64_t exp, std::shared_ptr target); - void addExperience(std::shared_ptr target, uint64_t exp, bool sendText = false); + void gainExperience(uint64_t exp, const std::shared_ptr &target); + void addExperience(const std::shared_ptr &target, uint64_t exp, bool sendText = false); void removeExperience(uint64_t exp, bool sendText = false); void updateInventoryWeight(); @@ -2683,10 +2681,10 @@ class Player final : public Creature, public Cylinder, public Bankable { void updateInventoryImbuement(); void setNextWalkActionTask(std::shared_ptr task); - void setNextWalkTask(std::shared_ptr task); - void setNextActionTask(std::shared_ptr task, bool resetIdleTime = true); - void setNextActionPushTask(std::shared_ptr task); - void setNextPotionActionTask(std::shared_ptr task); + void setNextWalkTask(const std::shared_ptr &task); + void setNextActionTask(const std::shared_ptr &task, bool resetIdleTime = true); + void setNextActionPushTask(const std::shared_ptr &task); + void setNextPotionActionTask(const std::shared_ptr &task); void death(std::shared_ptr lastHitCreature) override; bool spawn(); @@ -2712,7 +2710,7 @@ class Player final : public Creature, public Cylinder, public Bankable { size_t getFirstIndex() const override; size_t getLastIndex() const override; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override; - void stashContainer(StashContainerList itemDict); + void stashContainer(const StashContainerList &itemDict); ItemsTierCountList getInventoryItemsId(bool ignoreStoreInbox = false) const; // This function is a override function of base class @@ -2720,7 +2718,7 @@ class Player final : public Creature, public Cylinder, public Bankable { // Function from player class with correct type sizes (uint16_t) std::map &getAllSaleItemIdAndCount(std::map &countMap) const; void getAllItemTypeCountAndSubtype(std::map &countMap) const; - std::shared_ptr getForgeItemFromId(uint16_t itemId, uint8_t tier); + std::shared_ptr getForgeItemFromId(uint16_t itemId, uint8_t tier) const; std::shared_ptr getThing(size_t index) const override; void internalAddThing(std::shared_ptr thing) override; @@ -2924,7 +2922,7 @@ class Player final : public Creature, public Cylinder, public Bankable { TradeState_t tradeState = TRADE_NONE; FightMode_t fightMode = FIGHTMODE_ATTACK; Faction_t faction = FACTION_PLAYER; - QuickLootFilter_t quickLootFilter; + QuickLootFilter_t quickLootFilter {}; PlayerPronoun_t pronoun = PLAYERPRONOUN_THEY; bool chaseMode = false; @@ -3064,13 +3062,13 @@ class Player final : public Creature, public Cylinder, public Bankable { std::array getFinalDamageReduction() const; void calculateDamageReductionFromEquipedItems(std::array &combatReductionMap) const; - void calculateDamageReductionFromItem(std::array &combatReductionMap, std::shared_ptr item) const; - void updateDamageReductionFromItemImbuement(std::array &combatReductionMap, std::shared_ptr item, uint16_t combatTypeIndex) const; - void updateDamageReductionFromItemAbility(std::array &combatReductionMap, std::shared_ptr item, uint16_t combatTypeIndex) const; + void calculateDamageReductionFromItem(std::array &combatReductionMap, const std::shared_ptr &item) const; + void updateDamageReductionFromItemImbuement(std::array &combatReductionMap, const std::shared_ptr &item, uint16_t combatTypeIndex) const; + void updateDamageReductionFromItemAbility(std::array &combatReductionMap, const std::shared_ptr &item, uint16_t combatTypeIndex) const; double_t calculateDamageReduction(double_t currentTotal, int16_t resistance) const; void removeEmptyRewards(); - bool hasOtherRewardContainerOpen(const std::shared_ptr container) const; + bool hasOtherRewardContainerOpen(std::shared_ptr container) const; void checkAndShowBlessingMessage(); diff --git a/src/creatures/players/vip/player_vip.cpp b/src/creatures/players/vip/player_vip.cpp index 95ebe91ad5f..46fe5442a64 100644 --- a/src/creatures/players/vip/player_vip.cpp +++ b/src/creatures/players/vip/player_vip.cpp @@ -38,7 +38,7 @@ uint8_t PlayerVIP::getMaxGroupEntries() const { return 0; } -void PlayerVIP::notifyStatusChange(std::shared_ptr loginPlayer, VipStatus_t status, bool message) const { +void PlayerVIP::notifyStatusChange(const std::shared_ptr &loginPlayer, VipStatus_t status, bool message) const { if (!m_player.client) { return; } @@ -101,7 +101,7 @@ bool PlayerVIP::addInternal(uint32_t vipGuid) { return vipGuids.insert(vipGuid).second; } -bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify, std::vector groupsId) const { +bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify, const std::vector &groupsId) const { const auto it = vipGuids.find(vipGuid); if (it == vipGuids.end()) { return false; // player is not in VIP @@ -125,7 +125,7 @@ bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t } std::shared_ptr PlayerVIP::getGroupByID(uint8_t groupId) const { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr &vipGroup) { return vipGroup->id == groupId; }); @@ -134,7 +134,7 @@ std::shared_ptr PlayerVIP::getGroupByID(uint8_t groupId) const { std::shared_ptr PlayerVIP::getGroupByName(const std::string &name) const { const auto groupName = name.c_str(); - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupName](const std::shared_ptr vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupName](const std::shared_ptr &vipGroup) { return strcmp(groupName, vipGroup->name.c_str()) == 0; }); @@ -157,7 +157,7 @@ void PlayerVIP::addGroupInternal(uint8_t groupId, const std::string &name, bool } void PlayerVIP::removeGroup(uint8_t groupId) { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr &vipGroup) { return vipGroup->id == groupId; }); @@ -229,7 +229,7 @@ uint8_t PlayerVIP::getFreeId() const { return 0; } -const std::vector PlayerVIP::getGroupsIdGuidBelongs(uint32_t guid) { +std::vector PlayerVIP::getGroupsIdGuidBelongs(uint32_t guid) { std::vector guidBelongs; for (const auto &vipGroup : vipGroups) { if (vipGroup->vipGroupGuids.contains(guid)) { @@ -239,7 +239,7 @@ const std::vector PlayerVIP::getGroupsIdGuidBelongs(uint32_t guid) { return guidBelongs; } -void PlayerVIP::addGuidToGroupInternal(uint8_t groupId, uint32_t guid) { +void PlayerVIP::addGuidToGroupInternal(uint8_t groupId, uint32_t guid) const { const auto &group = getGroupByID(groupId); if (group) { group->vipGroupGuids.insert(guid); diff --git a/src/creatures/players/vip/player_vip.hpp b/src/creatures/players/vip/player_vip.hpp index e9aeaf85326..18e661ef78d 100644 --- a/src/creatures/players/vip/player_vip.hpp +++ b/src/creatures/players/vip/player_vip.hpp @@ -15,13 +15,13 @@ class Player; struct VIPGroup { uint8_t id = 0; - std::string name = ""; + std::string name; bool customizable = false; phmap::flat_hash_set vipGroupGuids; VIPGroup() = default; VIPGroup(uint8_t id, const std::string &name, bool customizable) : - id(id), name(std::move(name)), customizable(customizable) { } + id(id), name(name), customizable(customizable) { } }; class PlayerVIP { @@ -41,11 +41,11 @@ class PlayerVIP { status = newStatus; } - void notifyStatusChange(std::shared_ptr loginPlayer, VipStatus_t status, bool message = true) const; + void notifyStatusChange(const std::shared_ptr &loginPlayer, VipStatus_t status, bool message = true) const; bool remove(uint32_t vipGuid); bool add(uint32_t vipGuid, const std::string &vipName, VipStatus_t status); bool addInternal(uint32_t vipGuid); - bool edit(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify, std::vector groupsId) const; + bool edit(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify, const std::vector &groupsId) const; // VIP Group std::shared_ptr getGroupByID(uint8_t groupId) const; @@ -56,10 +56,10 @@ class PlayerVIP { void addGroup(const std::string &name, bool customizable = true); void editGroup(uint8_t groupId, const std::string &newName, bool customizable = true); - void addGuidToGroupInternal(uint8_t groupId, uint32_t guid); + void addGuidToGroupInternal(uint8_t groupId, uint32_t guid) const; uint8_t getFreeId() const; - const std::vector getGroupsIdGuidBelongs(uint32_t guid); + std::vector getGroupsIdGuidBelongs(uint32_t guid); [[nodiscard]] const std::vector> &getGroups() const { return vipGroups; diff --git a/src/creatures/players/vocations/vocation.cpp b/src/creatures/players/vocations/vocation.cpp index 6fec2725164..2a786e36852 100644 --- a/src/creatures/players/vocations/vocation.cpp +++ b/src/creatures/players/vocations/vocation.cpp @@ -35,7 +35,7 @@ bool Vocations::loadFromXml() { continue; } - uint16_t id = pugi::cast(attr.value()); + auto id = pugi::cast(attr.value()); auto res = vocationsMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(std::make_shared(id))); auto voc = res.first->second; @@ -124,7 +124,7 @@ bool Vocations::loadFromXml() { if (strcasecmp(childNode.name(), "skill") == 0) { pugi::xml_attribute skillIdAttribute = childNode.attribute("id"); if (skillIdAttribute) { - uint16_t skill_id = pugi::cast(skillIdAttribute.value()); + auto skill_id = pugi::cast(skillIdAttribute.value()); if (skill_id <= SKILL_LAST) { voc->skillMultipliers[skill_id] = pugi::cast(childNode.attribute("multiplier").value()); } else { @@ -254,7 +254,7 @@ uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) { return it->second; } - uint64_t tries = static_cast(skillBase[skill] * std::pow(static_cast(skillMultipliers[skill]), level - (minSkillLevel + 1))); + auto tries = static_cast(skillBase[skill] * std::pow(static_cast(skillMultipliers[skill]), level - (minSkillLevel + 1))); cacheSkill[skill][level] = tries; return tries; } diff --git a/src/creatures/players/wheel/player_wheel.cpp b/src/creatures/players/wheel/player_wheel.cpp index b78f136312b..6c63158980a 100644 --- a/src/creatures/players/wheel/player_wheel.cpp +++ b/src/creatures/players/wheel/player_wheel.cpp @@ -1301,7 +1301,7 @@ uint8_t PlayerWheel::getOptions(uint32_t ownerId) const { // Check if is in the temple range (we assume the temple is within the range of 10 sqms) if (m_player.getZoneType() == ZONE_PROTECTION) { - for (auto [townid, town] : g_game().map.towns.getTowns()) { + for (const auto &[townid, town] : g_game().map.towns.getTowns()) { if (Position::areInRange<1, 10>(town->getTemplePosition(), m_player.getPosition())) { return 1; } @@ -1669,7 +1669,7 @@ void PlayerWheel::printPlayerWheelMethodsBonusData(const PlayerWheelMethodsBonus continue; } - WheelGemAffinity_t affinity = static_cast(i); + auto affinity = static_cast(i); std::string affinityName(magic_enum::enum_name(affinity)); g_logger().debug(" Affinity: {} count: {}", affinityName, bonusData.unlockedVesselResonances[i]); } @@ -2112,7 +2112,7 @@ bool PlayerWheel::checkBallisticMastery() { uint16_t newHolyBonus = 2; // 2% uint16_t newPhysicalBonus = 2; // 2% - std::shared_ptr item = m_player.getWeapon(); + const auto item = m_player.getWeapon(); if (item && item->getAmmoType() == AMMO_BOLT) { if (getMajorStat(WheelMajor_t::CRITICAL_DMG) != newCritical) { setMajorStat(WheelMajor_t::CRITICAL_DMG, newCritical); @@ -2153,7 +2153,7 @@ bool PlayerWheel::checkCombatMastery() { bool updateClient = false; uint8_t stage = getStage(WheelStage_t::COMBAT_MASTERY); - std::shared_ptr item = m_player.getWeapon(); + const auto item = m_player.getWeapon(); if (item && item->getSlotPosition() & SLOTP_TWO_HAND) { int32_t criticalSkill = 0; if (stage >= 3) { @@ -2236,7 +2236,7 @@ bool PlayerWheel::checkDivineEmpowerment() { return updateClient; } -int32_t PlayerWheel::checkDivineGrenade(std::shared_ptr target) const { +int32_t PlayerWheel::checkDivineGrenade(const std::shared_ptr &target) const { if (!target || target == m_player.getPlayer()) { return 0; } @@ -2272,7 +2272,7 @@ void PlayerWheel::checkGiftOfLife() { sendGiftOfLifeCooldown(); } -int32_t PlayerWheel::checkBlessingGroveHealingByTarget(std::shared_ptr target) const { +int32_t PlayerWheel::checkBlessingGroveHealingByTarget(const std::shared_ptr &target) const { if (!target || target == m_player.getPlayer()) { return 0; } @@ -2301,7 +2301,7 @@ int32_t PlayerWheel::checkBlessingGroveHealingByTarget(std::shared_ptr return healingBonus; } -int32_t PlayerWheel::checkTwinBurstByTarget(std::shared_ptr target) const { +int32_t PlayerWheel::checkTwinBurstByTarget(const std::shared_ptr &target) const { if (!target || target == m_player.getPlayer()) { return 0; } @@ -2322,7 +2322,7 @@ int32_t PlayerWheel::checkTwinBurstByTarget(std::shared_ptr target) co return damageBonus; } -int32_t PlayerWheel::checkExecutionersThrow(std::shared_ptr target) const { +int32_t PlayerWheel::checkExecutionersThrow(const std::shared_ptr &target) const { if (!target || target == m_player.getPlayer()) { return 0; } @@ -2357,7 +2357,7 @@ int32_t PlayerWheel::checkBeamMasteryDamage() const { return damageBoost; } -int32_t PlayerWheel::checkDrainBodyLeech(std::shared_ptr target, skills_t skill) const { +int32_t PlayerWheel::checkDrainBodyLeech(const std::shared_ptr &target, skills_t skill) const { if (!target || !target->getMonster() || target->getWheelOfDestinyDrainBodyDebuff() == 0) { return 0; } @@ -2795,7 +2795,7 @@ bool PlayerWheel::getInstant(WheelInstant_t type) const { return false; } -uint8_t PlayerWheel::getStage(const std::string name) const { +uint8_t PlayerWheel::getStage(const std::string &name) const { if (name == "Battle Instinct") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_INSTINCT); } else if (name == "Battle Healing") { @@ -2919,7 +2919,7 @@ int64_t PlayerWheel::getOnThinkTimer(WheelOnThink_t type) const { return 0; } -bool PlayerWheel::getInstant(const std::string name) const { +bool PlayerWheel::getInstant(const std::string &name) const { if (name == "Battle Instinct") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_INSTINCT); } else if (name == "Battle Healing") { diff --git a/src/creatures/players/wheel/player_wheel.hpp b/src/creatures/players/wheel/player_wheel.hpp index e94f605930c..b0375b6c794 100644 --- a/src/creatures/players/wheel/player_wheel.hpp +++ b/src/creatures/players/wheel/player_wheel.hpp @@ -229,13 +229,13 @@ class PlayerWheel { bool checkBallisticMastery(); bool checkCombatMastery(); bool checkDivineEmpowerment(); - int32_t checkDrainBodyLeech(std::shared_ptr target, skills_t skill) const; + int32_t checkDrainBodyLeech(const std::shared_ptr &target, skills_t skill) const; int32_t checkBeamMasteryDamage() const; int32_t checkBattleHealingAmount() const; - int32_t checkBlessingGroveHealingByTarget(std::shared_ptr target) const; - int32_t checkTwinBurstByTarget(std::shared_ptr target) const; - int32_t checkExecutionersThrow(std::shared_ptr target) const; - int32_t checkDivineGrenade(std::shared_ptr target) const; + int32_t checkBlessingGroveHealingByTarget(const std::shared_ptr &target) const; + int32_t checkTwinBurstByTarget(const std::shared_ptr &target) const; + int32_t checkExecutionersThrow(const std::shared_ptr &target) const; + int32_t checkDivineGrenade(const std::shared_ptr &target) const; int32_t checkAvatarSkill(WheelAvatarSkill_t skill) const; int32_t checkFocusMasteryDamage(); int32_t checkElementSensitiveReduction(CombatType_t type) const; @@ -322,7 +322,7 @@ class PlayerWheel { // Wheel of destiny - Header get: bool getInstant(WheelInstant_t type) const; bool getHealingLinkUpgrade(const std::string &spell) const; - uint8_t getStage(const std::string name) const; + uint8_t getStage(const std::string &name) const; uint8_t getStage(WheelStage_t type) const; WheelSpellGrade_t getSpellUpgrade(const std::string &name) const; int32_t getMajorStat(WheelMajor_t type) const; @@ -330,7 +330,7 @@ class PlayerWheel { int32_t getResistance(CombatType_t type) const; int32_t getMajorStatConditional(const std::string &instant, WheelMajor_t major) const; int64_t getOnThinkTimer(WheelOnThink_t type) const; - bool getInstant(const std::string name) const; + bool getInstant(const std::string &name) const; double getMitigationMultiplier() const; // Wheel of destiny - Specific functions diff --git a/src/creatures/players/wheel/wheel_gems.hpp b/src/creatures/players/wheel/wheel_gems.hpp index 668d8fe05db..030bcc5df5d 100644 --- a/src/creatures/players/wheel/wheel_gems.hpp +++ b/src/creatures/players/wheel/wheel_gems.hpp @@ -219,7 +219,7 @@ class GemModifierRevelationStrategy : public GemModifierStrategy { private: WheelGemAffinity_t m_affinity; - uint16_t m_value; + uint16_t m_value {}; }; class GemModifierSpellBonusStrategy : public GemModifierStrategy { diff --git a/src/database/database.cpp b/src/database/database.cpp index f226587c511..67499f2d4fe 100644 --- a/src/database/database.cpp +++ b/src/database/database.cpp @@ -99,7 +99,7 @@ bool Database::commit() { return true; } -bool Database::isRecoverableError(unsigned int error) const { +bool Database::isRecoverableError(unsigned int error) { return error == CR_SERVER_LOST || error == CR_SERVER_GONE_ERROR || error == CR_CONN_HOST_ERROR || error == 1053 /*ER_SERVER_SHUTDOWN*/ || error == CR_CONNECTION_ERROR; } @@ -223,10 +223,10 @@ std::string DBResult::getString(const std::string &s) const { auto it = listNames.find(s); if (it == listNames.end()) { g_logger().error("Column '{}' does not exist in result set", s); - return std::string(); + return {}; } if (row[it->second] == nullptr) { - return std::string(); + return {}; } return std::string(row[it->second]); } @@ -248,7 +248,7 @@ const char* DBResult::getStream(const std::string &s, unsigned long &size) const return row[it->second]; } -uint8_t DBResult::getU8FromString(const std::string &string, const std::string &function) const { +uint8_t DBResult::getU8FromString(const std::string &string, const std::string &function) { auto result = static_cast(std::atoi(string.c_str())); if (result > std::numeric_limits::max()) { g_logger().error("[{}] Failed to get number value {} for tier table result, on function call: {}", __FUNCTION__, result, function); @@ -258,7 +258,7 @@ uint8_t DBResult::getU8FromString(const std::string &string, const std::string & return result; } -int8_t DBResult::getInt8FromString(const std::string &string, const std::string &function) const { +int8_t DBResult::getInt8FromString(const std::string &string, const std::string &function) { auto result = static_cast(std::atoi(string.c_str())); if (result > std::numeric_limits::max()) { g_logger().error("[{}] Failed to get number value {} for tier table result, on function call: {}", __FUNCTION__, result, function); diff --git a/src/database/database.hpp b/src/database/database.hpp index 2a27c30159b..c7d568b8919 100644 --- a/src/database/database.hpp +++ b/src/database/database.hpp @@ -15,6 +15,7 @@ #ifndef USE_PRECOMPILED_HEADERS #include #include + #include #endif class DBResult; @@ -63,7 +64,7 @@ class Database { bool rollback(); bool commit(); - bool isRecoverableError(unsigned int error) const; + static bool isRecoverableError(unsigned int error); MYSQL* handle = nullptr; std::recursive_mutex databaseLock; @@ -149,8 +150,8 @@ class DBResult { std::string getString(const std::string &s) const; const char* getStream(const std::string &s, unsigned long &size) const; - uint8_t getU8FromString(const std::string &string, const std::string &function) const; - int8_t getInt8FromString(const std::string &string, const std::string &function) const; + static uint8_t getU8FromString(const std::string &string, const std::string &function); + static int8_t getInt8FromString(const std::string &string, const std::string &function); size_t countResults() const; bool hasNext() const; @@ -172,7 +173,7 @@ class DBInsert { public: explicit DBInsert(std::string query); void upsert(const std::vector &columns); - bool addRow(const std::string_view row); + bool addRow(std::string_view row); bool addRow(std::ostringstream &row); bool execute(); @@ -280,10 +281,10 @@ class DBTransaction { class DatabaseException : public std::exception { public: - explicit DatabaseException(const std::string &message) : - message(message) { } + explicit DatabaseException(std::string message) : + message(std::move(message)) { } - virtual const char* what() const throw() { + const char* what() const noexcept override { return message.c_str(); } diff --git a/src/database/databasetasks.cpp b/src/database/databasetasks.cpp index 06cfda93fc0..b4745ef8dd8 100644 --- a/src/database/databasetasks.cpp +++ b/src/database/databasetasks.cpp @@ -22,7 +22,7 @@ DatabaseTasks &DatabaseTasks::getInstance() { return inject(); } -void DatabaseTasks::execute(const std::string &query, std::function callback /* nullptr */) { +void DatabaseTasks::execute(const std::string &query, const std::function &callback /* nullptr */) { threadPool.detach_task([this, query, callback]() { bool success = db.executeQuery(query); if (callback != nullptr) { @@ -31,7 +31,7 @@ void DatabaseTasks::execute(const std::string &query, std::function callback /* nullptr */) { +void DatabaseTasks::store(const std::string &query, const std::function &callback /* nullptr */) { threadPool.detach_task([this, query, callback]() { DBResult_ptr result = db.storeQuery(query); if (callback != nullptr) { diff --git a/src/database/databasetasks.hpp b/src/database/databasetasks.hpp index 6922dfc566f..a9c86583db4 100644 --- a/src/database/databasetasks.hpp +++ b/src/database/databasetasks.hpp @@ -22,8 +22,8 @@ class DatabaseTasks { static DatabaseTasks &getInstance(); - void execute(const std::string &query, std::function callback = nullptr); - void store(const std::string &query, std::function callback = nullptr); + void execute(const std::string &query, const std::function &callback = nullptr); + void store(const std::string &query, const std::function &callback = nullptr); private: Database &db; diff --git a/src/game/bank/bank.cpp b/src/game/bank/bank.cpp index d9a056396ce..6798250cced 100644 --- a/src/game/bank/bank.cpp +++ b/src/game/bank/bank.cpp @@ -16,7 +16,7 @@ #include "game/scheduling/save_manager.hpp" #include "lib/metrics/metrics.hpp" -Bank::Bank(const std::shared_ptr bankable) : +Bank::Bank(const std::shared_ptr &bankable) : m_bankable(bankable) { } @@ -25,7 +25,7 @@ Bank::~Bank() { if (bankable == nullptr || bankable->isOnline()) { return; } - std::shared_ptr player = bankable->getPlayer(); + const auto player = bankable->getPlayer(); if (player && !player->isOnline()) { g_saveManager().savePlayer(player); @@ -53,7 +53,7 @@ bool Bank::debit(uint64_t amount) { bool Bank::balance(uint64_t amount) const { auto bankable = getBankable(); if (!bankable) { - return 0; + return false; } bankable->setBankBalance(amount); return true; @@ -80,7 +80,7 @@ const std::set deniedNames = { "paladinsample" }; -bool Bank::transferTo(const std::shared_ptr destination, uint64_t amount) { +bool Bank::transferTo(const std::shared_ptr &destination, uint64_t amount) { if (!destination) { g_logger().error("Bank::transferTo: destination is nullptr"); return false; @@ -129,7 +129,7 @@ bool Bank::transferTo(const std::shared_ptr destination, uint64_t amount) return true; } -bool Bank::withdraw(std::shared_ptr player, uint64_t amount) { +bool Bank::withdraw(const std::shared_ptr &player, uint64_t amount) { if (!debit(amount)) { return false; } @@ -138,7 +138,7 @@ bool Bank::withdraw(std::shared_ptr player, uint64_t amount) { return true; } -bool Bank::deposit(const std::shared_ptr destination) { +bool Bank::deposit(const std::shared_ptr &destination) { auto bankable = getBankable(); if (!bankable) { return false; @@ -150,7 +150,7 @@ bool Bank::deposit(const std::shared_ptr destination) { return deposit(destination, amount); } -bool Bank::deposit(const std::shared_ptr destination, uint64_t amount) { +bool Bank::deposit(const std::shared_ptr &destination, uint64_t amount) { if (!destination) { return false; } diff --git a/src/game/bank/bank.hpp b/src/game/bank/bank.hpp index 9e65a55aeb9..7149d8ab0d0 100644 --- a/src/game/bank/bank.hpp +++ b/src/game/bank/bank.hpp @@ -29,7 +29,7 @@ class Bankable { class Bank : public SharedObject { public: - explicit Bank(const std::shared_ptr bankable); + explicit Bank(const std::shared_ptr &bankable); ~Bank() override; // Deleted copy constructor and assignment operator. @@ -42,10 +42,10 @@ class Bank : public SharedObject { bool balance(uint64_t amount) const; uint64_t balance(); bool hasBalance(uint64_t amount); - bool transferTo(const std::shared_ptr destination, uint64_t amount); - bool withdraw(std::shared_ptr player, uint64_t amount); - bool deposit(const std::shared_ptr destination); - bool deposit(const std::shared_ptr destination, uint64_t amount); + bool transferTo(const std::shared_ptr &destination, uint64_t amount); + bool withdraw(const std::shared_ptr &player, uint64_t amount); + bool deposit(const std::shared_ptr &destination); + bool deposit(const std::shared_ptr &destination, uint64_t amount); private: std::shared_ptr getBankable() const { diff --git a/src/game/game.cpp b/src/game/game.cpp index df1b401bf48..7b70cbc1b34 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -57,8 +57,10 @@ #include +#include + namespace InternalGame { - void sendBlockEffect(BlockType_t blockType, CombatType_t combatType, const Position &targetPos, std::shared_ptr source) { + void sendBlockEffect(BlockType_t blockType, CombatType_t combatType, const Position &targetPos, const std::shared_ptr &source) { if (blockType == BLOCK_DEFENSE) { g_game().addMagicEffect(targetPos, CONST_ME_POFF); } else if (blockType == BLOCK_ARMOR) { @@ -96,11 +98,11 @@ namespace InternalGame { } if (blockType != BLOCK_NONE) { - g_game().sendSingleSoundEffect(targetPos, SoundEffect_t::NO_DAMAGE, std::move(source)); + g_game().sendSingleSoundEffect(targetPos, SoundEffect_t::NO_DAMAGE, source); } } - bool playerCanUseItemOnHouseTile(std::shared_ptr player, std::shared_ptr item) { + bool playerCanUseItemOnHouseTile(const std::shared_ptr &player, const std::shared_ptr &item) { if (!player || !item) { return false; } @@ -137,7 +139,7 @@ namespace InternalGame { return true; } - bool playerCanUseItemWithOnHouseTile(std::shared_ptr player, std::shared_ptr item, const Position &toPos, int toStackPos, int toItemId) { + bool playerCanUseItemWithOnHouseTile(const std::shared_ptr &player, const std::shared_ptr &item, const Position &toPos, int toStackPos, int toItemId) { if (!player || !item) { return false; } @@ -165,7 +167,7 @@ namespace InternalGame { } template - T getCustomAttributeValue(std::shared_ptr item, const std::string &attributeName) { + T getCustomAttributeValue(const auto item, const std::string &attributeName) { static_assert(std::is_integral::value, "T must be an integral type"); auto attribute = item->getCustomAttribute(attributeName); @@ -420,8 +422,8 @@ void Game::loadBoostedCreature() { return; } - const uint16_t date = result->getNumber("date"); - const time_t now = time(0); + const auto date = result->getNumber("date"); + const time_t now = time(nullptr); tm* ltm = localtime(&now); if (date == ltm->tm_mday) { @@ -429,7 +431,7 @@ void Game::loadBoostedCreature() { return; } - const uint16_t oldRace = result->getNumber("raceid"); + const auto oldRace = result->getNumber("raceid"); const auto monsterlist = getBestiaryList(); struct MonsterRace { @@ -494,7 +496,7 @@ void Game::start(ServiceManager* manager) { serviceManager = manager; - time_t now = time(0); + time_t now = time(nullptr); const tm* tms = localtime(&now); int minutes = tms->tm_min; lightHour = (minutes * LIGHT_DAY_LENGTH) / 60; @@ -639,7 +641,7 @@ void Game::loadItemsPrice() { } // Update active buy offers (market_offers) - auto offers = IOMarket::getInstance().getActiveOffers(MARKETACTION_BUY); + auto offers = IOMarket::getActiveOffers(MARKETACTION_BUY); for (const auto &offer : offers) { itemsPriceMap[offer.itemId][offer.tier] = std::max(itemsPriceMap[offer.itemId][offer.tier], offer.price); } @@ -717,7 +719,7 @@ std::shared_ptr Game::internalGetCylinder(std::shared_ptr play return player; } -std::shared_ptr Game::internalGetThing(std::shared_ptr player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type) { +std::shared_ptr Game::internalGetThing(const std::shared_ptr &player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type) { if (pos.x != 0xFFFF) { std::shared_ptr tile = map.getTile(pos); if (!tile) { @@ -731,7 +733,7 @@ std::shared_ptr Game::internalGetThing(std::shared_ptr player, co } case STACKPOS_MOVE: { - std::shared_ptr item = tile->getTopDownItem(); + const auto item = tile->getTopDownItem(); if (item && item->isMovable()) { thing = item; } else { @@ -852,11 +854,11 @@ std::shared_ptr Game::internalGetThing(std::shared_ptr player, co } // inventory - Slots_t slot = static_cast(pos.y); + auto slot = static_cast(pos.y); return player->getInventoryItem(slot); } -void Game::internalGetPosition(std::shared_ptr item, Position &pos, uint8_t &stackpos) { +void Game::internalGetPosition(const std::shared_ptr &item, Position &pos, uint8_t &stackpos) { pos.x = 0; pos.y = 0; pos.z = 0; @@ -864,7 +866,7 @@ void Game::internalGetPosition(std::shared_ptr item, Position &pos, uint8_ std::shared_ptr topParent = item->getTopParent(); if (topParent) { - if (std::shared_ptr player = std::dynamic_pointer_cast(topParent)) { + if (const auto player = std::dynamic_pointer_cast(topParent)) { pos.x = 0xFFFF; std::shared_ptr container = std::dynamic_pointer_cast(item->getParent()); @@ -1063,7 +1065,7 @@ ReturnValue Game::getPlayerByNameWildcard(const std::string &s, std::shared_ptr< return RETURNVALUE_NOERROR; } -std::vector> Game::getPlayersByAccount(std::shared_ptr acc, bool allowOffline /* = false */) { +std::vector> Game::getPlayersByAccount(const std::shared_ptr &acc, bool allowOffline /* = false */) { auto [accountPlayers, error] = acc->getAccountPlayers(); if (error != enumToValue(AccountErrors_t::Ok)) { return {}; @@ -1078,7 +1080,7 @@ std::vector> Game::getPlayersByAccount(std::shared_ptr creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/, bool creatureCheck /*= false*/) { +bool Game::internalPlaceCreature(const std::shared_ptr &creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/, bool creatureCheck /*= false*/) { if (creature->getParent() != nullptr) { return false; } @@ -1107,7 +1109,7 @@ bool Game::internalPlaceCreature(std::shared_ptr creature, const Posit return true; } -bool Game::placeCreature(std::shared_ptr creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/) { +bool Game::placeCreature(const std::shared_ptr &creature, const Position &pos, bool extendedPos /*=false*/, bool forced /*= false*/) { metrics::method_latency measure(__METHOD_NAME__); if (!internalPlaceCreature(creature, pos, extendedPos, forced)) { return false; @@ -1134,7 +1136,7 @@ bool Game::placeCreature(std::shared_ptr creature, const Position &pos return true; } -bool Game::removeCreature(std::shared_ptr creature, bool isLogout /* = true*/) { +bool Game::removeCreature(const std::shared_ptr &creature, bool isLogout /* = true*/) { metrics::method_latency measure(__METHOD_NAME__); if (!creature || creature->isRemoved()) { return false; @@ -1213,7 +1215,7 @@ void Game::executeDeath(uint32_t creatureId) { void Game::playerTeleport(uint32_t playerId, const Position &newPosition) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->hasFlag(PlayerFlags_t::CanMapClickTeleport)) { return; } @@ -1224,7 +1226,7 @@ void Game::playerTeleport(uint32_t playerId, const Position &newPosition) { } } -void Game::playerInspectItem(std::shared_ptr player, const Position &pos) { +void Game::playerInspectItem(const std::shared_ptr &player, const Position &pos) { metrics::method_latency measure(__METHOD_NAME__); std::shared_ptr thing = internalGetThing(player, pos, 0, 0, STACKPOS_TOPDOWN_ITEM); if (!thing) { @@ -1232,7 +1234,7 @@ void Game::playerInspectItem(std::shared_ptr player, const Position &pos return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -1241,7 +1243,7 @@ void Game::playerInspectItem(std::shared_ptr player, const Position &pos player->sendItemInspection(item->getID(), static_cast(item->getItemCount()), item, false); } -void Game::playerInspectItem(std::shared_ptr player, uint16_t itemId, uint8_t itemCount, bool cyclopedia) { +void Game::playerInspectItem(const std::shared_ptr &player, uint16_t itemId, uint8_t itemCount, bool cyclopedia) { metrics::method_latency measure(__METHOD_NAME__); player->sendItemInspection(itemId, itemCount, nullptr, cyclopedia); } @@ -1297,7 +1299,7 @@ FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string &file) { void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -1361,7 +1363,7 @@ void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t } void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position &movingCreatureOrigPos, const Position &toPos) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -1380,7 +1382,7 @@ void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, playerMoveCreature(player, movingCreature, movingCreatureOrigPos, toTile); } -void Game::playerMoveCreature(std::shared_ptr player, std::shared_ptr movingCreature, const Position &movingCreatureOrigPos, std::shared_ptr toTile) { +void Game::playerMoveCreature(const std::shared_ptr &player, const std::shared_ptr &movingCreature, const Position &movingCreatureOrigPos, const std::shared_ptr &toTile) { metrics::method_latency measure(__METHOD_NAME__); if (!player->canDoAction()) { const auto &task = createPlayerTask( @@ -1471,7 +1473,7 @@ void Game::playerMoveCreature(std::shared_ptr player, std::shared_ptrsetLastPosition(player->getPosition()); } -ReturnValue Game::internalMoveCreature(std::shared_ptr creature, Direction direction, uint32_t flags /*= 0*/) { +ReturnValue Game::internalMoveCreature(const std::shared_ptr &creature, Direction direction, uint32_t flags /*= 0*/) { if (!creature) { return RETURNVALUE_NOTPOSSIBLE; } @@ -1479,7 +1481,7 @@ ReturnValue Game::internalMoveCreature(std::shared_ptr creature, Direc creature->setLastPosition(creature->getPosition()); const Position ¤tPos = creature->getPosition(); Position destPos = getNextPosition(direction, currentPos); - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); bool diagonalMovement = (direction & DIRECTION_DIAGONAL_MASK) != 0; if (player && !diagonalMovement) { @@ -1586,14 +1588,14 @@ ReturnValue Game::internalMoveCreature(const std::shared_ptr &creature } void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } playerMoveItem(player, fromPos, itemId, fromStackPos, toPos, count, nullptr, nullptr); } -void Game::playerMoveItem(std::shared_ptr player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, std::shared_ptr item, std::shared_ptr toCylinder) { +void Game::playerMoveItem(const std::shared_ptr &player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, std::shared_ptr item, std::shared_ptr toCylinder) { if (!player->canDoAction()) { uint32_t delay = player->getNextActionTime(); std::shared_ptr task = createPlayerTask( @@ -1823,11 +1825,11 @@ void Game::playerMoveItem(std::shared_ptr player, const Position &fromPo g_callbacks().executeCallback(EventCallback_t::playerOnItemMoved, &EventCallback::playerOnItemMoved, player, item, count, fromPos, toPos, fromCylinder, toCylinder); } -bool Game::isTryingToStow(const Position &toPos, std::shared_ptr toCylinder) const { +bool Game::isTryingToStow(const Position &toPos, const std::shared_ptr &toCylinder) const { return toCylinder->getContainer() && toCylinder->getItem()->getID() == ITEM_LOCKER && toPos.getZ() == ITEM_SUPPLY_STASH_INDEX; } -ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::shared_ptr fromCylinder, std::shared_ptr toCylinder, std::shared_ptr item, Position toPos) { +ReturnValue Game::checkMoveItemToCylinder(const std::shared_ptr &player, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder, const std::shared_ptr &item, Position toPos) { if (!player || !toCylinder || !item) { return RETURNVALUE_NOTPOSSIBLE; } @@ -1931,7 +1933,7 @@ ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::s return RETURNVALUE_NOERROR; } -ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std::shared_ptr toCylinder, int32_t index, std::shared_ptr item, uint32_t count, std::shared_ptr* movedItem, uint32_t flags /*= 0*/, std::shared_ptr actor /*=nullptr*/, std::shared_ptr tradeItem /* = nullptr*/, bool checkTile /* = true*/) { +ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std::shared_ptr toCylinder, int32_t index, const std::shared_ptr &item, uint32_t count, std::shared_ptr* movedItem, uint32_t flags /*= 0*/, const std::shared_ptr &actor /*=nullptr*/, const std::shared_ptr &tradeItem /* = nullptr*/, bool checkTile /* = true*/) { metrics::method_latency measure(__METHOD_NAME__); if (fromCylinder == nullptr) { g_logger().error("[{}] fromCylinder is nullptr", __FUNCTION__); @@ -2163,10 +2165,10 @@ ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std:: return ret; } - if (std::shared_ptr player = actor->getPlayer()) { + if (const auto &player_m = actor->getPlayer()) { // Refresh depot search window if necessary - if (player->isDepotSearchOpenOnItem(item->getID()) && ((fromCylinder->getItem() && fromCylinder->getItem()->isInsideDepot(true)) || (toCylinder->getItem() && toCylinder->getItem()->isInsideDepot(true)))) { - player->requestDepotSearchItem(item->getID(), item->getTier()); + if (player_m->isDepotSearchOpenOnItem(item->getID()) && ((fromCylinder->getItem() && fromCylinder->getItem()->isInsideDepot(true)) || (toCylinder->getItem() && toCylinder->getItem()->isInsideDepot(true)))) { + player_m->requestDepotSearchItem(item->getID(), item->getTier()); } const ItemType &it = Item::items[fromCylinder->getItem()->getID()]; @@ -2175,8 +2177,8 @@ ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std:: } // Looting analyser - if (it.isCorpse && toContainer->getTopParent() == player && item->getIsLootTrackeable()) { - player->sendLootStats(item, static_cast(item->getItemCount())); + if (it.isCorpse && toContainer->getTopParent() == player_m && item->getIsLootTrackeable()) { + player_m->sendLootStats(item, static_cast(item->getItemCount())); } } } @@ -2184,12 +2186,12 @@ ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std:: return ret; } -ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, std::shared_ptr item, int32_t index /*= INDEX_WHEREEVER*/, uint32_t flags /* = 0*/, bool test /* = false*/) { +ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, const std::shared_ptr &item, int32_t index /*= INDEX_WHEREEVER*/, uint32_t flags /* = 0*/, bool test /* = false*/) { uint32_t remainderCount = 0; - return internalAddItem(std::move(toCylinder), std::move(item), index, flags, test, remainderCount); + return internalAddItem(std::move(toCylinder), item, index, flags, test, remainderCount); } -ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, std::shared_ptr item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount) { +ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, const std::shared_ptr &item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount) { metrics::method_latency measure(__METHOD_NAME__); if (toCylinder == nullptr) { g_logger().error("[{}] fromCylinder is nullptr", __FUNCTION__); @@ -2276,7 +2278,8 @@ ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, std::sha return RETURNVALUE_NOERROR; } -ReturnValue Game::internalRemoveItem(std::shared_ptr item, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/, bool force /*= false*/) { +ReturnValue Game::internalRemoveItem(const std::shared_ptr &items, int32_t count /*= -1*/, bool test /*= false*/, uint32_t flags /*= 0*/, bool force /*= false*/) { + auto item = items; metrics::method_latency measure(__METHOD_NAME__); if (item == nullptr) { g_logger().debug("{} - Item is nullptr", __FUNCTION__); @@ -2287,7 +2290,7 @@ ReturnValue Game::internalRemoveItem(std::shared_ptr item, int32_t count / g_logger().debug("{} - Cylinder is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr fromTile = cylinder->getTile(); + auto fromTile = cylinder->getTile(); if (fromTile) { if (fromTile && browseFields.contains(fromTile) && browseFields[fromTile].lock() == cylinder) { cylinder = fromTile; @@ -2327,7 +2330,7 @@ ReturnValue Game::internalRemoveItem(std::shared_ptr item, int32_t count / cylinder->postRemoveNotification(item, nullptr, index); } - std::shared_ptr quiver = cylinder->getItem(); + auto quiver = cylinder->getItem(); if (quiver && quiver->isQuiver() && quiver->getHoldingPlayer() && quiver->getHoldingPlayer()->getThing(CONST_SLOT_RIGHT) == quiver) { @@ -2470,7 +2473,7 @@ std::tuple Game::createItem(const std::shared_p return createItemBatch(toCylinder, { std::make_tuple(itemId, count, subType) }, flags, dropOnMap, autoContainerId); } -ReturnValue Game::internalPlayerAddItem(std::shared_ptr player, std::shared_ptr item, bool dropOnMap /*= true*/, Slots_t slot /*= CONST_SLOT_WHEREEVER*/) { +ReturnValue Game::internalPlayerAddItem(const std::shared_ptr &player, const std::shared_ptr &item, bool dropOnMap /*= true*/, Slots_t slot /*= CONST_SLOT_WHEREEVER*/) { metrics::method_latency measure(__METHOD_NAME__); uint32_t remainderCount = 0; ReturnValue ret; @@ -2502,7 +2505,7 @@ ReturnValue Game::internalPlayerAddItem(std::shared_ptr player, std::sha return ret; } -std::shared_ptr Game::findItemOfType(std::shared_ptr cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) const { +std::shared_ptr Game::findItemOfType(const std::shared_ptr &cylinder, uint16_t itemId, bool depthSearch /*= true*/, int32_t subType /*= -1*/) const { metrics::method_latency measure(__METHOD_NAME__); if (cylinder == nullptr) { g_logger().error("[{}] Cylinder is nullptr", __FUNCTION__); @@ -2516,7 +2519,7 @@ std::shared_ptr Game::findItemOfType(std::shared_ptr cylinder, u continue; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { continue; } @@ -2536,7 +2539,7 @@ std::shared_ptr Game::findItemOfType(std::shared_ptr cylinder, u size_t i = 0; while (i < containers.size()) { std::shared_ptr container = containers[i++]; - for (std::shared_ptr item : container->getItemList()) { + for (const auto item : container->getItemList()) { if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) { return item; } @@ -2550,7 +2553,7 @@ std::shared_ptr Game::findItemOfType(std::shared_ptr cylinder, u return nullptr; } -bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint32_t flags /*= 0*/, bool useBalance /*= false*/) { +bool Game::removeMoney(const std::shared_ptr &cylinder, uint64_t money, uint32_t flags /*= 0*/, bool useBalance /*= false*/) { if (cylinder == nullptr) { g_logger().error("[{}] cylinder is nullptr", __FUNCTION__); return false; @@ -2566,7 +2569,7 @@ bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint3 if (!thing) { continue; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { continue; } @@ -2598,7 +2601,7 @@ bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint3 } } - std::shared_ptr player = useBalance ? std::dynamic_pointer_cast(cylinder) : nullptr; + const auto player = useBalance ? std::dynamic_pointer_cast(cylinder) : nullptr; uint64_t balance = 0; if (useBalance && player) { balance = player->getBankBalance(); @@ -2609,7 +2612,7 @@ bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint3 } for (const auto &moneyEntry : moneyMap) { - std::shared_ptr item = moneyEntry.second; + const auto item = moneyEntry.second; if (moneyEntry.first < money) { internalRemoveItem(item); money -= moneyEntry.first; @@ -2632,7 +2635,7 @@ bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint3 return true; } -void Game::addMoney(std::shared_ptr cylinder, uint64_t money, uint32_t flags /*= 0*/) { +void Game::addMoney(const std::shared_ptr &cylinder, uint64_t money, uint32_t flags /*= 0*/) { if (cylinder == nullptr) { g_logger().error("[{}] cylinder is nullptr", __FUNCTION__); return; @@ -2842,13 +2845,13 @@ ReturnValue Game::internalTeleport(const std::shared_ptr &thing, const Po map.moveCreature(creature, toTile, !pushMove); return RETURNVALUE_NOERROR; - } else if (std::shared_ptr item = thing->getItem()) { + } else if (const auto item = thing->getItem()) { return internalMoveItem(item->getParent(), toTile, INDEX_WHEREEVER, item, item->getItemCount(), nullptr, flags); } return RETURNVALUE_NOTPOSSIBLE; } -void Game::playerQuickLootCorpse(std::shared_ptr player, std::shared_ptr corpse, const Position &position) { +void Game::playerQuickLootCorpse(const std::shared_ptr &player, const std::shared_ptr &corpse, const Position &position) { if (!player || !corpse) { return; } @@ -2860,7 +2863,7 @@ void Game::playerQuickLootCorpse(std::shared_ptr player, std::shared_ptr bool missedAnyItem = false; for (ContainerIterator it = corpse->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; bool listed = player->isQuickLootListedItem(item); if ((listed && ignoreListItems) || (!listed && !ignoreListItems)) { if (item->getWorth() != 0) { @@ -2987,7 +2990,7 @@ void Game::playerQuickLootCorpse(std::shared_ptr player, std::shared_ptr player->lastQuickLootNotification = OTSYS_TIME(); } -std::shared_ptr Game::findManagedContainer(std::shared_ptr player, bool &fallbackConsumed, ObjectCategory_t category, bool isLootContainer) { +std::shared_ptr Game::findManagedContainer(const std::shared_ptr &player, bool &fallbackConsumed, ObjectCategory_t category, bool isLootContainer) { auto lootContainer = player->getManagedContainer(category, isLootContainer); if (!lootContainer && player->quickLootFallbackToMainContainer && !fallbackConsumed) { auto fallbackItem = player->getInventoryItem(CONST_SLOT_BACKPACK); @@ -3028,7 +3031,7 @@ std::shared_ptr Game::findNextAvailableContainer(ContainerIterator &c return nullptr; } -bool Game::handleFallbackLogic(std::shared_ptr player, std::shared_ptr &lootContainer, ContainerIterator &containerIterator, const bool &fallbackConsumed) { +bool Game::handleFallbackLogic(const std::shared_ptr &player, std::shared_ptr &lootContainer, ContainerIterator &containerIterator, const bool &fallbackConsumed) { if (fallbackConsumed || !player->quickLootFallbackToMainContainer) { return false; } @@ -3044,7 +3047,7 @@ bool Game::handleFallbackLogic(std::shared_ptr player, std::shared_ptr item, std::shared_ptr lootContainer, uint32_t &remainderCount, std::shared_ptr player) { +ReturnValue Game::processMoveOrAddItemToLootContainer(const std::shared_ptr &item, const std::shared_ptr &lootContainer, uint32_t &remainderCount, const std::shared_ptr &player) { std::shared_ptr moveItem = nullptr; ReturnValue ret; if (item->getParent()) { @@ -3058,7 +3061,7 @@ ReturnValue Game::processMoveOrAddItemToLootContainer(std::shared_ptr item return ret; } -ReturnValue Game::processLootItems(std::shared_ptr player, std::shared_ptr lootContainer, std::shared_ptr item, bool &fallbackConsumed) { +ReturnValue Game::processLootItems(const std::shared_ptr &player, std::shared_ptr lootContainer, const std::shared_ptr &item, bool &fallbackConsumed) { std::shared_ptr lastSubContainer = nullptr; uint32_t remainderCount = item->getItemCount(); ContainerIterator containerIterator = lootContainer->iterator(); @@ -3080,7 +3083,7 @@ ReturnValue Game::processLootItems(std::shared_ptr player, std::shared_p return ret; } -ReturnValue Game::internalCollectManagedItems(std::shared_ptr player, std::shared_ptr item, ObjectCategory_t category /* = OBJECTCATEGORY_DEFAULT*/, bool isLootContainer /* = true*/) { +ReturnValue Game::internalCollectManagedItems(const std::shared_ptr &player, const std::shared_ptr &item, ObjectCategory_t category /* = OBJECTCATEGORY_DEFAULT*/, bool isLootContainer /* = true*/) { if (!player || !item) { return RETURNVALUE_NOTPOSSIBLE; } @@ -3118,7 +3121,7 @@ ReturnValue Game::internalCollectManagedItems(std::shared_ptr player, st return processLootItems(player, lootContainer, item, fallbackConsumed); } -ReturnValue Game::collectRewardChestItems(std::shared_ptr player, uint32_t maxMoveItems /* = 0*/) { +ReturnValue Game::collectRewardChestItems(const std::shared_ptr &player, uint32_t maxMoveItems /* = 0*/) { // Check if have item on player reward chest std::shared_ptr rewardChest = player->getRewardChest(); if (rewardChest->empty()) { @@ -3161,7 +3164,7 @@ ReturnValue Game::collectRewardChestItems(std::shared_ptr player, uint32 return RETURNVALUE_NOERROR; } -ObjectCategory_t Game::getObjectCategory(std::shared_ptr item) { +ObjectCategory_t Game::getObjectCategory(const std::shared_ptr &item) { ObjectCategory_t category = OBJECTCATEGORY_DEFAULT; if (!item) { return OBJECTCATEGORY_NONE; @@ -3264,7 +3267,7 @@ uint64_t Game::getItemMarketPrice(const std::map &itemMap, b return total; } -std::shared_ptr searchForItem(std::shared_ptr container, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { +std::shared_ptr searchForItem(const std::shared_ptr &container, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if ((*it)->getID() == itemId && (!hasTier || (*it)->getTier() == tier)) { return *it; @@ -3303,7 +3306,7 @@ Slots_t getSlotType(const ItemType &it) { // Implementation of player invoked events void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3316,7 +3319,7 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = return; } - std::shared_ptr item = player->getInventoryItem(CONST_SLOT_BACKPACK); + const auto item = player->getInventoryItem(CONST_SLOT_BACKPACK); if (!item) { return; } @@ -3379,7 +3382,7 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = } void Game::playerMove(uint32_t playerId, Direction direction) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3392,7 +3395,7 @@ void Game::playerMove(uint32_t playerId, Direction direction) { } void Game::forcePlayerMove(uint32_t playerId, Direction direction) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3404,7 +3407,7 @@ void Game::forcePlayerMove(uint32_t playerId, Direction direction) { player->startAutoWalk(std::vector { direction }, true); } -bool Game::playerBroadcastMessage(std::shared_ptr player, const std::string &text) const { +bool Game::playerBroadcastMessage(const std::shared_ptr &player, const std::string &text) const { if (!player->hasFlag(PlayerFlags_t::CanBroadcast)) { return false; } @@ -3419,7 +3422,7 @@ bool Game::playerBroadcastMessage(std::shared_ptr player, const std::str } void Game::playerCreatePrivateChannel(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isPremium()) { return; } @@ -3433,7 +3436,7 @@ void Game::playerCreatePrivateChannel(uint32_t playerId) { } void Game::playerChannelInvite(uint32_t playerId, const std::string &name) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3456,7 +3459,7 @@ void Game::playerChannelInvite(uint32_t playerId, const std::string &name) { } void Game::playerChannelExclude(uint32_t playerId, const std::string &name) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3479,7 +3482,7 @@ void Game::playerChannelExclude(uint32_t playerId, const std::string &name) { } void Game::playerRequestChannels(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3488,7 +3491,7 @@ void Game::playerRequestChannels(uint32_t playerId) { } void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3510,7 +3513,7 @@ void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { } void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3519,7 +3522,7 @@ void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { } void Game::playerOpenPrivateChannel(uint32_t playerId, std::string &receiver) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3549,7 +3552,7 @@ void Game::playerCloseNpcChannel(uint32_t playerId) { } void Game::playerReceivePing(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3558,7 +3561,7 @@ void Game::playerReceivePing(uint32_t playerId) { } void Game::playerReceivePingBack(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3567,7 +3570,7 @@ void Game::playerReceivePingBack(uint32_t playerId) { } void Game::playerAutoWalk(uint32_t playerId, const std::vector &listDir) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3578,7 +3581,7 @@ void Game::playerAutoWalk(uint32_t playerId, const std::vector &listD } void Game::forcePlayerAutoWalk(uint32_t playerId, const std::vector &listDir) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3595,7 +3598,7 @@ void Game::forcePlayerAutoWalk(uint32_t playerId, const std::vector & } void Game::playerStopAutoWalk(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3605,7 +3608,7 @@ void Game::playerStopAutoWalk(uint32_t playerId) { void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint16_t fromItemId, const Position &toPos, uint8_t toStackPos, uint16_t toItemId) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3621,7 +3624,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t f return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || !item->isMultiUse() || item->getID() != fromItemId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; @@ -3743,7 +3746,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t f void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint8_t index, uint16_t itemId) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3759,7 +3762,7 @@ void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPo return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->isMultiUse() || item->getID() != itemId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; @@ -3846,7 +3849,7 @@ void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPo void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -3874,7 +3877,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uin return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || !item->isMultiUse() || item->getID() != itemId) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; @@ -4000,7 +4003,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uin } void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4010,7 +4013,7 @@ void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { } void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4062,7 +4065,7 @@ void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { } void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) { - std::shared_ptr player = getPlayerByGUID(playerId); + const auto player = getPlayerByGUID(playerId); if (!player) { return; } @@ -4131,7 +4134,7 @@ void Game::playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stac } void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -4141,7 +4144,7 @@ void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != itemId || !item->isPodium() || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -4187,7 +4190,7 @@ void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, } void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -4197,7 +4200,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Pos return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != itemId || !item->isPodium() || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -4317,7 +4320,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Pos } void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4411,7 +4414,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st addMagicEffect(pos, CONST_ME_POFF); } -std::shared_ptr Game::wrapItem(std::shared_ptr item, std::shared_ptr house) { +std::shared_ptr Game::wrapItem(const std::shared_ptr &item, const std::shared_ptr &house) { uint16_t hiddenCharges = 0; uint16_t amount = item->getItemCount(); if (isCaskItem(item->getID())) { @@ -4436,7 +4439,7 @@ std::shared_ptr Game::wrapItem(std::shared_ptr item, std::shared_ptr return newItem; } -void Game::unwrapItem(std::shared_ptr item, uint16_t unWrapId, std::shared_ptr house, std::shared_ptr player) { +void Game::unwrapItem(const std::shared_ptr &item, uint16_t unWrapId, const std::shared_ptr &house, const std::shared_ptr &player) { if (item->hasOwner() && !item->isOwner(player)) { player->sendCancelMessage(RETURNVALUE_ITEMISNOTYOURS); return; @@ -4466,7 +4469,7 @@ void Game::unwrapItem(std::shared_ptr item, uint16_t unWrapId, std::shared } void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string &text) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4530,7 +4533,7 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: } void Game::playerBrowseField(uint32_t playerId, const Position &pos) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4590,7 +4593,7 @@ void Game::playerBrowseField(uint32_t playerId, const Position &pos) { } void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4605,7 +4608,7 @@ void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemI return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != itemId || item->getItemCount() < count || item->isStoreItem()) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -4631,7 +4634,7 @@ void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemI } void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t count, uint8_t) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4706,7 +4709,7 @@ void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t coun } void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index, uint8_t containerCategory) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4731,7 +4734,7 @@ void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_ } void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string &text) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4748,7 +4751,7 @@ void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t w } void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t stackPos, uint32_t tradePlayerId, uint16_t itemId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -4822,7 +4825,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t st std::shared_ptr tradeItemContainer = tradeItem->getContainer(); if (tradeItemContainer) { for (const auto &it : tradeItems) { - std::shared_ptr item = it.first; + const auto item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_TRADE, "This item is already being traded."); return; @@ -4841,7 +4844,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t st } } else { for (const auto &it : tradeItems) { - std::shared_ptr item = it.first; + const auto item = it.first; if (tradeItem == item) { player->sendTextMessage(MESSAGE_TRADE, "This item is already being traded."); return; @@ -4886,7 +4889,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t st internalStartTrade(player, tradePartner, tradeItem); } -bool Game::internalStartTrade(std::shared_ptr player, std::shared_ptr tradePartner, std::shared_ptr tradeItem) { +bool Game::internalStartTrade(const std::shared_ptr &player, const std::shared_ptr &tradePartner, const std::shared_ptr &tradeItem) { if (player->tradeState != TRADE_NONE && !(player->tradeState == TRADE_ACKNOWLEDGE && player->tradePartner == tradePartner)) { player->sendCancelMessage(RETURNVALUE_YOUAREALREADYTRADING); return false; @@ -4922,7 +4925,7 @@ bool Game::internalStartTrade(std::shared_ptr player, std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5023,7 +5026,7 @@ void Game::playerAcceptTrade(uint32_t playerId) { } } -std::string Game::getTradeErrorDescription(ReturnValue ret, std::shared_ptr item) { +std::string Game::getTradeErrorDescription(ReturnValue ret, const std::shared_ptr &item) { if (item) { if (ret == RETURNVALUE_NOTENOUGHCAPACITY) { std::ostringstream ss; @@ -5055,7 +5058,7 @@ std::string Game::getTradeErrorDescription(ReturnValue ret, std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5114,7 +5117,7 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t } void Game::playerCloseTrade(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5122,7 +5125,7 @@ void Game::playerCloseTrade(uint32_t playerId) { internalCloseTrade(player); } -void Game::internalCloseTrade(std::shared_ptr player) { +void Game::internalCloseTrade(const std::shared_ptr &player) { std::shared_ptr tradePartner = player->tradePartner; if ((tradePartner && tradePartner->getTradeState() == TRADE_TRANSFER) || player->getTradeState() == TRADE_TRANSFER) { return; @@ -5169,7 +5172,7 @@ void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5225,7 +5228,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5255,7 +5258,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin } void Game::playerCloseShop(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5264,7 +5267,7 @@ void Game::playerCloseShop(uint32_t playerId) { } void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5294,7 +5297,7 @@ void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) { } void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, uint8_t stackPos) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5329,7 +5332,7 @@ void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, } void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5363,8 +5366,8 @@ void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { g_callbacks().executeCallback(EventCallback_t::playerOnLookInBattleList, &EventCallback::playerOnLookInBattleList, player, creature, lookDistance); } -void Game::playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, std::shared_ptr defaultItem, bool lootAllCorpses, bool autoLoot) { - std::shared_ptr player = getPlayerByID(playerId); +void Game::playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, const std::shared_ptr &defaultItem, bool lootAllCorpses, bool autoLoot) { + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5504,7 +5507,7 @@ void Game::playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t item } } -void Game::playerLootAllCorpses(std::shared_ptr player, const Position &pos, bool lootAllCorpses) { +void Game::playerLootAllCorpses(const std::shared_ptr &player, const Position &pos, bool lootAllCorpses) { if (lootAllCorpses) { std::shared_ptr tile = g_game().map.getTile(pos.x, pos.y, pos.z); if (!tile) { @@ -5554,7 +5557,7 @@ void Game::playerLootAllCorpses(std::shared_ptr player, const Position & } void Game::playerSetManagedContainer(uint32_t playerId, ObjectCategory_t category, const Position &pos, uint16_t itemId, uint8_t stackPos, bool isLootContainer) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || pos.x != 0xffff) { return; } @@ -5599,7 +5602,7 @@ void Game::playerSetManagedContainer(uint32_t playerId, ObjectCategory_t categor } void Game::playerClearManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5616,7 +5619,7 @@ void Game::playerClearManagedContainer(uint32_t playerId, ObjectCategory_t categ } void Game::playerOpenManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5630,7 +5633,7 @@ void Game::playerOpenManagedContainer(uint32_t playerId, ObjectCategory_t catego } void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5638,8 +5641,8 @@ void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) { player->quickLootFallbackToMainContainer = fallback; } -void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector itemIds) { - std::shared_ptr player = getPlayerByID(playerId); +void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector &itemIds) { + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5652,7 +5655,7 @@ void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t fi * Depot search system ******************************************************************************/ void Game::playerRequestDepotItems(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isDepotSearchAvailable()) { return; } @@ -5667,7 +5670,7 @@ void Game::playerRequestDepotItems(uint32_t playerId) { } void Game::playerRequestCloseDepotSearch(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5677,7 +5680,7 @@ void Game::playerRequestCloseDepotSearch(uint32_t playerId) { } void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5692,7 +5695,7 @@ void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint } void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpenOnItem(itemId)) { return; } @@ -5707,7 +5710,7 @@ void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, } void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position &pos) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5722,7 +5725,7 @@ void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Po } void Game::playerCancelAttackAndFollow(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5733,7 +5736,7 @@ void Game::playerCancelAttackAndFollow(uint32_t playerId) { } void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5764,7 +5767,7 @@ void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { } void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5775,7 +5778,7 @@ void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { } void Game::playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5790,7 +5793,7 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string &name) { return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5826,7 +5829,7 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string &name) { } void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5835,16 +5838,16 @@ void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { } void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string &description, uint32_t icon, bool notify, std::vector vipGroupsId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - player->vip()->edit(guid, description, icon, notify, vipGroupsId); + player->vip()->edit(guid, description, icon, notify, std::move(vipGroupsId)); } void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t slot, bool protectionCharm) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5858,7 +5861,7 @@ void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t return; } - std::shared_ptr item = player->imbuingItem; + const auto item = player->imbuingItem; if (!item) { return; } @@ -5873,7 +5876,7 @@ void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t } void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { - std::shared_ptr player = getPlayerByID(playerid); + const auto player = getPlayerByID(playerid); if (!player) { return; } @@ -5882,7 +5885,7 @@ void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { return; } - std::shared_ptr item = player->imbuingItem; + const auto item = player->imbuingItem; if (!item) { return; } @@ -5891,7 +5894,7 @@ void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { } void Game::playerCloseImbuementWindow(uint32_t playerid) { - std::shared_ptr player = getPlayerByID(playerid); + const auto player = getPlayerByID(playerid); if (!player) { return; } @@ -5900,7 +5903,7 @@ void Game::playerCloseImbuementWindow(uint32_t playerid) { } void Game::playerTurn(uint32_t playerId, Direction dir) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5922,7 +5925,7 @@ void Game::playerRequestOutfit(uint32_t playerId) { return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5931,7 +5934,7 @@ void Game::playerRequestOutfit(uint32_t playerId) { } void Game::playerToggleMount(uint32_t playerId, bool mount) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -5944,7 +5947,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMoun return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -6011,7 +6014,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMoun } void Game::playerShowQuestLog(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -6021,7 +6024,7 @@ void Game::playerShowQuestLog(uint32_t playerId) { } void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -6031,7 +6034,7 @@ void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { } void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, const std::string &receiver, const std::string &text) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -6095,7 +6098,7 @@ void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, c } } -bool Game::playerSaySpell(std::shared_ptr player, SpeakClasses type, const std::string &text) { +bool Game::playerSaySpell(const std::shared_ptr &player, SpeakClasses type, const std::string &text) { if (player->walkExhausted()) { return true; } @@ -6119,7 +6122,7 @@ bool Game::playerSaySpell(std::shared_ptr player, SpeakClasses type, con return false; } -void Game::playerWhisper(std::shared_ptr player, const std::string &text) { +void Game::playerWhisper(const std::shared_ptr &player, const std::string &text) { auto spectators = Spectators().find(player->getPosition(), false, MAP_MAX_CLIENT_VIEW_PORT_X, MAP_MAX_CLIENT_VIEW_PORT_X, MAP_MAX_CLIENT_VIEW_PORT_Y, MAP_MAX_CLIENT_VIEW_PORT_Y); // Send to client @@ -6139,7 +6142,7 @@ void Game::playerWhisper(std::shared_ptr player, const std::string &text } } -bool Game::playerYell(std::shared_ptr player, const std::string &text) { +bool Game::playerYell(const std::shared_ptr &player, const std::string &text) { if (player->getLevel() == 1) { player->sendTextMessage(MESSAGE_FAILURE, "You may not yell as long as you are on level 1."); return false; @@ -6159,7 +6162,7 @@ bool Game::playerYell(std::shared_ptr player, const std::string &text) { return true; } -bool Game::playerSpeakTo(std::shared_ptr player, SpeakClasses type, const std::string &receiver, const std::string &text) { +bool Game::playerSpeakTo(const std::shared_ptr &player, SpeakClasses type, const std::string &receiver, const std::string &text) { std::shared_ptr toPlayer = getPlayerByName(receiver); if (!toPlayer) { player->sendTextMessage(MESSAGE_FAILURE, "A player with this name is not online."); @@ -6185,7 +6188,7 @@ bool Game::playerSpeakTo(std::shared_ptr player, SpeakClasses type, cons return true; } -void Game::playerSpeakToNpc(std::shared_ptr player, const std::string &text) { +void Game::playerSpeakToNpc(const std::shared_ptr &player, const std::string &text) { if (player == nullptr) { g_logger().error("[Game::playerSpeakToNpc] - Player is nullptr"); return; @@ -6208,8 +6211,8 @@ void Game::playerSpeakToNpc(std::shared_ptr player, const std::string &t player->updateUIExhausted(); } -std::shared_ptr Game::createPlayerTask(uint32_t delay, std::function f, std::string context) const { - return Player::createPlayerTask(delay, std::move(f), std::move(context)); +std::shared_ptr Game::createPlayerTask(uint32_t delay, std::function f, const std::string &context) const { + return Player::createPlayerTask(delay, std::move(f), context); } //-- @@ -6221,7 +6224,7 @@ bool Game::isSightClear(const Position &fromPos, const Position &toPos, bool flo return map.isSightClear(fromPos, toPos, floorCheck); } -bool Game::internalCreatureTurn(std::shared_ptr creature, Direction dir) { +bool Game::internalCreatureTurn(const std::shared_ptr &creature, Direction dir) { if (creature->getDirection() == dir) { return false; } @@ -6240,7 +6243,7 @@ bool Game::internalCreatureTurn(std::shared_ptr creature, Direction di return true; } -bool Game::internalCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text, bool ghostMode, Spectators* spectatorsPtr /* = nullptr*/, const Position* pos /* = nullptr*/) { +bool Game::internalCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, bool ghostMode, Spectators* spectatorsPtr /* = nullptr*/, const Position* pos /* = nullptr*/) { if (text.empty()) { return false; } @@ -6355,7 +6358,7 @@ void Game::checkCreatures() { index = (index + 1) % EVENT_CREATURECOUNT; } -void Game::changeSpeed(std::shared_ptr creature, int32_t varSpeedDelta) { +void Game::changeSpeed(const std::shared_ptr &creature, int32_t varSpeedDelta) { int32_t varSpeed = creature->getSpeed() - creature->getBaseSpeed(); varSpeed += varSpeedDelta; @@ -6367,7 +6370,7 @@ void Game::changeSpeed(std::shared_ptr creature, int32_t varSpeedDelta } } -void Game::setCreatureSpeed(std::shared_ptr creature, int32_t speed) { +void Game::setCreatureSpeed(const std::shared_ptr &creature, int32_t speed) { creature->setBaseSpeed(static_cast(speed)); // Send creature speed to client @@ -6388,7 +6391,7 @@ void Game::changePlayerSpeed(const std::shared_ptr &player, int32_t varS } } -void Game::internalCreatureChangeOutfit(std::shared_ptr creature, const Outfit_t &outfit) { +void Game::internalCreatureChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) { if (!g_events().eventCreatureOnChangeOutfit(creature, outfit)) { return; } @@ -6409,28 +6412,28 @@ void Game::internalCreatureChangeOutfit(std::shared_ptr creature, cons } } -void Game::internalCreatureChangeVisible(std::shared_ptr creature, bool visible) { +void Game::internalCreatureChangeVisible(const std::shared_ptr &creature, bool visible) { // Send to clients for (const auto &spectator : Spectators().find(creature->getPosition(), true)) { spectator->getPlayer()->sendCreatureChangeVisible(creature, visible); } } -void Game::changeLight(std::shared_ptr creature) { +void Game::changeLight(const std::shared_ptr &creature) { // Send to clients for (const auto &spectator : Spectators().find(creature->getPosition(), true)) { spectator->getPlayer()->sendCreatureLight(creature); } } -void Game::updateCreatureIcon(std::shared_ptr creature) { +void Game::updateCreatureIcon(const std::shared_ptr &creature) { // Send to clients for (const auto &spectator : Spectators().find(creature->getPosition(), true)) { spectator->getPlayer()->sendCreatureIcon(creature); } } -void Game::reloadCreature(std::shared_ptr creature) { +void Game::reloadCreature(const std::shared_ptr &creature) { if (!creature) { g_logger().error("[{}] Creature is nullptr", __FUNCTION__); return; @@ -6441,7 +6444,7 @@ void Game::reloadCreature(std::shared_ptr creature) { } } -void Game::sendSingleSoundEffect(const Position &pos, SoundEffect_t soundId, std::shared_ptr actor /* = nullptr*/) { +void Game::sendSingleSoundEffect(const Position &pos, SoundEffect_t soundId, const std::shared_ptr &actor /* = nullptr*/) { if (soundId == SoundEffect_t::SILENCE) { return; } @@ -6461,7 +6464,7 @@ void Game::sendSingleSoundEffect(const Position &pos, SoundEffect_t soundId, std } } -void Game::sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundEffect, SoundEffect_t secondarySoundEffect, std::shared_ptr actor /* = nullptr*/) { +void Game::sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundEffect, SoundEffect_t secondarySoundEffect, const std::shared_ptr &actor /* = nullptr*/) { if (secondarySoundEffect == SoundEffect_t::SILENCE) { sendSingleSoundEffect(pos, mainSoundEffect, actor); return; @@ -6482,7 +6485,7 @@ void Game::sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundEff } } -bool Game::combatBlockHit(CombatDamage &damage, std::shared_ptr attacker, std::shared_ptr target, bool checkDefense, bool checkArmor, bool field) { +bool Game::combatBlockHit(CombatDamage &damage, const std::shared_ptr &attacker, const std::shared_ptr &target, bool checkDefense, bool checkArmor, bool field) { if (damage.primary.type == COMBAT_NONE && damage.secondary.type == COMBAT_NONE) { return true; } @@ -6670,7 +6673,7 @@ bool Game::combatBlockHit(CombatDamage &damage, std::shared_ptr attack return (primaryBlockType != BLOCK_NONE) && (secondaryBlockType != BLOCK_NONE); } -void Game::combatGetTypeInfo(CombatType_t combatType, std::shared_ptr target, TextColor_t &color, uint16_t &effect) { +void Game::combatGetTypeInfo(CombatType_t combatType, const std::shared_ptr &target, TextColor_t &color, uint16_t &effect) { switch (combatType) { case COMBAT_PHYSICALDAMAGE: { std::shared_ptr splash = nullptr; @@ -6781,7 +6784,7 @@ void Game::combatGetTypeInfo(CombatType_t combatType, std::shared_ptr } // Hazard combat helpers -void Game::handleHazardSystemAttack(CombatDamage &damage, std::shared_ptr player, std::shared_ptr monster, bool isPlayerAttacker) { +void Game::handleHazardSystemAttack(CombatDamage &damage, const std::shared_ptr &player, const std::shared_ptr &monster, bool isPlayerAttacker) { if (damage.primary.value != 0 && monster->getHazard()) { if (isPlayerAttacker) { player->parseAttackDealtHazardSystem(damage, monster); @@ -6791,7 +6794,7 @@ void Game::handleHazardSystemAttack(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr targetMonster) { +void Game::notifySpectators(const CreatureVector &spectators, const Position &targetPos, const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster) { if (!spectators.empty()) { for (const auto &spectator : spectators) { if (!spectator) { @@ -6820,7 +6823,7 @@ void Game::notifySpectators(const CreatureVector &spectators, const Position &ta } // Custom PvP System combat helpers -void Game::applyPvPDamage(CombatDamage &damage, std::shared_ptr attacker, std::shared_ptr target) { +void Game::applyPvPDamage(CombatDamage &damage, const std::shared_ptr &attacker, const std::shared_ptr &target) { float targetDamageReceivedMultiplier = target->vocation->pvpDamageReceivedMultiplier; float attackerDamageDealtMultiplier = attacker->vocation->pvpDamageDealtMultiplier; float levelDifferenceDamageMultiplier = this->pvpLevelDifferenceDamageMultiplier(attacker, target); @@ -6831,7 +6834,7 @@ void Game::applyPvPDamage(CombatDamage &damage, std::shared_ptr attacker damage.secondary.value = std::round(damage.secondary.value * pvpDamageMultiplier); } -float Game::pvpLevelDifferenceDamageMultiplier(std::shared_ptr attacker, std::shared_ptr target) { +float Game::pvpLevelDifferenceDamageMultiplier(const std::shared_ptr &attacker, const std::shared_ptr &target) { int32_t levelDifference = target->getLevel() - attacker->getLevel(); levelDifference = std::abs(levelDifference); bool isLowerLevel = target->getLevel() < attacker->getLevel(); @@ -6852,7 +6855,7 @@ float Game::pvpLevelDifferenceDamageMultiplier(std::shared_ptr attacker, } // Wheel of destiny combat helpers -void Game::applyWheelOfDestinyHealing(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr target) { +void Game::applyWheelOfDestinyHealing(CombatDamage &damage, const std::shared_ptr &attackerPlayer, std::shared_ptr target) { damage.primary.value += (damage.primary.value * damage.healingMultiplier) / 100.; if (attackerPlayer) { @@ -6870,12 +6873,12 @@ void Game::applyWheelOfDestinyHealing(CombatDamage &damage, std::shared_ptrwheel()->getInstant("Blessing of the Grove")) { - damage.primary.value += (damage.primary.value * attackerPlayer->wheel()->checkBlessingGroveHealingByTarget(target)) / 100.; + damage.primary.value += (damage.primary.value * attackerPlayer->wheel()->checkBlessingGroveHealingByTarget(std::move(target))) / 100.; } } } -void Game::applyWheelOfDestinyEffectsToDamage(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr target) const { +void Game::applyWheelOfDestinyEffectsToDamage(CombatDamage &damage, const std::shared_ptr &attackerPlayer, const std::shared_ptr &target) const { // If damage is 0, it means the target is immune to the damage type, or that we missed. if (damage.primary.value == 0 && damage.secondary.value == 0) { return; @@ -6915,7 +6918,7 @@ void Game::applyWheelOfDestinyEffectsToDamage(CombatDamage &damage, std::shared_ } } -int32_t Game::applyHealthChange(CombatDamage &damage, std::shared_ptr target) const { +int32_t Game::applyHealthChange(CombatDamage &damage, const std::shared_ptr &target) const { int32_t targetHealth = target->getHealth(); // Wheel of destiny (Gift of Life) @@ -6932,7 +6935,7 @@ int32_t Game::applyHealthChange(CombatDamage &damage, std::shared_ptr return targetHealth; } -bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_ptr target, CombatDamage &damage, bool isEvent /*= false*/) { +bool Game::combatChangeHealth(const std::shared_ptr &attacker, const std::shared_ptr &target, CombatDamage &damage, bool isEvent /*= false*/) { using namespace std; const Position &targetPos = target->getPosition(); if (damage.primary.value > 0) { @@ -7079,7 +7082,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt int32_t distanceY = Position::getDistanceY(targetPos, attackerPos); int32_t damageX = attackerPlayer->getPerfectShotDamage(distanceX, true); int32_t damageY = attackerPlayer->getPerfectShotDamage(distanceY, true); - std::shared_ptr item = attackerPlayer->getWeapon(); + const auto item = attackerPlayer->getWeapon(); if (item && item->getWeaponType() == WEAPON_DISTANCE) { std::shared_ptr quiver = attackerPlayer->getInventoryItem(CONST_SLOT_RIGHT); if (quiver && quiver->getWeaponType()) { @@ -7354,7 +7357,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt return true; } -void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, std::shared_ptr player) const { +void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const std::shared_ptr &player) const { if (!player) { return; } @@ -7370,8 +7373,8 @@ void Game::updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, std::shared } void Game::sendDamageMessageAndEffects( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, - const Position &targetPos, std::shared_ptr attackerPlayer, std::shared_ptr targetPlayer, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, + const Position &targetPos, const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetPlayer, TextMessage &message, const CreatureVector &spectators, int32_t realDamage ) { message.primary.value = damage.primary.value; @@ -7380,7 +7383,7 @@ void Game::sendDamageMessageAndEffects( sendEffects(target, damage, targetPos, message, spectators); if (shouldSendMessage(message)) { - sendMessages(std::move(attacker), target, damage, targetPos, std::move(attackerPlayer), std::move(targetPlayer), message, spectators, realDamage); + sendMessages(attacker, target, damage, targetPos, attackerPlayer, targetPlayer, message, spectators, realDamage); } } @@ -7389,8 +7392,8 @@ bool Game::shouldSendMessage(const TextMessage &message) const { } void Game::sendMessages( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, - const Position &targetPos, std::shared_ptr attackerPlayer, std::shared_ptr targetPlayer, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, + const Position &targetPos, const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetPlayer, TextMessage &message, const CreatureVector &spectators, int32_t realDamage ) const { if (attackerPlayer) { @@ -7437,8 +7440,8 @@ void Game::sendMessages( } void Game::buildMessageAsSpectator( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, - std::shared_ptr targetPlayer, TextMessage &message, std::stringstream &ss, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, + const std::shared_ptr &targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString, std::string &spectatorMessage ) const { if (spectatorMessage.empty()) { @@ -7470,8 +7473,8 @@ void Game::buildMessageAsSpectator( } void Game::buildMessageAsTarget( - std::shared_ptr attacker, const CombatDamage &damage, std::shared_ptr attackerPlayer, - std::shared_ptr targetPlayer, TextMessage &message, std::stringstream &ss, + const std::shared_ptr &attacker, const CombatDamage &damage, const std::shared_ptr &attackerPlayer, + const std::shared_ptr &targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const { ss.str({}); @@ -7493,7 +7496,7 @@ void Game::buildMessageAsTarget( } void Game::buildMessageAsAttacker( - std::shared_ptr target, const CombatDamage &damage, TextMessage &message, + const std::shared_ptr &target, const CombatDamage &damage, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const { ss.str({}); @@ -7509,7 +7512,7 @@ void Game::buildMessageAsAttacker( } void Game::sendEffects( - std::shared_ptr target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, + const std::shared_ptr &target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, const CreatureVector &spectators ) { uint16_t hitEffect; @@ -7529,7 +7532,7 @@ void Game::sendEffects( } void Game::applyCharmRune( - std::shared_ptr targetMonster, std::shared_ptr attackerPlayer, std::shared_ptr target, const int32_t &realDamage + const std::shared_ptr &targetMonster, const std::shared_ptr &attackerPlayer, const std::shared_ptr &target, const int32_t &realDamage ) const { if (!targetMonster || !attackerPlayer) { return; @@ -7540,14 +7543,14 @@ void Game::applyCharmRune( int8_t chance = charm->id == CHARM_CRIPPLE ? charm->chance : charm->chance + attackerPlayer->getCharmChanceModifier(); g_logger().debug("charm chance: {}, base: {}, bonus: {}", chance, charm->chance, attackerPlayer->getCharmChanceModifier()); if (charm->type == CHARM_OFFENSIVE && (chance >= normal_random(0, 100))) { - g_iobestiary().parseCharmCombat(charm, attackerPlayer, std::move(target), realDamage); + g_iobestiary().parseCharmCombat(charm, attackerPlayer, target, realDamage); } } } // Mana leech void Game::applyManaLeech( - std::shared_ptr attackerPlayer, std::shared_ptr targetMonster, std::shared_ptr target, const CombatDamage &damage, const int32_t &realDamage + const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster, const std::shared_ptr &target, const CombatDamage &damage, const int32_t &realDamage ) const { // Wheel of destiny bonus - mana leech chance and amount auto wheelLeechChance = attackerPlayer->wheel()->checkDrainBodyLeech(target, SKILL_MANA_LEECH_CHANCE); @@ -7580,7 +7583,7 @@ void Game::applyManaLeech( // Life leech void Game::applyLifeLeech( - std::shared_ptr attackerPlayer, std::shared_ptr targetMonster, std::shared_ptr target, const CombatDamage &damage, const int32_t &realDamage + const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster, const std::shared_ptr &target, const CombatDamage &damage, const int32_t &realDamage ) const { // Wheel of destiny bonus - life leech chance and amount auto wheelLeechChance = attackerPlayer->wheel()->checkDrainBodyLeech(target, SKILL_LIFE_LEECH_CHANCE); @@ -7614,7 +7617,7 @@ int32_t Game::calculateLeechAmount(const int32_t &realDamage, const uint16_t &sk return std::clamp(static_cast(std::lround(intermediateResult)), 0, realDamage); } -bool Game::combatChangeMana(std::shared_ptr attacker, std::shared_ptr target, CombatDamage &damage) { +bool Game::combatChangeMana(const std::shared_ptr &attacker, const std::shared_ptr &target, CombatDamage &damage) { const Position &targetPos = target->getPosition(); auto manaChange = damage.primary.value + damage.secondary.value; if (manaChange > 0) { @@ -7813,12 +7816,12 @@ bool Game::combatChangeMana(std::shared_ptr attacker, std::shared_ptr< return true; } -void Game::addCreatureHealth(std::shared_ptr target) { +void Game::addCreatureHealth(const std::shared_ptr &target) { auto spectators = Spectators().find(target->getPosition(), true); addCreatureHealth(spectators.data(), target); } -void Game::addCreatureHealth(const CreatureVector &spectators, std::shared_ptr target) { +void Game::addCreatureHealth(const CreatureVector &spectators, const std::shared_ptr &target) { uint8_t healthPercent = std::ceil((static_cast(target->getHealth()) / std::max(target->getMaxHealth(), 1)) * 100); if (const auto &targetPlayer = target->getPlayer()) { if (const auto &party = targetPlayer->getParty()) { @@ -7838,14 +7841,14 @@ void Game::addCreatureHealth(const CreatureVector &spectators, std::shared_ptr target) { +void Game::addPlayerMana(const std::shared_ptr &target) { if (const auto &party = target->getParty()) { uint8_t manaPercent = std::ceil((static_cast(target->getMana()) / std::max(target->getMaxMana(), 1)) * 100); party->updatePlayerMana(target, manaPercent); } } -void Game::addPlayerVocation(std::shared_ptr target) { +void Game::addPlayerVocation(const std::shared_ptr &target) { if (const auto &party = target->getParty()) { party->updatePlayerVocation(target); } @@ -7894,7 +7897,7 @@ void Game::addDistanceEffect(const CreatureVector &spectators, const Position &f } } -void Game::checkImbuements() { +void Game::checkImbuements() const { for (const auto &[mapPlayerId, mapPlayer] : getPlayers()) { if (!mapPlayer) { continue; @@ -8003,7 +8006,7 @@ void Game::shutdown() { g_logger().info("Done!"); } -void Game::addBestiaryList(uint16_t raceid, std::string name) { +void Game::addBestiaryList(uint16_t raceid, const std::string &name) { auto it = BestiaryList.find(raceid); if (it != BestiaryList.end()) { return; @@ -8021,7 +8024,7 @@ void Game::broadcastMessage(const std::string &text, MessageClasses type) const } } -void Game::updateCreatureWalkthrough(std::shared_ptr creature) { +void Game::updateCreatureWalkthrough(const std::shared_ptr &creature) { // Send to clients for (const auto &spectator : Spectators().find(creature->getPosition(), true)) { const auto &tmpPlayer = spectator->getPlayer(); @@ -8029,7 +8032,7 @@ void Game::updateCreatureWalkthrough(std::shared_ptr creature) { } } -void Game::updateCreatureSkull(std::shared_ptr creature) { +void Game::updateCreatureSkull(const std::shared_ptr &creature) const { if (getWorldType() != WORLD_TYPE_PVP) { return; } @@ -8039,13 +8042,13 @@ void Game::updateCreatureSkull(std::shared_ptr creature) { } } -void Game::updatePlayerShield(std::shared_ptr player) { +void Game::updatePlayerShield(const std::shared_ptr &player) { for (const auto &spectator : Spectators().find(player->getPosition(), true)) { spectator->getPlayer()->sendCreatureShield(player); } } -void Game::updateCreatureType(std::shared_ptr creature) { +void Game::updateCreatureType(const std::shared_ptr &creature) { if (!creature) { return; } @@ -8149,7 +8152,7 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) { return; } - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8176,7 +8179,7 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) { party->invitePlayer(invitedPlayer); } -void Game::updatePlayerHelpers(std::shared_ptr player) { +void Game::updatePlayerHelpers(const std::shared_ptr &player) { if (!player) { return; } @@ -8188,7 +8191,7 @@ void Game::updatePlayerHelpers(std::shared_ptr player) { } void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8212,7 +8215,7 @@ void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { } void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8231,7 +8234,7 @@ void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { } void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8250,7 +8253,7 @@ void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { } void Game::playerLeaveParty(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8265,7 +8268,7 @@ void Game::playerLeaveParty(uint32_t playerId) { } void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8280,7 +8283,7 @@ void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpAc } void Game::sendGuildMotd(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8292,7 +8295,7 @@ void Game::sendGuildMotd(uint32_t playerId) { } void Game::kickPlayer(uint32_t playerId, bool displayEffect) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8300,7 +8303,7 @@ void Game::kickPlayer(uint32_t playerId, bool displayEffect) { player->removePlayer(displayEffect); } -void Game::playerFriendSystemAction(std::shared_ptr player, uint8_t type, uint8_t titleId) { +void Game::playerFriendSystemAction(const std::shared_ptr &player, uint8_t type, uint8_t titleId) { if (type == 0x0E) { player->title()->setCurrentTitle(titleId); player->sendCyclopediaCharacterBaseInformation(); @@ -8309,7 +8312,7 @@ void Game::playerFriendSystemAction(std::shared_ptr player, uint8_t type } } -void Game::playerCyclopediaCharacterInfo(std::shared_ptr player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page) { +void Game::playerCyclopediaCharacterInfo(const std::shared_ptr &player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page) { uint32_t playerGUID = player->getGUID(); if (characterID != playerGUID) { // For now allow viewing only our character since we don't have tournaments supported @@ -8422,8 +8425,8 @@ std::string Game::generateVocationConditionHighscore(uint32_t vocation) { return queryPart.str(); } -void Game::processHighscoreResults(DBResult_ptr result, uint32_t playerID, uint8_t category, uint32_t vocation, uint8_t entriesPerPage) { - std::shared_ptr player = g_game().getPlayerByID(playerID); +void Game::processHighscoreResults(const DBResult_ptr &result, uint32_t playerID, uint8_t category, uint32_t vocation, uint8_t entriesPerPage) { + const auto player = g_game().getPlayerByID(playerID); if (!player) { return; } @@ -8435,8 +8438,8 @@ void Game::processHighscoreResults(DBResult_ptr result, uint32_t playerID, uint8 return; } - uint16_t page = result->getNumber("page"); - uint32_t pages = result->getNumber("entries"); + auto page = result->getNumber("page"); + auto pages = result->getNumber("entries"); pages += entriesPerPage - 1; pages /= entriesPerPage; @@ -8460,7 +8463,7 @@ void Game::processHighscoreResults(DBResult_ptr result, uint32_t playerID, uint8 do { const auto &voc = g_vocations().getVocation(result->getNumber("vocation")); uint8_t characterVocation = voc ? voc->getClientId() : 0; - std::string loyaltyTitle = ""; // todo get loyalty title from player + std::string loyaltyTitle; // todo get loyalty title from player characters.emplace_back(std::move(result->getString("name")), result->getNumber("points"), result->getNumber("id"), result->getNumber("rank"), result->getNumber("level"), characterVocation, loyaltyTitle); } while (result->next()); } @@ -8511,7 +8514,7 @@ std::string Game::generateHighscoreOrGetCachedQueryForOurRank(const std::string return newQuery; } -void Game::playerHighscores(std::shared_ptr player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &, uint16_t page, uint8_t entriesPerPage) { +void Game::playerHighscores(const std::shared_ptr &player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &, uint16_t page, uint8_t entriesPerPage) { if (player->hasAsyncOngoingTask(PlayerAsyncTask_Highscore)) { return; } @@ -8526,8 +8529,8 @@ void Game::playerHighscores(std::shared_ptr player, HighscoreType_t type } uint32_t playerID = player->getID(); - std::function callback = [this, playerID, category, vocation, entriesPerPage](DBResult_ptr result, bool) { - processHighscoreResults(std::move(result), playerID, category, vocation, entriesPerPage); + std::function callback = [this, playerID, category, vocation, entriesPerPage](const DBResult_ptr &result, bool) { + processHighscoreResults(result, playerID, category, vocation, entriesPerPage); }; g_databaseTasks().store(query, callback); @@ -8561,7 +8564,7 @@ std::string Game::getSkillNameById(uint8_t &skill) { } void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8571,7 +8574,7 @@ void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string } void Game::playerReportBug(uint32_t playerId, const std::string &message, const Position &position, uint8_t category) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8581,7 +8584,7 @@ void Game::playerReportBug(uint32_t playerId, const std::string &message, const } void Game::playerDebugAssert(uint32_t playerId, const std::string &assertLine, const std::string &date, const std::string &description, const std::string &comment) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8596,7 +8599,7 @@ void Game::playerDebugAssert(uint32_t playerId, const std::string &assertLine, c } void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uint8_t option, int8_t index, uint16_t raceId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8605,7 +8608,7 @@ void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uin } void Game::playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t action, bool upgrade, uint16_t raceId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8650,7 +8653,7 @@ void Game::playerNpcGreet(uint32_t playerId, uint32_t npcId) { } void Game::playerLeaveMarket(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8659,7 +8662,7 @@ void Game::playerLeaveMarket(uint32_t playerId) { } void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8684,7 +8687,7 @@ void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) } void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8699,7 +8702,7 @@ void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { } void Game::playerBrowseMarketOwnHistory(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -8785,7 +8788,7 @@ namespace { } } // namespace -bool checkCanInitCreateMarketOffer(std::shared_ptr player, uint8_t type, const ItemType &it, uint16_t amount, uint64_t price, std::ostringstream &offerStatus) { +bool checkCanInitCreateMarketOffer(const std::shared_ptr &player, uint8_t type, const ItemType &it, uint16_t amount, uint64_t price, std::ostringstream &offerStatus) { if (!player) { offerStatus << "Failed to load player"; return false; @@ -8851,7 +8854,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite // Initialize variables // Before creating the offer we will compare it with the RETURN VALUE ERROR std::ostringstream offerStatus; - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); const ItemType &it = Item::items[itemId]; // Make sure everything is ok before the create market offer starts @@ -8934,7 +8937,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite } void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->getAccount()) { return; } @@ -8971,7 +8974,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint16_t tmpAmount = offer.amount; while (tmpAmount > 0) { int32_t stackCount = std::min(it.stackSize, tmpAmount); - std::shared_ptr item = Item::CreateItem(it.id, stackCount); + const auto item = Item::CreateItem(it.id, stackCount); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { break; } @@ -8991,7 +8994,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < offer.amount; ++i) { - std::shared_ptr item = Item::CreateItem(it.id, subType); + const auto item = Item::CreateItem(it.id, subType); if (internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { break; } @@ -9017,7 +9020,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) { std::ostringstream offerStatus; - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || !player->getAccount()) { offerStatus << "Failed to load player"; return; @@ -9124,7 +9127,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(it.stackSize, tmpAmount); - std::shared_ptr item = Item::CreateItem(it.id, stackCount); + const auto item = Item::CreateItem(it.id, stackCount); if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { offerStatus << "Failed to add player inbox stackable item for buy offer for player " << player->getName(); @@ -9146,7 +9149,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < amount; ++i) { - std::shared_ptr item = Item::CreateItem(it.id, subType); + const auto item = Item::CreateItem(it.id, subType); if (internalAddItem(buyerPlayer->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { offerStatus << "Failed to add player inbox item for buy offer for player " << player->getName(); @@ -9195,7 +9198,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(it.stackSize, tmpAmount); - std::shared_ptr item = Item::CreateItem(it.id, stackCount); + const auto item = Item::CreateItem(it.id, stackCount); if ( // Init-statement auto ret = internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); @@ -9223,7 +9226,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } for (uint16_t i = 0; i < amount; ++i) { - std::shared_ptr item = Item::CreateItem(it.id, subType); + const auto item = Item::CreateItem(it.id, subType); if ( // Init-statement auto ret = internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT); @@ -9289,7 +9292,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string &buffer) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9308,7 +9311,7 @@ void Game::forceRemoveCondition(uint32_t creatureId, ConditionType_t conditionTy creature->removeCondition(conditionType, conditionId, true); } -void Game::sendOfflineTrainingDialog(std::shared_ptr player) { +void Game::sendOfflineTrainingDialog(const std::shared_ptr &player) { if (!player) { return; } @@ -9319,7 +9322,7 @@ void Game::sendOfflineTrainingDialog(std::shared_ptr player) { } void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9354,7 +9357,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui void Game::playerForgeFuseItems(uint32_t playerId, ForgeAction_t actionType, uint16_t firstItemId, uint8_t tier, uint16_t secondItemId, bool usedCore, bool reduceTierLoss, bool convergence) { metrics::method_latency measure(__METHOD_NAME__); - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9381,7 +9384,7 @@ void Game::playerForgeFuseItems(uint32_t playerId, ForgeAction_t actionType, uin } void Game::playerForgeTransferItemTier(uint32_t playerId, ForgeAction_t actionType, uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId, bool convergence) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9396,7 +9399,7 @@ void Game::playerForgeTransferItemTier(uint32_t playerId, ForgeAction_t actionTy } void Game::playerForgeResourceConversion(uint32_t playerId, ForgeAction_t actionType) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9411,7 +9414,7 @@ void Game::playerForgeResourceConversion(uint32_t playerId, ForgeAction_t action } void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9426,7 +9429,7 @@ void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) { } void Game::playerBosstiarySlot(uint32_t playerId, uint8_t slotId, uint32_t selectedBossId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9453,7 +9456,7 @@ void Game::playerBosstiarySlot(uint32_t playerId, uint8_t slotId, uint32_t selec } void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t direction, const std::pair &podiumAndMonsterVisible) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -9463,7 +9466,7 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != itemId || !item->isPodium() || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -9559,7 +9562,7 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con } void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9569,7 +9572,7 @@ void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t st return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != itemId || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -9648,7 +9651,7 @@ void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t st } void Game::playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpen) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player || player->isRemoved()) { return; } @@ -9660,7 +9663,7 @@ void Game::playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpe std::map> itemsWithImbueSlotMap; for (uint8_t inventorySlot = CONST_SLOT_FIRST; inventorySlot <= CONST_SLOT_LAST; ++inventorySlot) { - auto item = player->getInventoryItem(static_cast(inventorySlot)); + const auto &item = player->getInventoryItem(static_cast(inventorySlot)); if (!item) { continue; } @@ -9680,7 +9683,7 @@ void Game::playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpe } void Game::playerOpenWheel(uint32_t playerId, uint32_t ownerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9700,7 +9703,7 @@ void Game::playerOpenWheel(uint32_t playerId, uint32_t ownerId) { } void Game::playerSaveWheel(uint32_t playerId, NetworkMessage &msg) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9715,7 +9718,7 @@ void Game::playerSaveWheel(uint32_t playerId, NetworkMessage &msg) { } void Game::playerWheelGemAction(uint32_t playerId, NetworkMessage &msg) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9752,7 +9755,7 @@ void Game::playerWheelGemAction(uint32_t playerId, NetworkMessage &msg) { ********************/ void Game::updatePlayerSaleItems(uint32_t playerId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } @@ -9762,33 +9765,33 @@ void Game::updatePlayerSaleItems(uint32_t playerId) { player->setScheduledSaleUpdate(false); } -void Game::addPlayer(std::shared_ptr player) { +void Game::addPlayer(const std::shared_ptr &player) { const std::string &lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames[lowercase_name] = player; wildcardTree->insert(lowercase_name); players[player->getID()] = player; } -void Game::removePlayer(std::shared_ptr player) { +void Game::removePlayer(const std::shared_ptr &player) { const std::string &lowercase_name = asLowerCaseString(player->getName()); mappedPlayerNames.erase(lowercase_name); wildcardTree->remove(lowercase_name); players.erase(player->getID()); } -void Game::addNpc(std::shared_ptr npc) { +void Game::addNpc(const std::shared_ptr &npc) { npcs[npc->getID()] = npc; } -void Game::removeNpc(std::shared_ptr npc) { +void Game::removeNpc(const std::shared_ptr &npc) { npcs.erase(npc->getID()); } -void Game::addMonster(std::shared_ptr monster) { +void Game::addMonster(const std::shared_ptr &monster) { monsters[monster->getID()] = monster; } -void Game::removeMonster(std::shared_ptr monster) { +void Game::removeMonster(const std::shared_ptr &monster) { monsters.erase(monster->getID()); } @@ -9815,7 +9818,7 @@ std::shared_ptr Game::getGuildByName(const std::string &name, bool allowO return it->second; } -void Game::addGuild(const std::shared_ptr guild) { +void Game::addGuild(const std::shared_ptr &guild) { if (!guild) { return; } @@ -9832,7 +9835,7 @@ void Game::removeGuild(uint32_t guildId) { void Game::internalRemoveItems(const std::vector> &itemVector, uint32_t amount, bool stackable) { if (stackable) { - for (const std::shared_ptr &item : itemVector) { + for (const auto &item : itemVector) { if (item->getItemCount() > amount) { internalRemoveItem(item, amount); break; @@ -9842,7 +9845,7 @@ void Game::internalRemoveItems(const std::vector> &itemVec } } } else { - for (const std::shared_ptr &item : itemVector) { + for (const auto &item : itemVector) { internalRemoveItem(item); } } @@ -9892,7 +9895,7 @@ void Game::removeUniqueItem(uint16_t uniqueId) { bool Game::hasEffect(uint16_t effectId) { for (uint16_t i = CONST_ME_NONE; i < CONST_ME_LAST; i++) { - MagicEffectClasses effect = static_cast(i); + auto effect = static_cast(i); if (effect == effectId) { return true; } @@ -9902,7 +9905,7 @@ bool Game::hasEffect(uint16_t effectId) { bool Game::hasDistanceEffect(uint16_t effectId) { for (uint16_t i = CONST_ANI_NONE; i <= CONST_ANI_LAST; i++) { - ShootType_t effect = static_cast(i); + auto effect = static_cast(i); if (effect == effectId) { return true; } @@ -9912,14 +9915,14 @@ bool Game::hasDistanceEffect(uint16_t effectId) { void Game::createLuaItemsOnMap() { for (const auto [position, itemId] : mapLuaItemsStored) { - std::shared_ptr item = Item::CreateItem(itemId, 1); + const auto item = Item::CreateItem(itemId, 1); if (!item) { g_logger().warn("[Game::createLuaItemsOnMap] - Cannot create item with id {}", itemId); continue; } if (position.x != 0) { - std::shared_ptr tile = g_game().map.getTile(position); + const auto tile = g_game().map.getTile(position); if (!tile) { g_logger().warn("[Game::createLuaItemsOnMap] - Tile is wrong or not found position: {}", position.toString()); @@ -9937,7 +9940,7 @@ void Game::createLuaItemsOnMap() { } } -void Game::sendUpdateCreature(std::shared_ptr creature) { +void Game::sendUpdateCreature(const std::shared_ptr &creature) { if (!creature) { return; } @@ -9990,7 +9993,7 @@ uint32_t Game::makeInfluencedMonster() { if (monster && monster->canBeForgeMonster()) { monster->setMonsterForgeClassification(ForgeClassifications_t::FORGE_INFLUENCED_MONSTER); monster->configureForgeSystem(); - influencedMonsters.insert(monster->getID()); + influencedMonsters.emplace(monster->getID()); return monster->getID(); } @@ -10002,7 +10005,7 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool cr forgeableMonsters.clear(); // If the forgeable monsters haven't been created // Then we'll create them so they don't return in the next if (forgeableMonsters.empty()) - for (auto [monsterId, monster] : monsters) { + for (const auto &[monsterId, monster] : monsters) { auto monsterTile = monster->getTile(); if (!monster || !monsterTile) { continue; @@ -10097,7 +10100,7 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool cr monster->setMonsterForgeClassification(ForgeClassifications_t::FORGE_FIENDISH_MONSTER); monster->configureForgeSystem(); monster->setTimeToChangeFiendish(timeToChangeFiendish + getTimeNow()); - fiendishMonsters.insert(monster->getID()); + fiendishMonsters.emplace(monster->getID()); auto schedulerTask = createPlayerTask( finalTime, @@ -10112,7 +10115,7 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool cr } void Game::updateFiendishMonsterStatus(uint32_t monsterId, const std::string &monsterName) { - std::shared_ptr monster = getMonsterByID(monsterId); + const auto monster = getMonsterByID(monsterId); if (!monster) { g_logger().warn("[{}] Failed to update monster with id {} and name {}, monster not found", __FUNCTION__, monsterId, monsterName); return; @@ -10171,14 +10174,14 @@ bool Game::removeFiendishMonster(uint32_t id, bool create /* = true*/) { void Game::updateForgeableMonsters() { forgeableMonsters.clear(); - for (auto [monsterId, monster] : monsters) { + for (const auto &[monsterId, monster] : monsters) { auto monsterTile = monster->getTile(); if (!monsterTile) { continue; } if (monster->canBeForgeMonster() && !monsterTile->hasFlag(TILESTATE_NOLOGOUT)) { - forgeableMonsters.push_back(monster->getID()); + forgeableMonsters.emplace_back(monster->getID()); } } @@ -10240,7 +10243,7 @@ void Game::checkForgeEventId(uint32_t monsterId) { } } -bool Game::addInfluencedMonster(std::shared_ptr monster) { +bool Game::addInfluencedMonster(const std::shared_ptr &monster) { if (monster && monster->canBeForgeMonster()) { if (auto maxInfluencedMonsters = static_cast(g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT, __FUNCTION__)); // If condition @@ -10250,14 +10253,14 @@ bool Game::addInfluencedMonster(std::shared_ptr monster) { monster->setMonsterForgeClassification(ForgeClassifications_t::FORGE_INFLUENCED_MONSTER); monster->configureForgeSystem(); - influencedMonsters.insert(monster->getID()); + influencedMonsters.emplace(monster->getID()); return true; } return false; } -bool Game::addItemStoreInbox(std::shared_ptr player, uint32_t itemId) { - std::shared_ptr decoKit = Item::CreateItem(ITEM_DECORATION_KIT, 1); +bool Game::addItemStoreInbox(const std::shared_ptr &player, uint32_t itemId) { + const auto decoKit = Item::CreateItem(ITEM_DECORATION_KIT, 1); if (!decoKit) { return false; } @@ -10266,17 +10269,17 @@ bool Game::addItemStoreInbox(std::shared_ptr player, uint32_t itemId) { decoKit->setAttribute(ItemAttribute_t::DESCRIPTION, description); decoKit->setCustomAttribute("unWrapId", static_cast(itemId)); - std::shared_ptr thing = player->getThing(CONST_SLOT_STORE_INBOX); + const auto thing = player->getThing(CONST_SLOT_STORE_INBOX); if (!thing) { return false; } - std::shared_ptr inboxItem = thing->getItem(); + const auto inboxItem = thing->getItem(); if (!inboxItem) { return false; } - std::shared_ptr inboxContainer = inboxItem->getContainer(); + const auto inboxContainer = inboxItem->getContainer(); if (!inboxContainer) { return false; } @@ -10288,7 +10291,7 @@ bool Game::addItemStoreInbox(std::shared_ptr player, uint32_t itemId) { return true; } -void Game::addPlayerUniqueLogin(std::shared_ptr player) { +void Game::addPlayerUniqueLogin(const std::shared_ptr &player) { if (!player) { g_logger().error("Attempted to add null player to unique player names list"); return; @@ -10318,7 +10321,7 @@ void Game::removePlayerUniqueLogin(const std::string &playerName) { m_uniqueLoginPlayerNames.erase(lowercase_name); } -void Game::removePlayerUniqueLogin(std::shared_ptr player) { +void Game::removePlayerUniqueLogin(const std::shared_ptr &player) { if (!player) { g_logger().error("Attempted to remove null player from unique player names list."); return; @@ -10329,7 +10332,7 @@ void Game::removePlayerUniqueLogin(std::shared_ptr player) { } void Game::playerCheckActivity(const std::string &playerName, int interval) { - std::shared_ptr player = getPlayerUniqueLogin(playerName); + const auto player = getPlayerUniqueLogin(playerName); if (!player) { return; } @@ -10364,18 +10367,18 @@ void Game::playerCheckActivity(const std::string &playerName, int interval) { } void Game::playerRewardChestCollect(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, uint32_t maxMoveItems /* = 0*/) { - std::shared_ptr player = getPlayerByID(playerId); + const auto player = getPlayerByID(playerId); if (!player) { return; } - std::shared_ptr thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_FIND_THING); + const auto thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_FIND_THING); if (!thing) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - auto item = thing->getItem(); + const auto item = thing->getItem(); if (!item || item->getID() != ITEM_REWARD_CHEST || !item->getContainer()) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -10409,9 +10412,9 @@ void Game::playerRewardChestCollect(uint32_t playerId, const Position &pos, uint } } -bool Game::tryRetrieveStashItems(std::shared_ptr player, std::shared_ptr item) { +bool Game::tryRetrieveStashItems(const std::shared_ptr &player, const std::shared_ptr &item) { ObjectCategory_t category = getObjectCategory(item); - return internalCollectManagedItems(std::move(player), item, category, false) == RETURNVALUE_NOERROR; + return internalCollectManagedItems(player, item, category, false) == RETURNVALUE_NOERROR; } std::unique_ptr &Game::getIOWheel() { @@ -10476,7 +10479,7 @@ std::vector setDifference(const std::unordered_set &setA, const std::unord return setResult; } -ReturnValue Game::beforeCreatureZoneChange(std::shared_ptr creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones, bool force /* = false*/) const { +ReturnValue Game::beforeCreatureZoneChange(const std::shared_ptr &creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones, bool force /* = false*/) const { if (!creature) { return RETURNVALUE_NOTPOSSIBLE; } @@ -10506,7 +10509,8 @@ ReturnValue Game::beforeCreatureZoneChange(std::shared_ptr creature, c return RETURNVALUE_NOERROR; } -void Game::afterCreatureZoneChange(std::shared_ptr creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones) const { +void Game::afterCreatureZoneChange(const std::shared_ptr &creatures, const std::unordered_set> &fromZones, const std::unordered_set> &toZones) const { + auto creature = creatures; if (!creature) { return; } @@ -10539,7 +10543,7 @@ const std::vector &Game::getHighscoreCategories() const { return m_highscoreCategories; } -void Game::registerAchievement(uint16_t id, std::string name, std::string description, bool secret, uint8_t grade, uint8_t points) { +void Game::registerAchievement(uint16_t id, const std::string &name, std::string description, bool secret, uint8_t grade, uint8_t points) { m_achievements[id] = Achievement(); m_achievements[id].id = id; m_achievements[id].name = name; @@ -10555,7 +10559,7 @@ Achievement Game::getAchievementById(uint16_t id) { return m_achievements[id]; } -Achievement Game::getAchievementByName(std::string name) { +Achievement Game::getAchievementByName(const std::string &name) { auto it = m_achievementsNameToId.find(name); if (it != m_achievementsNameToId.end()) { return getAchievementById(it->second); diff --git a/src/game/game.hpp b/src/game/game.hpp index e04dbb26cff..b6dc3e51c99 100644 --- a/src/game/game.hpp +++ b/src/game/game.hpp @@ -39,7 +39,6 @@ class ServiceManager; class Creature; class Monster; class Npc; -class CombatInfo; class Charm; class IOPrey; class IOWheel; @@ -152,10 +151,10 @@ class Game { } std::shared_ptr internalGetCylinder(std::shared_ptr player, const Position &pos); - std::shared_ptr internalGetThing(std::shared_ptr player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type); - static void internalGetPosition(std::shared_ptr item, Position &pos, uint8_t &stackpos); + std::shared_ptr internalGetThing(const std::shared_ptr &player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type); + static void internalGetPosition(const std::shared_ptr &item, Position &pos, uint8_t &stackpos); - static std::string getTradeErrorDescription(ReturnValue ret, std::shared_ptr item); + static std::string getTradeErrorDescription(ReturnValue ret, const std::shared_ptr &item); std::shared_ptr getCreatureByID(uint32_t id); @@ -177,13 +176,13 @@ class Game { ReturnValue getPlayerByNameWildcard(const std::string &s, std::shared_ptr &player); - std::vector> getPlayersByAccount(std::shared_ptr acc, bool allowOffline = false); + std::vector> getPlayersByAccount(const std::shared_ptr &acc, bool allowOffline = false); - bool internalPlaceCreature(std::shared_ptr creature, const Position &pos, bool extendedPos = false, bool forced = false, bool creatureCheck = false); + bool internalPlaceCreature(const std::shared_ptr &creature, const Position &pos, bool extendedPos = false, bool forced = false, bool creatureCheck = false); - bool placeCreature(std::shared_ptr creature, const Position &pos, bool extendedPos = false, bool force = false); + bool placeCreature(const std::shared_ptr &creature, const Position &pos, bool extendedPos = false, bool force = false); - bool removeCreature(std::shared_ptr creature, bool isLogout = true); + bool removeCreature(const std::shared_ptr &creature, bool isLogout = true); void executeDeath(uint32_t creatureId); void addCreatureCheck(const std::shared_ptr &creature); @@ -213,7 +212,7 @@ class Game { if (it != itemsClassifications.end()) { return *it; } else if (create) { - ItemClassification* itemClassification = new ItemClassification(id); + auto* itemClassification = new ItemClassification(id); addItemsClassification(itemClassification); return itemClassification; } @@ -225,38 +224,38 @@ class Game { bool gameIsDay(); - ReturnValue internalMoveCreature(std::shared_ptr creature, Direction direction, uint32_t flags = 0); + ReturnValue internalMoveCreature(const std::shared_ptr &creature, Direction direction, uint32_t flags = 0); ReturnValue internalMoveCreature(const std::shared_ptr &creature, const std::shared_ptr &toTile, uint32_t flags = 0); - ReturnValue checkMoveItemToCylinder(std::shared_ptr player, std::shared_ptr fromCylinder, std::shared_ptr toCylinder, std::shared_ptr item, Position toPos); - ReturnValue internalMoveItem(std::shared_ptr fromCylinder, std::shared_ptr toCylinder, int32_t index, std::shared_ptr item, uint32_t count, std::shared_ptr* movedItem, uint32_t flags = 0, std::shared_ptr actor = nullptr, std::shared_ptr tradeItem = nullptr, bool checkTile = true); + ReturnValue checkMoveItemToCylinder(const std::shared_ptr &player, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder, const std::shared_ptr &item, Position toPos); + ReturnValue internalMoveItem(std::shared_ptr fromCylinder, std::shared_ptr toCylinder, int32_t index, const std::shared_ptr &item, uint32_t count, std::shared_ptr* movedItem, uint32_t flags = 0, const std::shared_ptr &actor = nullptr, const std::shared_ptr &tradeItem = nullptr, bool checkTile = true); std::tuple addItemBatch(const std::shared_ptr &toCylinder, const std::vector> &items, uint32_t flags = 0, bool dropOnMap = true, uint32_t autoContainerId = 0); std::tuple createItemBatch(const std::shared_ptr &toCylinder, const std::vector> &itemCounts, uint32_t flags = 0, bool dropOnMap = true, uint32_t autoContainerId = 0); std::tuple createItem(const std::shared_ptr &toCylinder, uint16_t itemId, uint32_t count, uint16_t subType, uint32_t flags = 0, bool dropOnMap = true, uint32_t autoContainerId = 0); - ReturnValue internalAddItem(std::shared_ptr toCylinder, std::shared_ptr item, int32_t index = INDEX_WHEREEVER, uint32_t flags = 0, bool test = false); - ReturnValue internalAddItem(std::shared_ptr toCylinder, std::shared_ptr item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount); - ReturnValue internalRemoveItem(std::shared_ptr item, int32_t count = -1, bool test = false, uint32_t flags = 0, bool force = false); + ReturnValue internalAddItem(std::shared_ptr toCylinder, const std::shared_ptr &item, int32_t index = INDEX_WHEREEVER, uint32_t flags = 0, bool test = false); + ReturnValue internalAddItem(std::shared_ptr toCylinder, const std::shared_ptr &item, int32_t index, uint32_t flags, bool test, uint32_t &remainderCount); + ReturnValue internalRemoveItem(const std::shared_ptr &item, int32_t count = -1, bool test = false, uint32_t flags = 0, bool force = false); - ReturnValue internalPlayerAddItem(std::shared_ptr player, std::shared_ptr item, bool dropOnMap = true, Slots_t slot = CONST_SLOT_WHEREEVER); + ReturnValue internalPlayerAddItem(const std::shared_ptr &player, const std::shared_ptr &item, bool dropOnMap = true, Slots_t slot = CONST_SLOT_WHEREEVER); - std::shared_ptr findItemOfType(std::shared_ptr cylinder, uint16_t itemId, bool depthSearch = true, int32_t subType = -1) const; + std::shared_ptr findItemOfType(const std::shared_ptr &cylinder, uint16_t itemId, bool depthSearch = true, int32_t subType = -1) const; void createLuaItemsOnMap(); - bool removeMoney(std::shared_ptr cylinder, uint64_t money, uint32_t flags = 0, bool useBank = false); + bool removeMoney(const std::shared_ptr &cylinder, uint64_t money, uint32_t flags = 0, bool useBank = false); - void addMoney(std::shared_ptr cylinder, uint64_t money, uint32_t flags = 0); + void addMoney(const std::shared_ptr &cylinder, uint64_t money, uint32_t flags = 0); std::shared_ptr transformItem(std::shared_ptr item, uint16_t newId, int32_t newCount = -1); ReturnValue internalTeleport(const std::shared_ptr &thing, const Position &newPos, bool pushMove = true, uint32_t flags = 0); - bool internalCreatureTurn(std::shared_ptr creature, Direction dir); + bool internalCreatureTurn(const std::shared_ptr &creature, Direction dir); - bool internalCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text, bool ghostMode, Spectators* spectatorsPtr = nullptr, const Position* pos = nullptr); + bool internalCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, bool ghostMode, Spectators* spectatorsPtr = nullptr, const Position* pos = nullptr); - ObjectCategory_t getObjectCategory(const std::shared_ptr item); + ObjectCategory_t getObjectCategory(const std::shared_ptr &item); ObjectCategory_t getObjectCategory(const ItemType &it); uint64_t getItemMarketPrice(const std::map &itemMap, bool buyPrice) const; @@ -264,8 +263,8 @@ class Game { void loadPlayersRecord(); void checkPlayersRecord(); - void sendSingleSoundEffect(const Position &pos, SoundEffect_t soundId, std::shared_ptr actor = nullptr); - void sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundEffect, SoundEffect_t secondarySoundEffect, std::shared_ptr actor = nullptr); + void sendSingleSoundEffect(const Position &pos, SoundEffect_t soundId, const std::shared_ptr &actor = nullptr); + void sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundEffect, SoundEffect_t secondarySoundEffect, const std::shared_ptr &actor = nullptr); void sendGuildMotd(uint32_t playerId); void kickPlayer(uint32_t playerId, bool displayEffect); @@ -297,38 +296,38 @@ class Game { void playerBrowseForgeHistory(uint32_t playerId, uint8_t page); void playerBosstiarySlot(uint32_t playerId, uint8_t slotId, uint32_t selectedBossId); - void playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t direction, const std::pair &podiumAndMonsterVisible); - void playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); + void playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, const Position &pos, uint8_t stackPos, uint16_t itemId, uint8_t direction, const std::pair &podiumAndMonsterVisible); + void playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t stackPos, uint16_t itemId); void playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpen); - bool addItemStoreInbox(std::shared_ptr player, uint32_t itemId); + bool addItemStoreInbox(const std::shared_ptr &player, uint32_t itemId); void playerRewardChestCollect(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, uint32_t maxMoveItems = 0); void playerReportRuleViolationReport(uint32_t playerId, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); - void playerFriendSystemAction(std::shared_ptr player, uint8_t type, uint8_t titleId); + void playerFriendSystemAction(const std::shared_ptr &player, uint8_t type, uint8_t titleId); - void playerCyclopediaCharacterInfo(std::shared_ptr player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page); + void playerCyclopediaCharacterInfo(const std::shared_ptr &player, uint32_t characterID, CyclopediaCharacterInfoType_t characterInfoType, uint16_t entriesPerPage, uint16_t page); - void playerHighscores(std::shared_ptr player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &worldName, uint16_t page, uint8_t entriesPerPage); + void playerHighscores(const std::shared_ptr &player, HighscoreType_t type, uint8_t category, uint32_t vocation, const std::string &worldName, uint16_t page, uint8_t entriesPerPage); static std::string getSkillNameById(uint8_t &skill); void updatePlayerSaleItems(uint32_t playerId); - bool internalStartTrade(std::shared_ptr player, std::shared_ptr partner, std::shared_ptr tradeItem); - void internalCloseTrade(std::shared_ptr player); - bool playerBroadcastMessage(std::shared_ptr player, const std::string &text) const; + bool internalStartTrade(const std::shared_ptr &player, const std::shared_ptr &partner, const std::shared_ptr &tradeItem); + void internalCloseTrade(const std::shared_ptr &player); + bool playerBroadcastMessage(const std::shared_ptr &player, const std::string &text) const; void broadcastMessage(const std::string &text, MessageClasses type) const; // Implementation of player invoked events void playerTeleport(uint32_t playerId, const Position &pos); void playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count); void playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position &movingCreatureOrigPos, const Position &toPos); - void playerMoveCreature(std::shared_ptr playerId, std::shared_ptr movingCreature, const Position &movingCreatureOrigPos, std::shared_ptr toTile); + void playerMoveCreature(const std::shared_ptr &playerId, const std::shared_ptr &movingCreature, const Position &movingCreatureOrigPos, const std::shared_ptr &toTile); void playerMoveItemByPlayerID(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count); - void playerMoveItem(std::shared_ptr player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, std::shared_ptr item, std::shared_ptr toCylinder); + void playerMoveItem(const std::shared_ptr &player, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count, std::shared_ptr item, std::shared_ptr toCylinder); void playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier = false, uint8_t tier = 0); void playerMove(uint32_t playerId, Direction direction); void forcePlayerMove(uint32_t playerId, Direction direction); @@ -353,10 +352,10 @@ class Game { void playerCloseContainer(uint32_t playerId, uint8_t cid); void playerMoveUpContainer(uint32_t playerId, uint8_t cid); void playerUpdateContainer(uint32_t playerId, uint8_t cid); - void playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); - void playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); - void playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction); - void playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId); + void playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint16_t itemId); + void playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, uint16_t itemId); + void playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, uint16_t itemId, uint8_t podiumVisible, uint8_t direction); + void playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint16_t itemId); void playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string &text); void playerBrowseField(uint32_t playerId, const Position &pos); void playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index, uint8_t containerCategory); @@ -375,14 +374,14 @@ class Game { void playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode); void playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, uint8_t stackPos); void playerLookInBattleList(uint32_t playerId, uint32_t creatureId); - void playerQuickLootCorpse(std::shared_ptr player, std::shared_ptr corpse, const Position &position); - void playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, std::shared_ptr defaultItem = nullptr, bool lootAllCorpses = false, bool autoLoot = false); - void playerLootAllCorpses(std::shared_ptr player, const Position &pos, bool lootAllCorpses); + void playerQuickLootCorpse(const std::shared_ptr &player, const std::shared_ptr &corpse, const Position &position); + void playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, const std::shared_ptr &defaultItem = nullptr, bool lootAllCorpses = false, bool autoLoot = false); + void playerLootAllCorpses(const std::shared_ptr &player, const Position &pos, bool lootAllCorpses); void playerSetManagedContainer(uint32_t playerId, ObjectCategory_t category, const Position &pos, uint16_t itemId, uint8_t stackPos, bool isLootContainer); void playerClearManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer); void playerOpenManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer); void playerSetQuickLootFallback(uint32_t playerId, bool fallback); - void playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector itemIds); + void playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector &itemIds); void playerRequestDepotItems(uint32_t playerId); void playerRequestCloseDepotSearch(uint32_t playerId); @@ -424,11 +423,11 @@ class Game { void playerSaveWheel(uint32_t playerId, NetworkMessage &msg); void playerWheelGemAction(uint32_t playerId, NetworkMessage &msg); - void updatePlayerHelpers(std::shared_ptr player); + void updatePlayerHelpers(const std::shared_ptr &player); void shutdown(); void dieSafely(const std::string &errorMsg); - void addBestiaryList(uint16_t raceid, std::string name); + void addBestiaryList(uint16_t raceid, const std::string &name); const std::map &getBestiaryList() const { return BestiaryList; } @@ -445,18 +444,18 @@ class Game { bool canThrowObjectTo(const Position &fromPos, const Position &toPos, SightLines_t lineOfSight = SightLine_CheckSightLine, int32_t rangex = MAP_MAX_CLIENT_VIEW_PORT_X, int32_t rangey = MAP_MAX_CLIENT_VIEW_PORT_Y); bool isSightClear(const Position &fromPos, const Position &toPos, bool sameFloor); - void changeSpeed(std::shared_ptr creature, int32_t varSpeedDelta); - void setCreatureSpeed(std::shared_ptr creature, int32_t speed); // setCreatureSpeed + void changeSpeed(const std::shared_ptr &creature, int32_t varSpeedDelta); + void setCreatureSpeed(const std::shared_ptr &creature, int32_t speed); // setCreatureSpeed void changePlayerSpeed(const std::shared_ptr &player, int32_t varSpeedDelta); - void internalCreatureChangeOutfit(std::shared_ptr creature, const Outfit_t &oufit); - void internalCreatureChangeVisible(std::shared_ptr creature, bool visible); - void changeLight(const std::shared_ptr creature); - void updateCreatureIcon(const std::shared_ptr creature); - void reloadCreature(const std::shared_ptr creature); - void updateCreatureSkull(std::shared_ptr player); - void updatePlayerShield(std::shared_ptr player); - void updateCreatureType(std::shared_ptr creature); - void updateCreatureWalkthrough(const std::shared_ptr creature); + void internalCreatureChangeOutfit(const std::shared_ptr &creature, const Outfit_t &oufit); + void internalCreatureChangeVisible(const std::shared_ptr &creature, bool visible); + void changeLight(const std::shared_ptr &creature); + void updateCreatureIcon(const std::shared_ptr &creature); + void reloadCreature(const std::shared_ptr &creature); + void updateCreatureSkull(const std::shared_ptr &player) const; + void updatePlayerShield(const std::shared_ptr &player); + void updateCreatureType(const std::shared_ptr &creature); + void updateCreatureWalkthrough(const std::shared_ptr &creature); GameState_t getGameState() const; void setGameState(GameState_t newState); @@ -468,41 +467,41 @@ class Game { void checkCreatures(); void checkLight(); - bool combatBlockHit(CombatDamage &damage, std::shared_ptr attacker, std::shared_ptr target, bool checkDefense, bool checkArmor, bool field); + bool combatBlockHit(CombatDamage &damage, const std::shared_ptr &attacker, const std::shared_ptr &target, bool checkDefense, bool checkArmor, bool field); - void combatGetTypeInfo(CombatType_t combatType, std::shared_ptr target, TextColor_t &color, uint16_t &effect); + void combatGetTypeInfo(CombatType_t combatType, const std::shared_ptr &target, TextColor_t &color, uint16_t &effect); // Hazard combat helpers - void handleHazardSystemAttack(CombatDamage &damage, std::shared_ptr player, const std::shared_ptr monster, bool isPlayerAttacker); - void notifySpectators(const CreatureVector &spectators, const Position &targetPos, std::shared_ptr attackerPlayer, std::shared_ptr targetMonster); + void handleHazardSystemAttack(CombatDamage &damage, const std::shared_ptr &player, const std::shared_ptr &monster, bool isPlayerAttacker); + void notifySpectators(const CreatureVector &spectators, const Position &targetPos, const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster); // Custom PvP System combat helpers - void applyPvPDamage(CombatDamage &damage, std::shared_ptr attacker, std::shared_ptr target); - float pvpLevelDifferenceDamageMultiplier(std::shared_ptr attacker, std::shared_ptr target); + void applyPvPDamage(CombatDamage &damage, const std::shared_ptr &attacker, const std::shared_ptr &target); + float pvpLevelDifferenceDamageMultiplier(const std::shared_ptr &attacker, const std::shared_ptr &target); // Wheel of destiny combat helpers - void applyWheelOfDestinyHealing(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr target); - void applyWheelOfDestinyEffectsToDamage(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr target) const; - int32_t applyHealthChange(CombatDamage &damage, std::shared_ptr target) const; + void applyWheelOfDestinyHealing(CombatDamage &damage, const std::shared_ptr &attackerPlayer, std::shared_ptr target); + void applyWheelOfDestinyEffectsToDamage(CombatDamage &damage, const std::shared_ptr &attackerPlayer, const std::shared_ptr &target) const; + int32_t applyHealthChange(CombatDamage &damage, const std::shared_ptr &target) const; - bool combatChangeHealth(std::shared_ptr attacker, std::shared_ptr target, CombatDamage &damage, bool isEvent = false); - void applyCharmRune(std::shared_ptr targetMonster, std::shared_ptr attackerPlayer, std::shared_ptr target, const int32_t &realDamage) const; + bool combatChangeHealth(const std::shared_ptr &attacker, const std::shared_ptr &target, CombatDamage &damage, bool isEvent = false); + void applyCharmRune(const std::shared_ptr &targetMonster, const std::shared_ptr &attackerPlayer, const std::shared_ptr &target, const int32_t &realDamage) const; void applyManaLeech( - std::shared_ptr attackerPlayer, std::shared_ptr targetMonster, - std::shared_ptr target, const CombatDamage &damage, const int32_t &realDamage + const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster, + const std::shared_ptr &target, const CombatDamage &damage, const int32_t &realDamage ) const; void applyLifeLeech( - std::shared_ptr attackerPlayer, std::shared_ptr targetMonster, - std::shared_ptr target, const CombatDamage &damage, const int32_t &realDamage + const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetMonster, + const std::shared_ptr &target, const CombatDamage &damage, const int32_t &realDamage ) const; int32_t calculateLeechAmount(const int32_t &realDamage, const uint16_t &skillAmount, int targetsAffected) const; - bool combatChangeMana(std::shared_ptr attacker, std::shared_ptr target, CombatDamage &damage); + bool combatChangeMana(const std::shared_ptr &attacker, const std::shared_ptr &target, CombatDamage &damage); // Animation help functions - void addCreatureHealth(const std::shared_ptr target); - static void addCreatureHealth(const CreatureVector &spectators, const std::shared_ptr target); - void addPlayerMana(const std::shared_ptr target); - void addPlayerVocation(const std::shared_ptr target); + void addCreatureHealth(const std::shared_ptr &target); + static void addCreatureHealth(const CreatureVector &spectators, const std::shared_ptr &target); + void addPlayerMana(const std::shared_ptr &target); + void addPlayerVocation(const std::shared_ptr &target); void addMagicEffect(const Position &pos, uint16_t effect); static void addMagicEffect(const std::vector> &players, const Position &pos, uint16_t effect); static void addMagicEffect(const CreatureVector &spectators, const Position &pos, uint16_t effect); @@ -529,7 +528,7 @@ class Game { motdNum++; } - void sendOfflineTrainingDialog(std::shared_ptr player); + void sendOfflineTrainingDialog(const std::shared_ptr &player); const std::map> &getItemsPrice() const { return itemsPriceMap; @@ -551,18 +550,18 @@ class Game { return itemsClassifications; } - void addPlayer(std::shared_ptr player); - void removePlayer(std::shared_ptr player); + void addPlayer(const std::shared_ptr &player); + void removePlayer(const std::shared_ptr &player); - void addNpc(std::shared_ptr npc); - void removeNpc(std::shared_ptr npc); + void addNpc(const std::shared_ptr &npc); + void removeNpc(const std::shared_ptr &npc); - void addMonster(std::shared_ptr npc); - void removeMonster(std::shared_ptr npc); + void addMonster(const std::shared_ptr &npc); + void removeMonster(const std::shared_ptr &npc); std::shared_ptr getGuild(uint32_t id, bool allowOffline = false) const; std::shared_ptr getGuildByName(const std::string &name, bool allowOffline = false) const; - void addGuild(const std::shared_ptr guild); + void addGuild(const std::shared_ptr &guild); void removeGuild(uint32_t guildId); phmap::flat_hash_map, std::weak_ptr> browseFields; @@ -591,20 +590,20 @@ class Game { auto getTilesToClean() const { return tilesToClean; } - void addTileToClean(std::shared_ptr tile) { + void addTileToClean(const std::shared_ptr &tile) { tilesToClean.emplace(tile); } - void removeTileToClean(std::shared_ptr tile) { + void removeTileToClean(const std::shared_ptr &tile) { tilesToClean.erase(tile); } void clearTilesToClean() { tilesToClean.clear(); } - void playerInspectItem(std::shared_ptr player, const Position &pos); - void playerInspectItem(std::shared_ptr player, uint16_t itemId, uint8_t itemCount, bool cyclopedia); + void playerInspectItem(const std::shared_ptr &player, const Position &pos); + void playerInspectItem(const std::shared_ptr &player, uint16_t itemId, uint8_t itemCount, bool cyclopedia); - void addCharmRune(const std::shared_ptr charm) { + void addCharmRune(const std::shared_ptr &charm) { CharmList.push_back(charm); CharmList.shrink_to_fit(); } @@ -649,9 +648,9 @@ class Game { uint32_t makeFiendishMonster(uint32_t forgeableMonsterId = 0, bool createForgeableMonsters = false); uint32_t makeInfluencedMonster(); - bool addInfluencedMonster(std::shared_ptr monster); - void sendUpdateCreature(std::shared_ptr creature); - std::shared_ptr wrapItem(std::shared_ptr item, std::shared_ptr house); + bool addInfluencedMonster(const std::shared_ptr &monster); + void sendUpdateCreature(const std::shared_ptr &creature); + std::shared_ptr wrapItem(const std::shared_ptr &item, const std::shared_ptr &house); /** * @brief Adds a player to the unique login map. @@ -660,7 +659,7 @@ class Game { * * @param player A pointer to the Player object to add. */ - void addPlayerUniqueLogin(std::shared_ptr player); + void addPlayerUniqueLogin(const std::shared_ptr &player); /** * @brief Gets a player from the unique login map using their name. @@ -689,7 +688,7 @@ class Game { * * @param player A pointer to the Player object to remove. */ - void removePlayerUniqueLogin(std::shared_ptr player); + void removePlayerUniqueLogin(const std::shared_ptr &player); void playerCheckActivity(const std::string &playerName, int interval); /** @@ -702,10 +701,10 @@ class Game { * @param item Pointer to the item to be checked. * @return True if stash items can be retrieved, false otherwise. */ - bool tryRetrieveStashItems(std::shared_ptr player, std::shared_ptr item); + bool tryRetrieveStashItems(const std::shared_ptr &player, const std::shared_ptr &item); - ReturnValue beforeCreatureZoneChange(std::shared_ptr creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones, bool force = false) const; - void afterCreatureZoneChange(std::shared_ptr creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones) const; + ReturnValue beforeCreatureZoneChange(const std::shared_ptr &creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones, bool force = false) const; + void afterCreatureZoneChange(const std::shared_ptr &creature, const std::unordered_set> &fromZones, const std::unordered_set> &toZones) const; std::unique_ptr &getIOWheel(); const std::unique_ptr &getIOWheel() const; @@ -717,9 +716,9 @@ class Game { const std::vector &getHighscoreCategories() const; - void registerAchievement(uint16_t id, std::string name, std::string description, bool secret, uint8_t grade, uint8_t points); + void registerAchievement(uint16_t id, const std::string &name, std::string description, bool secret, uint8_t grade, uint8_t points); Achievement getAchievementById(uint16_t id); - Achievement getAchievementByName(std::string name); + Achievement getAchievementByName(const std::string &name); std::vector getSecretAchievements(); std::vector getPublicAchievements(); std::map getAchievements(); @@ -755,13 +754,13 @@ class Game { std::map forgeMonsterEventIds; std::unordered_set fiendishMonsters; std::unordered_set influencedMonsters; - void checkImbuements(); - bool playerSaySpell(std::shared_ptr player, SpeakClasses type, const std::string &text); - void playerWhisper(std::shared_ptr player, const std::string &text); - bool playerYell(std::shared_ptr player, const std::string &text); - bool playerSpeakTo(std::shared_ptr player, SpeakClasses type, const std::string &receiver, const std::string &text); - void playerSpeakToNpc(std::shared_ptr player, const std::string &text); - std::shared_ptr createPlayerTask(uint32_t delay, std::function f, std::string context) const; + void checkImbuements() const; + bool playerSaySpell(const std::shared_ptr &player, SpeakClasses type, const std::string &text); + void playerWhisper(const std::shared_ptr &player, const std::string &text); + bool playerYell(const std::shared_ptr &player, const std::string &text); + bool playerSpeakTo(const std::shared_ptr &player, SpeakClasses type, const std::string &receiver, const std::string &text); + void playerSpeakToNpc(const std::shared_ptr &player, const std::string &text); + std::shared_ptr createPlayerTask(uint32_t delay, std::function f, const std::string &context) const; /** * @brief Finds the managed container for loot or obtain based on the given parameters. @@ -775,7 +774,7 @@ class Game { * * @return Pointer to the managed container or nullptr if not found. */ - std::shared_ptr findManagedContainer(std::shared_ptr player, bool &fallbackConsumed, ObjectCategory_t category, bool isLootContainer); + std::shared_ptr findManagedContainer(const std::shared_ptr &player, bool &fallbackConsumed, ObjectCategory_t category, bool isLootContainer); /** * @brief Finds the next available sub-container within a container. @@ -796,7 +795,7 @@ class Game { * @param fallbackConsumed Reference to a boolean flag indicating whether a fallback has been consumed. * @return True if fallback logic was handled, false otherwise. */ - bool handleFallbackLogic(std::shared_ptr player, std::shared_ptr &lootContainer, ContainerIterator &containerIterator, const bool &fallbackConsumed); + bool handleFallbackLogic(const std::shared_ptr &player, std::shared_ptr &lootContainer, ContainerIterator &containerIterator, const bool &fallbackConsumed); /** * @brief Processes the movement or addition of an item to a loot container. @@ -807,7 +806,7 @@ class Game { * @param player Pointer to the player object. * @return Return value indicating success or error. */ - ReturnValue processMoveOrAddItemToLootContainer(std::shared_ptr item, std::shared_ptr lootContainer, uint32_t &remainderCount, std::shared_ptr player); + ReturnValue processMoveOrAddItemToLootContainer(const std::shared_ptr &item, const std::shared_ptr &lootContainer, uint32_t &remainderCount, const std::shared_ptr &player); /** * @brief Processes loot items and places them into the appropriate containers. @@ -818,7 +817,7 @@ class Game { * @param fallbackConsumed Reference to a boolean flag indicating whether a fallback has been consumed. * @return Return value indicating success or error. */ - ReturnValue processLootItems(std::shared_ptr player, std::shared_ptr lootContainer, std::shared_ptr item, bool &fallbackConsumed); + ReturnValue processLootItems(const std::shared_ptr &player, std::shared_ptr lootContainer, const std::shared_ptr &item, bool &fallbackConsumed); /** * @brief Internally collects loot or obtain items from a given item and places them into the managed container. @@ -828,7 +827,7 @@ class Game { * @param category Category of the item (default is OBJECTCATEGORY_DEFAULT). * @return Return value indicating success or error. */ - ReturnValue internalCollectManagedItems(std::shared_ptr player, std::shared_ptr item, ObjectCategory_t category = OBJECTCATEGORY_DEFAULT, bool isLootContainer = true); + ReturnValue internalCollectManagedItems(const std::shared_ptr &player, const std::shared_ptr &item, ObjectCategory_t category = OBJECTCATEGORY_DEFAULT, bool isLootContainer = true); /** * @brief Collects items from the reward chest. @@ -837,7 +836,7 @@ class Game { * @param maxMoveItems Maximum number of items to move (default is 0, which means no limit). * @return Return value indicating success or error. */ - ReturnValue collectRewardChestItems(std::shared_ptr player, uint32_t maxMoveItems = 0); + ReturnValue collectRewardChestItems(const std::shared_ptr &player, uint32_t maxMoveItems = 0); phmap::flat_hash_map queryCache; phmap::flat_hash_map highscoreCache; @@ -856,7 +855,7 @@ class Game { std::map mapLuaItemsStored; std::map BestiaryList; - std::string boostedCreature = ""; + std::string boostedCreature; std::vector> CharmList; std::vector> checkCreatureLists[EVENT_CREATURECOUNT]; @@ -919,53 +918,53 @@ class Game { std::vector itemsClassifications; - bool isTryingToStow(const Position &toPos, std::shared_ptr toCylinder) const; + bool isTryingToStow(const Position &toPos, const std::shared_ptr &toCylinder) const; void sendDamageMessageAndEffects( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, const Position &targetPos, - std::shared_ptr attackerPlayer, std::shared_ptr targetPlayer, TextMessage &message, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, const Position &targetPos, + const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetPlayer, TextMessage &message, const CreatureVector &spectators, int32_t realDamage ); - void updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, std::shared_ptr player) const; + void updatePlayerPartyHuntAnalyzer(const CombatDamage &damage, const std::shared_ptr &player) const; void sendEffects( - std::shared_ptr target, const CombatDamage &damage, const Position &targetPos, + const std::shared_ptr &target, const CombatDamage &damage, const Position &targetPos, TextMessage &message, const CreatureVector &spectators ); void sendMessages( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, - const Position &targetPos, std::shared_ptr attackerPlayer, std::shared_ptr targetPlayer, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, + const Position &targetPos, const std::shared_ptr &attackerPlayer, const std::shared_ptr &targetPlayer, TextMessage &message, const CreatureVector &spectators, int32_t realDamage ) const; bool shouldSendMessage(const TextMessage &message) const; void buildMessageAsAttacker( - std::shared_ptr target, const CombatDamage &damage, TextMessage &message, + const std::shared_ptr &target, const CombatDamage &damage, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const; void buildMessageAsTarget( - std::shared_ptr attacker, const CombatDamage &damage, std::shared_ptr attackerPlayer, - std::shared_ptr targetPlayer, TextMessage &message, std::stringstream &ss, + const std::shared_ptr &attacker, const CombatDamage &damage, const std::shared_ptr &attackerPlayer, + const std::shared_ptr &targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString ) const; void buildMessageAsSpectator( - std::shared_ptr attacker, std::shared_ptr target, const CombatDamage &damage, - std::shared_ptr targetPlayer, TextMessage &message, std::stringstream &ss, + const std::shared_ptr &attacker, const std::shared_ptr &target, const CombatDamage &damage, + const std::shared_ptr &targetPlayer, TextMessage &message, std::stringstream &ss, const std::string &damageString, std::string &spectatorMessage ) const; - void unwrapItem(std::shared_ptr item, uint16_t unWrapId, std::shared_ptr house, std::shared_ptr player); + void unwrapItem(const std::shared_ptr &item, uint16_t unWrapId, const std::shared_ptr &house, const std::shared_ptr &player); // Variable members (m_) std::unique_ptr m_IOWheel; void cacheQueryHighscore(const std::string &key, const std::string &query, uint32_t page, uint8_t entriesPerPage); - void processHighscoreResults(DBResult_ptr result, uint32_t playerID, uint8_t category, uint32_t vocation, uint8_t entriesPerPage); + void processHighscoreResults(const DBResult_ptr &result, uint32_t playerID, uint8_t category, uint32_t vocation, uint8_t entriesPerPage); std::string generateVocationConditionHighscore(uint32_t vocation); std::string generateHighscoreQueryForEntries(const std::string &categoryName, uint32_t page, uint8_t entriesPerPage, uint32_t vocation); diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index 44050100eb6..91b644e5cbd 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -47,7 +47,7 @@ std::shared_ptr Teleport::queryDestination(int32_t &, const std::share return getTeleport(); } -bool Teleport::checkInfinityLoop(std::shared_ptr destTile) { +bool Teleport::checkInfinityLoop(const std::shared_ptr &destTile) { if (!destTile) { return false; } @@ -95,7 +95,7 @@ void Teleport::addThing(int32_t, std::shared_ptr thing) { g_game().addMagicEffect(origPos, effect); g_game().addMagicEffect(destTile->getPosition(), effect); } - } else if (std::shared_ptr item = thing->getItem()) { + } else if (const auto item = thing->getItem()) { if (effect != CONST_ME_NONE) { g_game().addMagicEffect(destTile->getPosition(), effect); g_game().addMagicEffect(item->getPosition(), effect); diff --git a/src/game/movement/teleport.hpp b/src/game/movement/teleport.hpp index 9e26e1864cf..da647e9c486 100644 --- a/src/game/movement/teleport.hpp +++ b/src/game/movement/teleport.hpp @@ -20,7 +20,7 @@ class Teleport final : public Item, public Cylinder { return static_self_cast(); } - std::shared_ptr getCylinder() override final { + std::shared_ptr getCylinder() final { return getTeleport(); } @@ -32,10 +32,10 @@ class Teleport final : public Item, public Cylinder { return destPos; } void setDestPos(Position pos) { - destPos = std::move(pos); + destPos = pos; } - bool checkInfinityLoop(std::shared_ptr destTile); + bool checkInfinityLoop(const std::shared_ptr &destTile); // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; diff --git a/src/game/scheduling/dispatcher.cpp b/src/game/scheduling/dispatcher.cpp index dbbfc020be5..ff6cf86b98a 100644 --- a/src/game/scheduling/dispatcher.cpp +++ b/src/game/scheduling/dispatcher.cpp @@ -104,7 +104,7 @@ void Dispatcher::asyncWait(size_t requestSize, std::function &&f } void Dispatcher::executeEvents(const TaskGroup startGroup) { - for (uint_fast8_t groupId = static_cast(startGroup); groupId < static_cast(TaskGroup::Last); ++groupId) { + for (auto groupId = static_cast(startGroup); groupId < static_cast(TaskGroup::Last); ++groupId) { auto &tasks = m_tasks[groupId]; if (tasks.empty()) { return; @@ -155,8 +155,8 @@ void Dispatcher::executeScheduledEvents() { // Merge only async thread events with main dispatch events void Dispatcher::mergeAsyncEvents() { - constexpr uint8_t start = static_cast(TaskGroup::GenericParallel); - constexpr uint8_t end = static_cast(TaskGroup::Last); + constexpr auto start = static_cast(TaskGroup::GenericParallel); + constexpr auto end = static_cast(TaskGroup::Last); for (const auto &thread : threads) { std::scoped_lock lock(thread->mutex); @@ -171,7 +171,7 @@ void Dispatcher::mergeAsyncEvents() { // Merge thread events with main dispatch events void Dispatcher::mergeEvents() { - constexpr uint8_t serial = static_cast(TaskGroup::Serial); + constexpr auto serial = static_cast(TaskGroup::Serial); for (const auto &thread : threads) { std::scoped_lock lock(thread->mutex); diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 94b284c9316..19f8104c3bd 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -31,7 +31,7 @@ enum class DispatcherType : uint8_t { }; struct DispatcherContext { - bool isOn() const { + static bool isOn() { return OTSYS_TIME() != 0; } @@ -70,7 +70,7 @@ struct DispatcherContext { DispatcherType type = DispatcherType::None; TaskGroup group = TaskGroup::ThreadPool; - std::string_view taskName = ""; + std::string_view taskName; friend class Dispatcher; }; @@ -128,7 +128,7 @@ class Dispatcher { void stopEvent(uint64_t eventId); - const auto &context() const { + static const auto &context() { return dispacherContext; } @@ -150,11 +150,11 @@ class Dispatcher { inline void mergeAsyncEvents(); inline void mergeEvents(); - inline void executeEvents(const TaskGroup startGroup = TaskGroup::Serial); + inline void executeEvents(TaskGroup startGroup = TaskGroup::Serial); inline void executeScheduledEvents(); inline void executeSerialEvents(std::vector &tasks); - inline void executeParallelEvents(std::vector &tasks, const uint8_t groupId); + inline void executeParallelEvents(std::vector &tasks, uint8_t groupId); inline std::chrono::milliseconds timeUntilNextScheduledTask() const; inline void checkPendingTasks() { diff --git a/src/game/scheduling/events_scheduler.hpp b/src/game/scheduling/events_scheduler.hpp index 6c8233d8b0e..fe56aeb9a12 100644 --- a/src/game/scheduling/events_scheduler.hpp +++ b/src/game/scheduling/events_scheduler.hpp @@ -87,7 +87,7 @@ class EventsScheduler { std::vector eventScheduler; - std::string join(const std::vector &vec, const std::string &delim); + static std::string join(const std::vector &vec, const std::string &delim); }; constexpr auto g_eventsScheduler = EventsScheduler::getInstance; diff --git a/src/game/scheduling/task.cpp b/src/game/scheduling/task.cpp index 96355968bd1..758b86d9a3e 100644 --- a/src/game/scheduling/task.cpp +++ b/src/game/scheduling/task.cpp @@ -16,26 +16,6 @@ std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0; -Task::Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context) : - func(std::move(f)), context(context), utime(OTSYS_TIME()), expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { - if (this->context.empty()) { - g_logger().error("[{}]: task context cannot be empty!", __FUNCTION__); - return; - } - - assert(!this->context.empty() && "Context cannot be empty!"); -} - -Task::Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle /* = false*/, bool log /*= true*/) : - func(std::move(f)), context(context), utime(OTSYS_TIME() + delay), delay(delay), cycle(cycle), log(log) { - if (this->context.empty()) { - g_logger().error("[{}]: task context cannot be empty!", __FUNCTION__); - return; - } - - assert(!this->context.empty() && "Context cannot be empty!"); -} - bool Task::execute() const { metrics::task_latency measure(context); if (isCanceled()) { @@ -43,19 +23,18 @@ bool Task::execute() const { } if (hasExpired()) { - g_logger().info("The task '{}' has expired, it has not been executed in {}.", getContext(), expiration - utime); + g_logger().info("The task '{}' has expired, it has not been executed in {}. Function: {}", getContext(), expiration - utime, functionName); return false; } if (log) { if (hasTraceableContext()) { - g_logger().trace("Executing task {}.", getContext()); + g_logger().trace("Executing task {}. Function: {}", getContext(), functionName); } else { - g_logger().debug("Executing task {}.", getContext()); + g_logger().debug("Executing task {}. Function: {}", getContext(), functionName); } } func(); - return true; } diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index 9c561b41381..2508c1328aa 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -10,12 +10,29 @@ #pragma once #include "utils/tools.hpp" #include +#include class Task { public: - Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context); + Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, const std::source_location &location = std::source_location::current()) : + func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME()), + expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { + if (this->context.empty()) { + g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); + return; + } + assert(!this->context.empty() && "Context cannot be empty!"); + } - Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true); + Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true, const std::source_location &location = std::source_location::current()) : + func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME() + delay), delay(delay), + cycle(cycle), log(log) { + if (this->context.empty()) { + g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); + return; + } + assert(!this->context.empty() && "Context cannot be empty!"); + } ~Task() = default; @@ -24,10 +41,8 @@ class Task { if (++LAST_EVENT_ID == 0) { LAST_EVENT_ID = 1; } - id = LAST_EVENT_ID; } - return id; } @@ -39,6 +54,10 @@ class Task { return context; } + std::string_view getFunctionName() const { + return functionName; + } + auto getTime() const { return utime; } @@ -93,7 +112,6 @@ class Task { "SpawnNpc::checkSpawnNpc", "Webhook::run", "Protocol::sendRecvMessageCallback" }); - return tasksContext.contains(context); } @@ -105,6 +123,7 @@ class Task { std::function func = nullptr; std::string context; + std::string functionName; int64_t utime = 0; int64_t expiration = 0; diff --git a/src/game/zones/zone.hpp b/src/game/zones/zone.hpp index 82969a25792..ab30fd348af 100644 --- a/src/game/zones/zone.hpp +++ b/src/game/zones/zone.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "game/movement/position.hpp" #include "items/item.hpp" #include "creatures/creature.hpp" @@ -143,8 +145,8 @@ namespace weak { class Zone { public: - explicit Zone(const std::string &name, uint32_t id = 0) : - name(name), id(id) { } + explicit Zone(std::string name, uint32_t id = 0) : + name(std::move(name)), id(id) { } explicit Zone(uint32_t id) : id(id) { } @@ -199,7 +201,7 @@ class Zone { static std::shared_ptr addZone(const std::string &name, uint32_t id = 0); static std::shared_ptr getZone(const std::string &name); static std::shared_ptr getZone(uint32_t id); - static std::vector> getZones(const Position position); + static std::vector> getZones(Position position); static std::vector> getZones(); static void refreshAll() { for (const auto &[_, zone] : zones) { diff --git a/src/io/fileloader.hpp b/src/io/fileloader.hpp index 2069487202f..83cb601e027 100644 --- a/src/io/fileloader.hpp +++ b/src/io/fileloader.hpp @@ -22,9 +22,9 @@ namespace OTB { Node &operator=(const Node &) = delete; std::list children; - mio::mmap_source::const_iterator propsBegin; - mio::mmap_source::const_iterator propsEnd; - uint8_t type; + mio::mmap_source::const_iterator propsBegin {}; + mio::mmap_source::const_iterator propsEnd {}; + uint8_t type {}; enum NodeChar : uint8_t { ESCAPE = 0xFD, START = 0xFE, diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index 764d4641469..9bce6c0015d 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -18,20 +18,20 @@ #include "enums/account_errors.hpp" #include "utils/tools.hpp" -void IOLoginDataLoad::loadItems(ItemsMap &itemsMap, DBResult_ptr result, const std::shared_ptr &player) { +void IOLoginDataLoad::loadItems(ItemsMap &itemsMap, const DBResult_ptr &result, const std::shared_ptr &player) { try { do { - uint32_t sid = result->getNumber("sid"); - uint32_t pid = result->getNumber("pid"); - uint16_t type = result->getNumber("itemtype"); - uint16_t count = result->getNumber("count"); + auto sid = result->getNumber("sid"); + auto pid = result->getNumber("pid"); + auto type = result->getNumber("itemtype"); + auto count = result->getNumber("count"); unsigned long attrSize; const char* attr = result->getStream("attributes", attrSize); PropStream propStream; propStream.init(attr, attrSize); try { - std::shared_ptr item = Item::CreateItem(type, count); + const auto item = Item::CreateItem(type, count); if (item) { if (!item->unserializeAttr(propStream)) { g_logger().warn("[{}] - Failed to deserialize item attributes {}, from player {}, from account id {}", __FUNCTION__, item->getID(), player->getName(), player->getAccountId()); @@ -51,7 +51,7 @@ void IOLoginDataLoad::loadItems(ItemsMap &itemsMap, DBResult_ptr result, const s } } -bool IOLoginDataLoad::preLoadPlayer(std::shared_ptr player, const std::string &name) { +bool IOLoginDataLoad::preLoadPlayer(const std::shared_ptr &player, const std::string &name) { Database &db = Database::getInstance(); std::ostringstream query; @@ -105,7 +105,7 @@ bool IOLoginDataLoad::preLoadPlayer(std::shared_ptr player, const std::s return true; } -bool IOLoginDataLoad::loadPlayerFirst(std::shared_ptr player, DBResult_ptr result) { +bool IOLoginDataLoad::loadPlayerFirst(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return false; @@ -141,7 +141,7 @@ bool IOLoginDataLoad::loadPlayerFirst(std::shared_ptr player, DBResult_p player->manaMax = result->getNumber("manamax"); player->magLevel = result->getNumber("maglevel"); uint64_t nextManaCount = player->vocation->getReqMana(player->magLevel + 1); - uint64_t manaSpent = result->getNumber("manaspent"); + auto manaSpent = result->getNumber("manaspent"); if (manaSpent > nextManaCount) { manaSpent = 0; } @@ -187,13 +187,13 @@ bool IOLoginDataLoad::loadPlayerFirst(std::shared_ptr player, DBResult_p return true; } -void IOLoginDataLoad::loadPlayerExperience(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerExperience(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; } - uint64_t experience = result->getNumber("experience"); + auto experience = result->getNumber("experience"); uint64_t currExpCount = Player::getExpForLevel(player->level); uint64_t nextExpCount = Player::getExpForLevel(player->level + 1); @@ -210,7 +210,7 @@ void IOLoginDataLoad::loadPlayerExperience(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerBlessings(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerBlessings(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -221,7 +221,7 @@ void IOLoginDataLoad::loadPlayerBlessings(std::shared_ptr player, DBResu } } -void IOLoginDataLoad::loadPlayerConditions(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerConditions(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -241,7 +241,7 @@ void IOLoginDataLoad::loadPlayerConditions(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerDefaultOutfit(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerDefaultOutfit(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -272,7 +272,7 @@ void IOLoginDataLoad::loadPlayerDefaultOutfit(std::shared_ptr player, DB player->currentOutfit = player->defaultOutfit; } -void IOLoginDataLoad::loadPlayerSkullSystem(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerSkullSystem(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -284,7 +284,7 @@ void IOLoginDataLoad::loadPlayerSkullSystem(std::shared_ptr player, DBRe // ensure that we round up the number of ticks player->skullTicks = (skullSeconds + 2); - uint16_t skull = result->getNumber("skull"); + auto skull = result->getNumber("skull"); if (skull == SKULL_RED) { player->skull = SKULL_RED; } else if (skull == SKULL_BLACK) { @@ -294,7 +294,7 @@ void IOLoginDataLoad::loadPlayerSkullSystem(std::shared_ptr player, DBRe } } -void IOLoginDataLoad::loadPlayerSkill(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerSkill(const std::shared_ptr &player, const DBResult_ptr &result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -303,8 +303,8 @@ void IOLoginDataLoad::loadPlayerSkill(std::shared_ptr player, DBResult_p static const std::array skillNames = { "skill_fist", "skill_club", "skill_sword", "skill_axe", "skill_dist", "skill_shielding", "skill_fishing", "skill_critical_hit_chance", "skill_critical_hit_damage", "skill_life_leech_chance", "skill_life_leech_amount", "skill_mana_leech_chance", "skill_mana_leech_amount" }; static const std::array skillNameTries = { "skill_fist_tries", "skill_club_tries", "skill_sword_tries", "skill_axe_tries", "skill_dist_tries", "skill_shielding_tries", "skill_fishing_tries", "skill_critical_hit_chance_tries", "skill_critical_hit_damage_tries", "skill_life_leech_chance_tries", "skill_life_leech_amount_tries", "skill_mana_leech_chance_tries", "skill_mana_leech_amount_tries" }; for (size_t i = 0; i < skillNames.size(); ++i) { - uint16_t skillLevel = result->getNumber(skillNames[i]); - uint64_t skillTries = result->getNumber(skillNameTries[i]); + auto skillLevel = result->getNumber(skillNames[i]); + auto skillTries = result->getNumber(skillNameTries[i]); uint64_t nextSkillTries = player->vocation->getReqSkillTries(static_cast(i), skillLevel + 1); if (skillTries > nextSkillTries) { skillTries = 0; @@ -316,7 +316,7 @@ void IOLoginDataLoad::loadPlayerSkill(std::shared_ptr player, DBResult_p } } -void IOLoginDataLoad::loadPlayerKills(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerKills(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -327,7 +327,7 @@ void IOLoginDataLoad::loadPlayerKills(std::shared_ptr player, DBResult_p query << "SELECT `player_id`, `time`, `target`, `unavenged` FROM `player_kills` WHERE `player_id` = " << player->getGUID(); if ((result = db.storeQuery(query.str()))) { do { - time_t killTime = result->getNumber("time"); + auto killTime = result->getNumber("time"); if ((time(nullptr) - killTime) <= g_configManager().getNumber(FRAG_TIME, __FUNCTION__)) { player->unjustifiedKills.emplace_back(result->getNumber("target"), killTime, result->getNumber("unavenged")); } @@ -335,7 +335,7 @@ void IOLoginDataLoad::loadPlayerKills(std::shared_ptr player, DBResult_p } } -void IOLoginDataLoad::loadPlayerGuild(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerGuild(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -345,8 +345,8 @@ void IOLoginDataLoad::loadPlayerGuild(std::shared_ptr player, DBResult_p std::ostringstream query; query << "SELECT `guild_id`, `rank_id`, `nick` FROM `guild_membership` WHERE `player_id` = " << player->getGUID(); if ((result = db.storeQuery(query.str()))) { - uint32_t guildId = result->getNumber("guild_id"); - uint32_t playerRankId = result->getNumber("rank_id"); + auto guildId = result->getNumber("guild_id"); + auto playerRankId = result->getNumber("rank_id"); player->guildNick = result->getString("nick"); auto guild = g_game().getGuild(guildId); @@ -385,7 +385,7 @@ void IOLoginDataLoad::loadPlayerGuild(std::shared_ptr player, DBResult_p } } -void IOLoginDataLoad::loadPlayerStashItems(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerStashItems(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -401,7 +401,7 @@ void IOLoginDataLoad::loadPlayerStashItems(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerBestiaryCharms(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerBestiaryCharms(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -454,7 +454,7 @@ void IOLoginDataLoad::loadPlayerBestiaryCharms(std::shared_ptr player, D } } -void IOLoginDataLoad::loadPlayerInstantSpellList(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerInstantSpellList(const std::shared_ptr &player, DBResult_ptr result) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; @@ -470,7 +470,7 @@ void IOLoginDataLoad::loadPlayerInstantSpellList(std::shared_ptr player, } } -void IOLoginDataLoad::loadPlayerInventoryItems(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerInventoryItems(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -488,9 +488,9 @@ void IOLoginDataLoad::loadPlayerInventoryItems(std::shared_ptr player, D if ((result = db.storeQuery(query.str()))) { loadItems(inventoryItems, result, player); - for (ItemsMap::const_reverse_iterator it = inventoryItems.rbegin(), end = inventoryItems.rend(); it != end; ++it) { + for (auto it = inventoryItems.rbegin(), end = inventoryItems.rend(); it != end; ++it) { const std::pair, int32_t> &pair = it->second; - std::shared_ptr item = pair.first; + const auto item = pair.first; if (!item) { continue; } @@ -518,7 +518,7 @@ void IOLoginDataLoad::loadPlayerInventoryItems(std::shared_ptr player, D if (!oldProtocol) { auto cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); if (cid > 0) { - openContainersList.emplace_back(std::make_pair(cid, itemContainer)); + openContainersList.emplace_back(cid, itemContainer); } } for (bool isLootContainer : { true, false }) { @@ -552,7 +552,7 @@ void IOLoginDataLoad::loadPlayerInventoryItems(std::shared_ptr player, D } } -void IOLoginDataLoad::loadPlayerStoreInbox(std::shared_ptr player) { +void IOLoginDataLoad::loadPlayerStoreInbox(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; @@ -563,7 +563,7 @@ void IOLoginDataLoad::loadPlayerStoreInbox(std::shared_ptr player) { } } -void IOLoginDataLoad::loadRewardItems(std::shared_ptr player) { +void IOLoginDataLoad::loadRewardItems(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; @@ -581,7 +581,7 @@ void IOLoginDataLoad::loadRewardItems(std::shared_ptr player) { } } -void IOLoginDataLoad::loadPlayerDepotItems(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerDepotItems(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -593,9 +593,9 @@ void IOLoginDataLoad::loadPlayerDepotItems(std::shared_ptr player, DBRes query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_depotitems` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; if ((result = db.storeQuery(query.str()))) { loadItems(depotItems, result, player); - for (ItemsMap::const_reverse_iterator it = depotItems.rbegin(), end = depotItems.rend(); it != end; ++it) { + for (auto it = depotItems.rbegin(), end = depotItems.rend(); it != end; ++it) { const std::pair, int32_t> &pair = it->second; - std::shared_ptr item = pair.first; + const auto item = pair.first; int32_t pid = pair.second; if (pid >= 0 && pid < 100) { @@ -620,7 +620,7 @@ void IOLoginDataLoad::loadPlayerDepotItems(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerInboxItems(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerInboxItems(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -633,9 +633,9 @@ void IOLoginDataLoad::loadPlayerInboxItems(std::shared_ptr player, DBRes ItemsMap inboxItems; loadItems(inboxItems, result, player); - for (ItemsMap::const_reverse_iterator it = inboxItems.rbegin(), end = inboxItems.rend(); it != end; ++it) { + for (auto it = inboxItems.rbegin(), end = inboxItems.rend(); it != end; ++it) { const std::pair, int32_t> &pair = it->second; - std::shared_ptr item = pair.first; + const auto item = pair.first; int32_t pid = pair.second; if (pid >= 0 && pid < 100) { player->getInbox()->internalAddThing(item); @@ -656,7 +656,7 @@ void IOLoginDataLoad::loadPlayerInboxItems(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerStorageMap(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerStorageMap(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -672,7 +672,7 @@ void IOLoginDataLoad::loadPlayerStorageMap(std::shared_ptr player, DBRes } } -void IOLoginDataLoad::loadPlayerVip(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerVip(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -710,7 +710,7 @@ void IOLoginDataLoad::loadPlayerVip(std::shared_ptr player, DBResult_ptr } } -void IOLoginDataLoad::loadPlayerPreyClass(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerPreyClass(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -757,7 +757,7 @@ void IOLoginDataLoad::loadPlayerPreyClass(std::shared_ptr player, DBResu } } -void IOLoginDataLoad::loadPlayerTaskHuntingClass(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerTaskHuntingClass(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -807,7 +807,7 @@ void IOLoginDataLoad::loadPlayerTaskHuntingClass(std::shared_ptr player, } } -void IOLoginDataLoad::loadPlayerForgeHistory(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerForgeHistory(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -828,7 +828,7 @@ void IOLoginDataLoad::loadPlayerForgeHistory(std::shared_ptr player, DBR } } -void IOLoginDataLoad::loadPlayerBosstiary(std::shared_ptr player, DBResult_ptr result) { +void IOLoginDataLoad::loadPlayerBosstiary(const std::shared_ptr &player, DBResult_ptr result) { if (!result || !player) { g_logger().warn("[IOLoginData::loadPlayer] - Player or Result nullptr: {}", __FUNCTION__); return; @@ -860,7 +860,7 @@ void IOLoginDataLoad::loadPlayerBosstiary(std::shared_ptr player, DBResu } } -void IOLoginDataLoad::bindRewardBag(std::shared_ptr player, ItemsMap &rewardItemsMap) { +void IOLoginDataLoad::bindRewardBag(const std::shared_ptr &player, ItemsMap &rewardItemsMap) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; @@ -882,13 +882,13 @@ void IOLoginDataLoad::bindRewardBag(std::shared_ptr player, ItemsMap &re void IOLoginDataLoad::insertItemsIntoRewardBag(const ItemsMap &rewardItemsMap) { for (const auto &it : std::views::reverse(rewardItemsMap)) { const std::pair, int32_t> &pair = it.second; - std::shared_ptr item = pair.first; + const auto item = pair.first; int32_t pid = pair.second; if (pid == 0) { break; } - ItemsMap::const_iterator it2 = rewardItemsMap.find(pid); + auto it2 = rewardItemsMap.find(pid); if (it2 == rewardItemsMap.end()) { continue; } @@ -900,7 +900,7 @@ void IOLoginDataLoad::insertItemsIntoRewardBag(const ItemsMap &rewardItemsMap) { } } -void IOLoginDataLoad::loadPlayerInitializeSystem(std::shared_ptr player) { +void IOLoginDataLoad::loadPlayerInitializeSystem(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; @@ -919,7 +919,7 @@ void IOLoginDataLoad::loadPlayerInitializeSystem(std::shared_ptr player) player->initializeTaskHunting(); } -void IOLoginDataLoad::loadPlayerUpdateSystem(std::shared_ptr player) { +void IOLoginDataLoad::loadPlayerUpdateSystem(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::loadPlayer] - Player nullptr: {}", __FUNCTION__); return; diff --git a/src/io/functions/iologindata_load_player.hpp b/src/io/functions/iologindata_load_player.hpp index 07a478d2dc3..3dc1147e927 100644 --- a/src/io/functions/iologindata_load_player.hpp +++ b/src/io/functions/iologindata_load_player.hpp @@ -13,38 +13,38 @@ class IOLoginDataLoad : public IOLoginData { public: - static bool loadPlayerFirst(std::shared_ptr player, DBResult_ptr result); - static bool preLoadPlayer(std::shared_ptr player, const std::string &name); - static void loadPlayerExperience(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerBlessings(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerConditions(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerDefaultOutfit(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerSkullSystem(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerSkill(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerKills(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerGuild(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerStashItems(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerBestiaryCharms(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerInstantSpellList(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerInventoryItems(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerStoreInbox(std::shared_ptr player); - static void loadPlayerDepotItems(std::shared_ptr player, DBResult_ptr result); - static void loadRewardItems(std::shared_ptr player); - static void loadPlayerInboxItems(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerStorageMap(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerVip(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerPreyClass(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerTaskHuntingClass(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerForgeHistory(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerBosstiary(std::shared_ptr player, DBResult_ptr result); - static void loadPlayerInitializeSystem(std::shared_ptr player); - static void loadPlayerUpdateSystem(std::shared_ptr player); + static bool loadPlayerFirst(const std::shared_ptr &player, const DBResult_ptr &result); + static bool preLoadPlayer(const std::shared_ptr &player, const std::string &name); + static void loadPlayerExperience(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerBlessings(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerConditions(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerDefaultOutfit(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerSkullSystem(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerSkill(const std::shared_ptr &player, const DBResult_ptr &result); + static void loadPlayerKills(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerGuild(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerStashItems(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerBestiaryCharms(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerInstantSpellList(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerInventoryItems(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerStoreInbox(const std::shared_ptr &player); + static void loadPlayerDepotItems(const std::shared_ptr &player, DBResult_ptr result); + static void loadRewardItems(const std::shared_ptr &player); + static void loadPlayerInboxItems(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerStorageMap(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerVip(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerPreyClass(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerTaskHuntingClass(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerForgeHistory(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerBosstiary(const std::shared_ptr &player, DBResult_ptr result); + static void loadPlayerInitializeSystem(const std::shared_ptr &player); + static void loadPlayerUpdateSystem(const std::shared_ptr &player); private: using ItemsMap = std::map, uint32_t>>; - static void bindRewardBag(std::shared_ptr player, ItemsMap &rewardItemsMap); + static void bindRewardBag(const std::shared_ptr &player, ItemsMap &rewardItemsMap); static void insertItemsIntoRewardBag(const ItemsMap &rewardItemsMap); - static void loadItems(ItemsMap &itemsMap, DBResult_ptr result, const std::shared_ptr &player); + static void loadItems(ItemsMap &itemsMap, const DBResult_ptr &result, const std::shared_ptr &player); }; diff --git a/src/io/functions/iologindata_save_player.cpp b/src/io/functions/iologindata_save_player.cpp index eccb88c8229..9e6f879dcf9 100644 --- a/src/io/functions/iologindata_save_player.cpp +++ b/src/io/functions/iologindata_save_player.cpp @@ -12,7 +12,7 @@ #include "io/functions/iologindata_save_player.hpp" #include "game/game.hpp" -bool IOLoginDataSave::saveItems(std::shared_ptr player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &propWriteStream) { +bool IOLoginDataSave::saveItems(const std::shared_ptr &player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &propWriteStream) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -30,7 +30,7 @@ bool IOLoginDataSave::saveItems(std::shared_ptr player, const ItemBlockL const auto openContainers = player->getOpenContainers(); for (const auto &it : itemList) { int32_t pid = it.first; - std::shared_ptr item = it.second; + const auto item = it.second; ++runningId; // Update container attributes if necessary @@ -91,7 +91,7 @@ bool IOLoginDataSave::saveItems(std::shared_ptr player, const ItemBlockL } // Loop through items in container - for (std::shared_ptr item : container->getItemList()) { + for (const std::shared_ptr &item : container->getItemList()) { if (!item) { continue; // Check for null item } @@ -148,7 +148,7 @@ bool IOLoginDataSave::saveItems(std::shared_ptr player, const ItemBlockL return true; } -bool IOLoginDataSave::savePlayerFirst(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerFirst(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -314,7 +314,7 @@ bool IOLoginDataSave::savePlayerFirst(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerStash(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerStash(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -343,7 +343,7 @@ bool IOLoginDataSave::savePlayerStash(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerSpells(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerSpells(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -372,7 +372,7 @@ bool IOLoginDataSave::savePlayerSpells(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerKills(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerKills(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -401,7 +401,7 @@ bool IOLoginDataSave::savePlayerKills(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerBestiarySystem(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerBestiarySystem(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -451,7 +451,7 @@ bool IOLoginDataSave::savePlayerBestiarySystem(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerItem(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerItem(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -470,7 +470,7 @@ bool IOLoginDataSave::savePlayerItem(std::shared_ptr player) { ItemBlockList itemList; for (int32_t slotId = CONST_SLOT_FIRST; slotId <= CONST_SLOT_LAST; ++slotId) { - std::shared_ptr item = player->inventory[slotId]; + const auto item = player->inventory[slotId]; if (item) { itemList.emplace_back(slotId, item); } @@ -483,7 +483,7 @@ bool IOLoginDataSave::savePlayerItem(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerDepotItems(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerDepotItems(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -505,7 +505,7 @@ bool IOLoginDataSave::savePlayerDepotItems(std::shared_ptr player) { DBInsert depotQuery("INSERT INTO `player_depotitems` (`player_id`, `pid`, `sid`, `itemtype`, `count`, `attributes`) VALUES "); for (const auto &[pid, depotChest] : player->depotChests) { - for (std::shared_ptr item : depotChest->getItemList()) { + for (const std::shared_ptr &item : depotChest->getItemList()) { depotList.emplace_back(pid, item); } } @@ -518,7 +518,7 @@ bool IOLoginDataSave::savePlayerDepotItems(std::shared_ptr player) { return true; } -bool IOLoginDataSave::saveRewardItems(std::shared_ptr player) { +bool IOLoginDataSave::saveRewardItems(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -552,7 +552,7 @@ bool IOLoginDataSave::saveRewardItems(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerInbox(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerInbox(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -580,7 +580,7 @@ bool IOLoginDataSave::savePlayerInbox(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerPreyClass(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerPreyClass(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -634,7 +634,7 @@ bool IOLoginDataSave::savePlayerPreyClass(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerTaskHuntingClass(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerTaskHuntingClass(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -686,7 +686,7 @@ bool IOLoginDataSave::savePlayerTaskHuntingClass(std::shared_ptr player) return true; } -bool IOLoginDataSave::savePlayerForgeHistory(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerForgeHistory(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -720,7 +720,7 @@ bool IOLoginDataSave::savePlayerForgeHistory(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerBosstiary(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerBosstiary(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; @@ -764,7 +764,7 @@ bool IOLoginDataSave::savePlayerBosstiary(std::shared_ptr player) { return true; } -bool IOLoginDataSave::savePlayerStorage(std::shared_ptr player) { +bool IOLoginDataSave::savePlayerStorage(const std::shared_ptr &player) { if (!player) { g_logger().warn("[IOLoginData::savePlayer] - Player nullptr: {}", __FUNCTION__); return false; diff --git a/src/io/functions/iologindata_save_player.hpp b/src/io/functions/iologindata_save_player.hpp index bbd44105de6..8a35db73d11 100644 --- a/src/io/functions/iologindata_save_player.hpp +++ b/src/io/functions/iologindata_save_player.hpp @@ -13,20 +13,20 @@ class IOLoginDataSave : public IOLoginData { public: - static bool savePlayerFirst(std::shared_ptr player); - static bool savePlayerStash(std::shared_ptr player); - static bool savePlayerSpells(std::shared_ptr player); - static bool savePlayerKills(std::shared_ptr player); - static bool savePlayerBestiarySystem(std::shared_ptr player); - static bool savePlayerItem(std::shared_ptr player); - static bool savePlayerDepotItems(std::shared_ptr player); - static bool saveRewardItems(std::shared_ptr player); - static bool savePlayerInbox(std::shared_ptr player); - static bool savePlayerPreyClass(std::shared_ptr player); - static bool savePlayerTaskHuntingClass(std::shared_ptr player); - static bool savePlayerForgeHistory(std::shared_ptr player); - static bool savePlayerBosstiary(std::shared_ptr player); - static bool savePlayerStorage(std::shared_ptr player); + static bool savePlayerFirst(const std::shared_ptr &player); + static bool savePlayerStash(const std::shared_ptr &player); + static bool savePlayerSpells(const std::shared_ptr &player); + static bool savePlayerKills(const std::shared_ptr &player); + static bool savePlayerBestiarySystem(const std::shared_ptr &player); + static bool savePlayerItem(const std::shared_ptr &player); + static bool savePlayerDepotItems(const std::shared_ptr &player); + static bool saveRewardItems(const std::shared_ptr &player); + static bool savePlayerInbox(const std::shared_ptr &player); + static bool savePlayerPreyClass(const std::shared_ptr &player); + static bool savePlayerTaskHuntingClass(const std::shared_ptr &player); + static bool savePlayerForgeHistory(const std::shared_ptr &player); + static bool savePlayerBosstiary(const std::shared_ptr &player); + static bool savePlayerStorage(const std::shared_ptr &player); protected: using ItemBlockList = std::list>>; @@ -34,5 +34,5 @@ class IOLoginDataSave : public IOLoginData { using ItemRewardList = std::list>>; using ItemInboxList = std::list>>; - static bool saveItems(std::shared_ptr player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &stream); + static bool saveItems(const std::shared_ptr &player, const ItemBlockList &itemList, DBInsert &query_insert, PropWriteStream &stream); }; diff --git a/src/io/io_bosstiary.cpp b/src/io/io_bosstiary.cpp index 2f625cdb7cc..5ac3cb83d9c 100644 --- a/src/io/io_bosstiary.cpp +++ b/src/io/io_bosstiary.cpp @@ -27,7 +27,7 @@ void IOBosstiary::loadBoostedBoss() { return; } - uint16_t date = result->getNumber("date"); + auto date = result->getNumber("date"); auto timeNow = getTimeNow(); auto time = localtime(&timeNow); auto today = time->tm_mday; @@ -61,12 +61,12 @@ void IOBosstiary::loadBoostedBoss() { } // Check if not have archfoe registered boss - if (bossInfo.size() == 0) { + if (bossInfo.empty()) { g_logger().error("Failed to boost a boss. There is no boss registered with the Archfoe Rarity."); return; } - uint16_t oldBossRace = result->getNumber("raceid"); + auto oldBossRace = result->getNumber("raceid"); while (true) { uint32_t randomIndex = uniform_random(0, static_cast(bossInfo.size())); auto it = std::next(bossInfo.begin(), randomIndex); @@ -169,7 +169,7 @@ std::shared_ptr IOBosstiary::getMonsterTypeByBossRaceId(uint16_t ra return nullptr; } -void IOBosstiary::addBosstiaryKill(std::shared_ptr player, const std::shared_ptr mtype, uint32_t amount /*= 1*/) const { +void IOBosstiary::addBosstiaryKill(const std::shared_ptr &player, const std::shared_ptr &mtype, uint32_t amount /*= 1*/) const { if (!player || !mtype) { return; } @@ -268,7 +268,7 @@ std::vector IOBosstiary::getBosstiaryFinished(const std::shared_ptr player, uint16_t bossId) const { +uint8_t IOBosstiary::getBossCurrentLevel(const std::shared_ptr &player, uint16_t bossId) const { if (bossId == 0 || !player) { return 0; } diff --git a/src/io/io_bosstiary.hpp b/src/io/io_bosstiary.hpp index 84d9f0955e0..31153a46f0b 100644 --- a/src/io/io_bosstiary.hpp +++ b/src/io/io_bosstiary.hpp @@ -60,11 +60,11 @@ class IOBosstiary { uint16_t getBoostedBossId() const; std::shared_ptr getMonsterTypeByBossRaceId(uint16_t raceId) const; - void addBosstiaryKill(std::shared_ptr player, const std::shared_ptr mtype, uint32_t amount = 1) const; + void addBosstiaryKill(const std::shared_ptr &player, const std::shared_ptr &mtype, uint32_t amount = 1) const; uint16_t calculateLootBonus(uint32_t bossPoints) const; uint32_t calculateBossPoints(uint16_t lootBonus) const; std::vector getBosstiaryFinished(const std::shared_ptr &player, uint8_t level = 1) const; - uint8_t getBossCurrentLevel(std::shared_ptr player, uint16_t bossId) const; + uint8_t getBossCurrentLevel(const std::shared_ptr &player, uint16_t bossId) const; uint32_t calculteRemoveBoss(uint8_t removeTimes) const; const std::vector &getBossRaceKillStages(BosstiaryRarity_t race) const; diff --git a/src/io/iobestiary.cpp b/src/io/iobestiary.cpp index 9cd964e7c7c..b339a75fc9a 100644 --- a/src/io/iobestiary.cpp +++ b/src/io/iobestiary.cpp @@ -18,7 +18,7 @@ SoftSingleton IOBestiary::instanceTracker("IOBestiary"); -bool IOBestiary::parseCharmCombat(const std::shared_ptr charm, std::shared_ptr player, std::shared_ptr target, int32_t realDamage, bool dueToPotion, bool checkArmor) { +bool IOBestiary::parseCharmCombat(const std::shared_ptr &charm, const std::shared_ptr &player, const std::shared_ptr &target, int32_t realDamage, bool dueToPotion, bool checkArmor) { if (!charm || !player || !target) { return false; } @@ -136,7 +136,7 @@ std::map IOBestiary::findRaceByName(const std::string &ra return race_list; } -uint8_t IOBestiary::getKillStatus(const std::shared_ptr mtype, uint32_t killAmount) const { +uint8_t IOBestiary::getKillStatus(const std::shared_ptr &mtype, uint32_t killAmount) const { if (killAmount < mtype->info.bestiaryFirstUnlock) { return 1; } else if (killAmount < mtype->info.bestiarySecondUnlock) { @@ -147,7 +147,7 @@ uint8_t IOBestiary::getKillStatus(const std::shared_ptr mtype, uint return 4; } -void IOBestiary::resetCharmRuneCreature(std::shared_ptr player, const std::shared_ptr charm) { +void IOBestiary::resetCharmRuneCreature(const std::shared_ptr &player, const std::shared_ptr &charm) const { if (!player || !charm) { return; } @@ -157,7 +157,7 @@ void IOBestiary::resetCharmRuneCreature(std::shared_ptr player, const st player->parseRacebyCharm(charm->id, true, 0); } -void IOBestiary::setCharmRuneCreature(std::shared_ptr player, const std::shared_ptr charm, uint16_t raceid) { +void IOBestiary::setCharmRuneCreature(const std::shared_ptr &player, const std::shared_ptr &charm, uint16_t raceid) const { if (!player || !charm) { return; } @@ -167,14 +167,14 @@ void IOBestiary::setCharmRuneCreature(std::shared_ptr player, const std: player->setUsedRunesBit(Toggle); } -std::list IOBestiary::getCharmUsedRuneBitAll(std::shared_ptr player) { +std::list IOBestiary::getCharmUsedRuneBitAll(const std::shared_ptr &player) { int32_t input = player->getUsedRunesBit(); int8_t i = 0; std::list rtn; while (input != 0) { if ((input & 1) == 1) { - charmRune_t tmpcharm = static_cast(i); + auto tmpcharm = static_cast(i); rtn.push_front(tmpcharm); } input = input >> 1; @@ -183,7 +183,7 @@ std::list IOBestiary::getCharmUsedRuneBitAll(std::shared_ptr player, BestiaryType_t race) const { +uint16_t IOBestiary::getBestiaryRaceUnlocked(const std::shared_ptr &player, BestiaryType_t race) const { if (!player) { return 0; } @@ -200,7 +200,7 @@ uint16_t IOBestiary::getBestiaryRaceUnlocked(std::shared_ptr player, Bes return count; } -void IOBestiary::addCharmPoints(std::shared_ptr player, uint16_t amount, bool negative /*= false*/) { +void IOBestiary::addCharmPoints(const std::shared_ptr &player, uint16_t amount, bool negative /*= false*/) { if (!player) { return; } @@ -214,7 +214,7 @@ void IOBestiary::addCharmPoints(std::shared_ptr player, uint16_t amount, player->setCharmPoints(myCharms); } -void IOBestiary::addBestiaryKill(std::shared_ptr player, const std::shared_ptr mtype, uint32_t amount /*= 1*/) { +void IOBestiary::addBestiaryKill(const std::shared_ptr &player, const std::shared_ptr &mtype, uint32_t amount /*= 1*/) { uint16_t raceid = mtype->info.raceid; if (raceid == 0 || !player || !mtype) { return; @@ -241,7 +241,7 @@ void IOBestiary::addBestiaryKill(std::shared_ptr player, const std::shar player->refreshCyclopediaMonsterTracker(); } -charmRune_t IOBestiary::getCharmFromTarget(std::shared_ptr player, const std::shared_ptr mtype) { +charmRune_t IOBestiary::getCharmFromTarget(const std::shared_ptr &player, const std::shared_ptr &mtype) { if (!player || !mtype) { return CHARM_NONE; } @@ -258,7 +258,7 @@ charmRune_t IOBestiary::getCharmFromTarget(std::shared_ptr player, const return CHARM_NONE; } -bool IOBestiary::hasCharmUnlockedRuneBit(const std::shared_ptr charm, int32_t input) const { +bool IOBestiary::hasCharmUnlockedRuneBit(const std::shared_ptr &charm, int32_t input) const { if (!charm) { return false; } @@ -266,7 +266,7 @@ bool IOBestiary::hasCharmUnlockedRuneBit(const std::shared_ptr charm, int return ((input & charm->binary) != 0); } -int32_t IOBestiary::bitToggle(int32_t input, const std::shared_ptr charm, bool on) const { +int32_t IOBestiary::bitToggle(int32_t input, const std::shared_ptr &charm, bool on) const { if (!charm) { return CHARM_NONE; } @@ -283,7 +283,7 @@ int32_t IOBestiary::bitToggle(int32_t input, const std::shared_ptr charm, } } -void IOBestiary::sendBuyCharmRune(std::shared_ptr player, charmRune_t runeID, uint8_t action, uint16_t raceid) { +void IOBestiary::sendBuyCharmRune(const std::shared_ptr &player, charmRune_t runeID, uint8_t action, uint16_t raceid) { const auto charm = getBestiaryCharm(runeID); if (!player || !charm) { return; @@ -345,7 +345,7 @@ void IOBestiary::sendBuyCharmRune(std::shared_ptr player, charmRune_t ru player->BestiarysendCharms(); } -std::map IOBestiary::getMonsterElements(const std::shared_ptr mtype) const { +std::map IOBestiary::getMonsterElements(const std::shared_ptr &mtype) const { std::map defaultMap = {}; for (uint8_t i = 0; i <= 7; i++) { defaultMap[i] = 100; @@ -383,7 +383,7 @@ std::map IOBestiary::getMonsterElements(const std::shared_ptr< return defaultMap; } -std::map IOBestiary::getBestiaryKillCountByMonsterIDs(std::shared_ptr player, std::map mtype_list) const { +std::map IOBestiary::getBestiaryKillCountByMonsterIDs(const std::shared_ptr &player, const std::map &mtype_list) const { std::map raceMonsters = {}; for (const auto &it : mtype_list) { uint16_t raceid = it.first; diff --git a/src/io/iobestiary.hpp b/src/io/iobestiary.hpp index a521ce68852..6baef14c89d 100644 --- a/src/io/iobestiary.hpp +++ b/src/io/iobestiary.hpp @@ -26,7 +26,7 @@ class Charm { std::string name; charmRune_t id = CHARM_NONE; std::string description; - charm_t type; + charm_t type {}; uint16_t points = 0; int32_t binary = 0; std::string cancelMsg; @@ -55,29 +55,29 @@ class IOBestiary { } std::shared_ptr getBestiaryCharm(charmRune_t activeCharm, bool force = false) const; - void addBestiaryKill(std::shared_ptr player, const std::shared_ptr mtype, uint32_t amount = 1); - bool parseCharmCombat(const std::shared_ptr charm, std::shared_ptr player, std::shared_ptr target, int32_t realDamage, bool dueToPotion = false, bool checkArmor = false); - void addCharmPoints(std::shared_ptr player, uint16_t amount, bool negative = false); - void sendBuyCharmRune(std::shared_ptr player, charmRune_t runeID, uint8_t action, uint16_t raceid); - void setCharmRuneCreature(std::shared_ptr player, const std::shared_ptr charm, uint16_t raceid); - void resetCharmRuneCreature(std::shared_ptr player, const std::shared_ptr charm); + void addBestiaryKill(const std::shared_ptr &player, const std::shared_ptr &mtype, uint32_t amount = 1); + bool parseCharmCombat(const std::shared_ptr &charm, const std::shared_ptr &player, const std::shared_ptr &target, int32_t realDamage, bool dueToPotion = false, bool checkArmor = false); + void addCharmPoints(const std::shared_ptr &player, uint16_t amount, bool negative = false); + void sendBuyCharmRune(const std::shared_ptr &player, charmRune_t runeID, uint8_t action, uint16_t raceid); + void setCharmRuneCreature(const std::shared_ptr &player, const std::shared_ptr &charm, uint16_t raceid) const; + void resetCharmRuneCreature(const std::shared_ptr &player, const std::shared_ptr &charm) const; int8_t calculateDifficult(uint32_t chance) const; - uint8_t getKillStatus(const std::shared_ptr mtype, uint32_t killAmount) const; + uint8_t getKillStatus(const std::shared_ptr &mtype, uint32_t killAmount) const; - uint16_t getBestiaryRaceUnlocked(std::shared_ptr player, BestiaryType_t race) const; + uint16_t getBestiaryRaceUnlocked(const std::shared_ptr &player, BestiaryType_t race) const; - int32_t bitToggle(int32_t input, const std::shared_ptr charm, bool on) const; + int32_t bitToggle(int32_t input, const std::shared_ptr &charm, bool on) const; - bool hasCharmUnlockedRuneBit(const std::shared_ptr charm, int32_t input) const; + bool hasCharmUnlockedRuneBit(const std::shared_ptr &charm, int32_t input) const; - std::list getCharmUsedRuneBitAll(std::shared_ptr player); + std::list getCharmUsedRuneBitAll(const std::shared_ptr &player); std::vector getBestiaryFinished(const std::shared_ptr &player) const; - charmRune_t getCharmFromTarget(std::shared_ptr player, const std::shared_ptr mtype); + charmRune_t getCharmFromTarget(const std::shared_ptr &player, const std::shared_ptr &mtype); - std::map getBestiaryKillCountByMonsterIDs(std::shared_ptr player, std::map mtype_list) const; - std::map getMonsterElements(const std::shared_ptr mtype) const; + std::map getBestiaryKillCountByMonsterIDs(const std::shared_ptr &player, const std::map &mtype_list) const; + std::map getMonsterElements(const std::shared_ptr &mtype) const; std::map findRaceByName(const std::string &race, bool Onlystring = true, BestiaryType_t raceNumber = BESTY_RACE_NONE) const; private: diff --git a/src/io/ioguild.cpp b/src/io/ioguild.cpp index 99e1e750676..25d0cfdf736 100644 --- a/src/io/ioguild.cpp +++ b/src/io/ioguild.cpp @@ -33,7 +33,7 @@ std::shared_ptr IOGuild::loadGuild(uint32_t guildId) { return nullptr; } -void IOGuild::saveGuild(const std::shared_ptr guild) { +void IOGuild::saveGuild(const std::shared_ptr &guild) { if (!guild) { return; } @@ -68,7 +68,7 @@ void IOGuild::getWarList(uint32_t guildId, GuildWarVector &guildWarVector) { } do { - uint32_t guild1 = result->getNumber("guild1"); + auto guild1 = result->getNumber("guild1"); if (guildId != guild1) { guildWarVector.push_back(guild1); } else { diff --git a/src/io/ioguild.hpp b/src/io/ioguild.hpp index cc450841bd1..52a8e7c1cba 100644 --- a/src/io/ioguild.hpp +++ b/src/io/ioguild.hpp @@ -15,7 +15,7 @@ using GuildWarVector = std::vector; class IOGuild { public: static std::shared_ptr loadGuild(uint32_t guildId); - static void saveGuild(const std::shared_ptr guild); + static void saveGuild(const std::shared_ptr &guild); static uint32_t getGuildIdByName(const std::string &name); static void getWarList(uint32_t guildId, GuildWarVector &guildWarVector); }; diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index 132cead6412..231e0980278 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "io/iologindata.hpp" @@ -90,21 +92,21 @@ void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) { } // The boolean "disableIrrelevantInfo" will deactivate the loading of information that is not relevant to the preload, for example, forge, bosstiary, etc. None of this we need to access if the player is offline -bool IOLoginData::loadPlayerById(std::shared_ptr player, uint32_t id, bool disableIrrelevantInfo /* = true*/) { +bool IOLoginData::loadPlayerById(const std::shared_ptr &player, uint32_t id, bool disableIrrelevantInfo /* = true*/) { Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `players` WHERE `id` = " << id; return loadPlayer(player, db.storeQuery(query.str()), disableIrrelevantInfo); } -bool IOLoginData::loadPlayerByName(std::shared_ptr player, const std::string &name, bool disableIrrelevantInfo /* = true*/) { +bool IOLoginData::loadPlayerByName(const std::shared_ptr &player, const std::string &name, bool disableIrrelevantInfo /* = true*/) { Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `players` WHERE `name` = " << db.escapeString(name); return loadPlayer(player, db.storeQuery(query.str()), disableIrrelevantInfo); } -bool IOLoginData::loadPlayer(std::shared_ptr player, DBResult_ptr result, bool disableIrrelevantInfo /* = false*/) { +bool IOLoginData::loadPlayer(const std::shared_ptr &player, const DBResult_ptr &result, bool disableIrrelevantInfo /* = false*/) { if (!result || !player) { std::string nullptrType = !result ? "Result" : "Player"; g_logger().warn("[{}] - {} is nullptr", __FUNCTION__, nullptrType); @@ -198,7 +200,7 @@ bool IOLoginData::loadPlayer(std::shared_ptr player, DBResult_ptr result } } -bool IOLoginData::savePlayer(std::shared_ptr player) { +bool IOLoginData::savePlayer(const std::shared_ptr &player) { bool success = DBTransaction::executeWithinTransaction([player]() { return savePlayerGuard(player); }); @@ -210,7 +212,7 @@ bool IOLoginData::savePlayer(std::shared_ptr player) { return success; } -bool IOLoginData::savePlayerGuard(std::shared_ptr player) { +bool IOLoginData::savePlayerGuard(const std::shared_ptr &player) { if (!player) { throw DatabaseException("Player nullptr in function: " + std::string(__FUNCTION__)); } @@ -283,7 +285,7 @@ std::string IOLoginData::getNameByGuid(uint32_t guid) { query << "SELECT `name` FROM `players` WHERE `id` = " << guid; DBResult_ptr result = Database::getInstance().storeQuery(query.str()); if (!result) { - return std::string(); + return {}; } return result->getString("name"); } diff --git a/src/io/iologindata.hpp b/src/io/iologindata.hpp index 1451cf89778..230f7d5fa77 100644 --- a/src/io/iologindata.hpp +++ b/src/io/iologindata.hpp @@ -20,10 +20,10 @@ class IOLoginData { static bool gameWorldAuthentication(const std::string &accountDescriptor, const std::string &sessionOrPassword, std::string &characterName, uint32_t &accountId, bool oldProcotol); static uint8_t getAccountType(uint32_t accountId); static void updateOnlineStatus(uint32_t guid, bool login); - static bool loadPlayerById(std::shared_ptr player, uint32_t id, bool disableIrrelevantInfo = true); - static bool loadPlayerByName(std::shared_ptr player, const std::string &name, bool disableIrrelevantInfo = true); - static bool loadPlayer(std::shared_ptr player, DBResult_ptr result, bool disableIrrelevantInfo = false); - static bool savePlayer(std::shared_ptr player); + static bool loadPlayerById(const std::shared_ptr &player, uint32_t id, bool disableIrrelevantInfo = true); + static bool loadPlayerByName(const std::shared_ptr &player, const std::string &name, bool disableIrrelevantInfo = true); + static bool loadPlayer(const std::shared_ptr &player, const DBResult_ptr &result, bool disableIrrelevantInfo = false); + static bool savePlayer(const std::shared_ptr &player); static uint32_t getGuidByName(const std::string &name); static bool getGuidByNameEx(uint32_t &guid, bool &specialVip, std::string &name); static std::string getNameByGuid(uint32_t guid); @@ -44,5 +44,5 @@ class IOLoginData { static void removeGuidVIPGroupEntry(uint32_t accountId, uint32_t guid); private: - static bool savePlayerGuard(std::shared_ptr player); + static bool savePlayerGuard(const std::shared_ptr &player); }; diff --git a/src/io/iomap.cpp b/src/io/iomap.cpp index c17978e8d1d..8277e179515 100644 --- a/src/io/iomap.cpp +++ b/src/io/iomap.cpp @@ -135,7 +135,7 @@ void IOMap::parseTileArea(FileStream &stream, Map &map, const Position &pos) { const uint16_t x = base_x + tileCoordsX + pos.x; const uint16_t y = base_y + tileCoordsY + pos.y; - const uint8_t z = static_cast(base_z + pos.z); + const auto z = static_cast(base_z + pos.z); if (tileType == OTBM_HOUSETILE) { tile->houseId = stream.getU32(); diff --git a/src/io/iomap.hpp b/src/io/iomap.hpp index 78fcc23191f..711a2db961e 100644 --- a/src/io/iomap.hpp +++ b/src/io/iomap.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "declarations.hpp" #include "config/configmanager.hpp" @@ -157,8 +159,8 @@ class IOMap { class IOMapException : public std::exception { public: - explicit IOMapException(const std::string &msg) : - message(msg) { } + explicit IOMapException(std::string msg) : + message(std::move(msg)) { } const char* what() const noexcept override { return message.c_str(); diff --git a/src/io/iomapserialize.cpp b/src/io/iomapserialize.cpp index e2a367c4ec4..94508b827e9 100644 --- a/src/io/iomapserialize.cpp +++ b/src/io/iomapserialize.cpp @@ -110,7 +110,7 @@ bool IOMapSerialize::SaveHouseItemsGuard() { return true; } -bool IOMapSerialize::loadContainer(PropStream &propStream, std::shared_ptr container) { +bool IOMapSerialize::loadContainer(PropStream &propStream, const std::shared_ptr &container) { while (container->serializationCount > 0) { if (!loadItem(propStream, container)) { g_logger().warn("Deserialization error for container item: {}", container->getID()); @@ -127,7 +127,7 @@ bool IOMapSerialize::loadContainer(PropStream &propStream, std::shared_ptr parent, bool isHouseItem /*= false*/) { +bool IOMapSerialize::loadItem(PropStream &propStream, const std::shared_ptr &parent, bool isHouseItem /*= false*/) { uint16_t id; if (!propStream.read(id)) { return false; @@ -216,7 +216,7 @@ bool IOMapSerialize::loadItem(PropStream &propStream, std::shared_ptr return true; } -void IOMapSerialize::saveItem(PropWriteStream &stream, std::shared_ptr item) { +void IOMapSerialize::saveItem(PropWriteStream &stream, const std::shared_ptr &item) { std::shared_ptr container = item->getContainer(); // Write ID & props @@ -235,7 +235,7 @@ void IOMapSerialize::saveItem(PropWriteStream &stream, std::shared_ptr ite stream.write(0x00); // attr end } -void IOMapSerialize::saveTile(PropWriteStream &stream, std::shared_ptr tile) { +void IOMapSerialize::saveTile(PropWriteStream &stream, const std::shared_ptr &tile) { const TileItemVector* tileItems = tile->getItemList(); if (!tileItems) { return; @@ -266,7 +266,7 @@ void IOMapSerialize::saveTile(PropWriteStream &stream, std::shared_ptr til stream.write(tilePosition.z); stream.write(count); - for (std::shared_ptr item : items) { + for (const std::shared_ptr &item : items) { saveItem(stream, item); } } @@ -284,8 +284,8 @@ bool IOMapSerialize::loadHouseInfo() { auto houseId = result->getNumber("id"); const auto house = g_game().map.houses.getHouse(houseId); if (house) { - uint32_t owner = result->getNumber("owner"); - int32_t newOwner = result->getNumber("new_owner"); + auto owner = result->getNumber("owner"); + auto newOwner = result->getNumber("new_owner"); // Transfer house owner auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && newOwner >= 0) { @@ -372,7 +372,7 @@ bool IOMapSerialize::SaveHouseInfoGuard() { listText.clear(); } - for (std::shared_ptr door : house->getDoors()) { + for (const std::shared_ptr &door : house->getDoors()) { if (door->getAccessList(listText) && !listText.empty()) { query << house->getId() << ',' << door->getDoorId() << ',' << db.escapeString(listText) << ',' << version; if (!listUpdate.addRow(query)) { diff --git a/src/io/iomapserialize.hpp b/src/io/iomapserialize.hpp index 08cbac01128..ae1c9ccb5f1 100644 --- a/src/io/iomapserialize.hpp +++ b/src/io/iomapserialize.hpp @@ -21,9 +21,9 @@ class IOMapSerialize { private: static bool SaveHouseInfoGuard(); static bool SaveHouseItemsGuard(); - static void saveItem(PropWriteStream &stream, std::shared_ptr item); - static void saveTile(PropWriteStream &stream, std::shared_ptr tile); + static void saveItem(PropWriteStream &stream, const std::shared_ptr &item); + static void saveTile(PropWriteStream &stream, const std::shared_ptr &tile); - static bool loadContainer(PropStream &propStream, std::shared_ptr container); - static bool loadItem(PropStream &propStream, std::shared_ptr parent, bool isHouseItem = false); + static bool loadContainer(PropStream &propStream, const std::shared_ptr &container); + static bool loadItem(PropStream &propStream, const std::shared_ptr &parent, bool isHouseItem = false); }; diff --git a/src/io/iomarket.cpp b/src/io/iomarket.cpp index a0253e2ea01..b074b07cbaf 100644 --- a/src/io/iomarket.cpp +++ b/src/io/iomarket.cpp @@ -130,7 +130,7 @@ HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t p } do { - HistoryMarketOffer offer; + HistoryMarketOffer offer {}; offer.itemId = result->getNumber("itemtype"); offer.amount = result->getNumber("amount"); offer.price = result->getNumber("price"); @@ -149,7 +149,7 @@ HistoryMarketOfferList IOMarket::getOwnHistory(MarketAction_t action, uint32_t p return offerList; } -void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { +void IOMarket::processExpiredOffers(const DBResult_ptr &result, bool) { if (!result) { return; } @@ -159,8 +159,8 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { continue; } - const uint32_t playerId = result->getNumber("player_id"); - const uint16_t amount = result->getNumber("amount"); + const auto playerId = result->getNumber("player_id"); + const auto amount = result->getNumber("amount"); auto tier = getTierFromDatabaseTable(result->getString("tier")); if (result->getNumber("sale") == 1) { const ItemType &itemType = Item::items[result->getNumber("itemtype")]; @@ -168,7 +168,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { continue; } - std::shared_ptr player = g_game().getPlayerByGUID(playerId, true); + const auto player = g_game().getPlayerByGUID(playerId, true); if (!player) { continue; } @@ -177,7 +177,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { uint16_t tmpAmount = amount; while (tmpAmount > 0) { uint16_t stackCount = std::min(100, tmpAmount); - std::shared_ptr item = Item::CreateItem(itemType.id, stackCount); + const auto item = Item::CreateItem(itemType.id, stackCount); if (g_game().internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { g_logger().error("[{}] Ocurred an error to add item with id {} to player {}", __FUNCTION__, itemType.id, player->getName()); @@ -199,7 +199,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { } for (uint16_t i = 0; i < amount; ++i) { - std::shared_ptr item = Item::CreateItem(itemType.id, subType); + const auto item = Item::CreateItem(itemType.id, subType); if (g_game().internalAddItem(player->getInbox(), item, INDEX_WHEREEVER, FLAG_NOLIMIT) != RETURNVALUE_NOERROR) { break; } @@ -216,7 +216,7 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { } else { uint64_t totalPrice = result->getNumber("price") * amount; - std::shared_ptr player = g_game().getPlayerByGUID(playerId); + const auto player = g_game().getPlayerByGUID(playerId); if (player) { player->setBankBalance(player->getBankBalance() + totalPrice); } else { diff --git a/src/io/iomarket.hpp b/src/io/iomarket.hpp index 4292651fb47..5a078bbc1cb 100644 --- a/src/io/iomarket.hpp +++ b/src/io/iomarket.hpp @@ -26,7 +26,7 @@ class IOMarket { static MarketOfferList getOwnOffers(MarketAction_t action, uint32_t playerId); static HistoryMarketOfferList getOwnHistory(MarketAction_t action, uint32_t playerId); - static void processExpiredOffers(DBResult_ptr result, bool); + static void processExpiredOffers(const DBResult_ptr &result, bool); static void checkExpiredOffers(); static uint32_t getPlayerOfferCount(uint32_t playerId); diff --git a/src/io/ioprey.cpp b/src/io/ioprey.cpp index 93a91abade1..0860a79b114 100644 --- a/src/io/ioprey.cpp +++ b/src/io/ioprey.cpp @@ -246,7 +246,7 @@ void TaskHuntingSlot::reloadReward() { } // Prey/Task hunting global class -void IOPrey::checkPlayerPreys(std::shared_ptr player, uint8_t amount) const { +void IOPrey::checkPlayerPreys(const std::shared_ptr &player, uint8_t amount) const { if (!player) { return; } @@ -290,7 +290,7 @@ void IOPrey::checkPlayerPreys(std::shared_ptr player, uint8_t amount) co } } -void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const { +void IOPrey::parsePreyAction(const std::shared_ptr &player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const { const auto &slot = player->getPreySlotById(slotId); if (!slot || slot->state == PreyDataState_Locked) { player->sendMessageDialog("To unlock this prey slot first you must buy it on store."); @@ -396,7 +396,7 @@ void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, player->reloadPreySlot(slotId); } -void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const { +void IOPrey::parseTaskHuntingAction(const std::shared_ptr &player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const { const auto &slot = player->getTaskHuntingSlotById(slotId); if (!slot || slot->state == PreyTaskDataState_Locked) { player->sendMessageDialog("To unlock this task hunting slot first you must buy it on store."); diff --git a/src/io/ioprey.hpp b/src/io/ioprey.hpp index 221f2ce5562..e0bf96b278f 100644 --- a/src/io/ioprey.hpp +++ b/src/io/ioprey.hpp @@ -225,10 +225,10 @@ class IOPrey { return inject(); } - void checkPlayerPreys(std::shared_ptr player, uint8_t amount) const; - void parsePreyAction(std::shared_ptr player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const; + void checkPlayerPreys(const std::shared_ptr &player, uint8_t amount) const; + void parsePreyAction(const std::shared_ptr &player, PreySlot_t slotId, PreyAction_t action, PreyOption_t option, int8_t index, uint16_t raceId) const; - void parseTaskHuntingAction(std::shared_ptr player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const; + void parseTaskHuntingAction(const std::shared_ptr &player, PreySlot_t slotId, PreyTaskAction_t action, bool upgrade, uint16_t raceId) const; void initializeTaskHuntOptions(); const std::unique_ptr &getTaskRewardOption(const std::unique_ptr &slot) const; diff --git a/src/items/bed.cpp b/src/items/bed.cpp index 4b38be3b474..a2af5481de0 100644 --- a/src/items/bed.cpp +++ b/src/items/bed.cpp @@ -79,7 +79,7 @@ std::shared_ptr BedItem::getNextBedItem() { return tile->getBedItem(); } -bool BedItem::canUse(std::shared_ptr player) { +bool BedItem::canUse(const std::shared_ptr &player) { if ((player == nullptr) || (house == nullptr) || !player->isPremium()) { return false; } @@ -117,7 +117,7 @@ bool BedItem::canUse(std::shared_ptr player) { return true; } -bool BedItem::isBedComplete(std::shared_ptr nextBedItem) { +bool BedItem::isBedComplete(const std::shared_ptr &nextBedItem) { const ItemType &it = Item::items[id]; if (nextBedItem == nullptr) { @@ -134,7 +134,7 @@ bool BedItem::isBedComplete(std::shared_ptr nextBedItem) { return it.bedPartOf == nextBedItem->getID(); } -bool BedItem::trySleep(std::shared_ptr player) { +bool BedItem::trySleep(const std::shared_ptr &player) { if (!house || player->isRemoved()) { return false; } @@ -150,7 +150,7 @@ bool BedItem::trySleep(std::shared_ptr player) { return true; } -bool BedItem::sleep(std::shared_ptr player) { +bool BedItem::sleep(const std::shared_ptr &player) { if (house == nullptr) { return false; } @@ -191,7 +191,7 @@ bool BedItem::sleep(std::shared_ptr player) { return true; } -void BedItem::wakeUp(std::shared_ptr player) { +void BedItem::wakeUp(const std::shared_ptr &player) { if (house == nullptr) { return; } @@ -232,7 +232,7 @@ void BedItem::wakeUp(std::shared_ptr player) { } } -void BedItem::regeneratePlayer(std::shared_ptr player) const { +void BedItem::regeneratePlayer(const std::shared_ptr &player) const { const uint32_t sleptTime = time(nullptr) - sleepStart; std::shared_ptr condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); @@ -258,7 +258,7 @@ void BedItem::regeneratePlayer(std::shared_ptr player) const { player->changeSoul(soulRegen); } -void BedItem::updateAppearance(std::shared_ptr player) { +void BedItem::updateAppearance(const std::shared_ptr &player) { const ItemType &it = Item::items[id]; if (it.type == ITEM_TYPE_BED) { if ((player != nullptr) && it.transformToOnUse[player->getSex()] != 0) { @@ -275,7 +275,7 @@ void BedItem::updateAppearance(std::shared_ptr player) { } } -void BedItem::internalSetSleeper(std::shared_ptr player) { +void BedItem::internalSetSleeper(const std::shared_ptr &player) { std::string desc_str = player->getName() + " is sleeping there."; sleeperGUID = player->getGUID(); diff --git a/src/items/bed.hpp b/src/items/bed.hpp index 2aeb6e38e5b..7b62f6edad8 100644 --- a/src/items/bed.hpp +++ b/src/items/bed.hpp @@ -37,25 +37,25 @@ class BedItem final : public Item { house = h; } - bool canUse(std::shared_ptr player); + bool canUse(const std::shared_ptr &player); - bool isBedComplete(std::shared_ptr nextBedItem); + bool isBedComplete(const std::shared_ptr &nextBedItem); - bool trySleep(std::shared_ptr player); - bool sleep(std::shared_ptr player); - void wakeUp(std::shared_ptr player); + bool trySleep(const std::shared_ptr &player); + bool sleep(const std::shared_ptr &player); + void wakeUp(const std::shared_ptr &player); std::shared_ptr getNextBedItem(); friend class MapCache; private: - void updateAppearance(std::shared_ptr player); - void regeneratePlayer(std::shared_ptr player) const; - void internalSetSleeper(std::shared_ptr player); + void updateAppearance(const std::shared_ptr &player); + void regeneratePlayer(const std::shared_ptr &player) const; + void internalSetSleeper(const std::shared_ptr &player); void internalRemoveSleeper(); std::shared_ptr house; - uint64_t sleepStart; - uint32_t sleeperGUID; + uint64_t sleepStart {}; + uint32_t sleeperGUID {}; }; diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index 6c526a8500a..c4bf4a23c37 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -45,7 +45,7 @@ std::shared_ptr Container::create(uint16_t type, uint16_t size, bool return std::make_shared(type, size, unlocked, pagination); } -std::shared_ptr Container::create(std::shared_ptr tile) { +std::shared_ptr Container::create(const std::shared_ptr &tile) { auto container = std::make_shared(ITEM_BROWSEFIELD, 30, false, true); TileItemVector* itemVector = tile->getItemList(); if (itemVector) { @@ -67,7 +67,7 @@ Container::~Container() { g_game().browseFields.erase(getParent()->getTile()); } - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { item->setParent(getParent()); } } @@ -75,7 +75,7 @@ Container::~Container() { std::shared_ptr Container::clone() const { std::shared_ptr clone = std::static_pointer_cast(Item::clone()); - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { clone->addItem(item->clone()); } clone->totalWeight = totalWeight; @@ -123,22 +123,22 @@ bool Container::hasParent() { return getID() != ITEM_BROWSEFIELD && !isPlayer; } -void Container::addItem(std::shared_ptr item) { +void Container::addItem(const std::shared_ptr &item) { itemlist.push_back(item); item->setParent(getContainer()); } StashContainerList Container::getStowableItems() const { StashContainerList toReturnList; - for (auto item : itemlist) { - if (item->getContainer() != NULL) { + for (const auto &item : itemlist) { + if (item->getContainer() != nullptr) { auto subContainer = item->getContainer()->getStowableItems(); - for (auto subContItem : subContainer) { + for (const auto &subContItem : subContainer) { std::shared_ptr containerItem = subContItem.first; - toReturnList.push_back(std::pair, uint32_t>(containerItem, static_cast(containerItem->getItemCount()))); + toReturnList.emplace_back(containerItem, static_cast(containerItem->getItemCount())); } } else if (item->isItemStorable()) { - toReturnList.push_back(std::pair, uint32_t>(item, static_cast(item->getItemCount()))); + toReturnList.emplace_back(item, static_cast(item->getItemCount())); } } @@ -178,7 +178,7 @@ bool Container::unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, return false; } - std::shared_ptr item = Item::CreateItem(id, itemPosition); + const auto item = Item::CreateItem(id, itemPosition); if (!item) { continue; } @@ -225,7 +225,7 @@ std::string Container::getContentDescription(bool oldProtocol) { std::ostringstream &Container::getContentDescription(std::ostringstream &os, bool sendColoredMessage) { bool firstitem = true; for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; std::shared_ptr container = item->getContainer(); if (container && !container->empty()) { @@ -272,7 +272,7 @@ std::deque> Container::getStoreInboxFilteredItems() const const auto enumName = getAttribute(ItemAttribute_t::STORE_INBOX_CATEGORY); ItemDeque storeInboxFilteredList; if (isStoreInboxFiltered()) { - for (std::shared_ptr item : getItemList()) { + for (const std::shared_ptr &item : getItemList()) { auto itemId = item->getID(); auto attribute = item->getCustomAttribute("unWrapId"); uint16_t unWrapId = attribute ? static_cast(attribute->getInteger()) : 0; @@ -320,7 +320,7 @@ std::shared_ptr Container::getFilteredItemByIndex(size_t index) const { return nullptr; } - auto item = filteredItems[index]; + const auto &item = filteredItems[index]; auto it = std::find(itemlist.begin(), itemlist.end(), item); if (it == itemlist.end()) { @@ -356,7 +356,7 @@ uint32_t Container::getContainerHoldingCount() { return counter; } -bool Container::isHoldingItem(std::shared_ptr item) { +bool Container::isHoldingItem(const std::shared_ptr &item) { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { if (*it == item) { return true; @@ -367,7 +367,7 @@ bool Container::isHoldingItem(std::shared_ptr item) { bool Container::isHoldingItemWithId(const uint16_t id) { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { - std::shared_ptr item = *it; + const auto item = *it; if (item->getID() == id) { return true; } @@ -398,7 +398,7 @@ bool Container::isBrowseFieldAndHoldsRewardChest() { return getID() == ITEM_BROWSEFIELD && isHoldingItemWithId(ITEM_REWARD_CHEST); } -void Container::onAddContainerItem(std::shared_ptr item) { +void Container::onAddContainerItem(const std::shared_ptr &item) { auto spectators = Spectators().find(getPosition(), false, 2, 2, 2, 2); // send to client @@ -412,7 +412,7 @@ void Container::onAddContainerItem(std::shared_ptr item) { } } -void Container::onUpdateContainerItem(uint32_t index, std::shared_ptr oldItem, std::shared_ptr newItem) { +void Container::onUpdateContainerItem(uint32_t index, const std::shared_ptr &oldItem, const std::shared_ptr &newItem) { auto spectators = Spectators().find(getPosition(), false, 2, 2, 2, 2); // send to client @@ -426,7 +426,7 @@ void Container::onUpdateContainerItem(uint32_t index, std::shared_ptr oldI } } -void Container::onRemoveContainerItem(uint32_t index, std::shared_ptr item) { +void Container::onRemoveContainerItem(uint32_t index, const std::shared_ptr &item) { auto spectators = Spectators().find(getPosition(), false, 2, 2, 2, 2); // send change to client @@ -452,7 +452,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr & return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr item = addThing->getItem(); + const auto item = addThing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -531,7 +531,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr & } ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { maxQueryCount = 0; return RETURNVALUE_NOTPOSSIBLE; @@ -550,7 +550,7 @@ ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr if (index == INDEX_WHEREEVER) { // Iterate through every item and check how much free stackable slots there is. uint32_t slotIndex = 0; - for (std::shared_ptr containerItem : itemlist) { + for (const std::shared_ptr &containerItem : itemlist) { if (containerItem != item && containerItem->equals(item) && containerItem->getItemCount() < containerItem->getStackSize()) { uint32_t remainder = (containerItem->getStackSize() - containerItem->getItemCount()); if (queryAdd(slotIndex++, item, remainder, flags) == RETURNVALUE_NOERROR) { @@ -586,7 +586,7 @@ ReturnValue Container::queryRemove(const std::shared_ptr &thing, uint32_t return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { g_logger().debug("{} - Item is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -640,7 +640,7 @@ std::shared_ptr Container::queryDestination(int32_t &index, const std: *destItem = nullptr; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return getContainer(); } @@ -667,7 +667,7 @@ std::shared_ptr Container::queryDestination(int32_t &index, const std: // try find a suitable item to stack with uint32_t n = 0; - for (std::shared_ptr listItem : itemlist) { + for (const std::shared_ptr &listItem : itemlist) { if (listItem != item && listItem->equals(item) && listItem->getItemCount() < listItem->getStackSize()) { *destItem = listItem; index = n; @@ -692,7 +692,7 @@ void Container::addThing(int32_t index, std::shared_ptr thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -707,7 +707,7 @@ void Container::addThing(int32_t index, std::shared_ptr thing) { } } -void Container::addItemBack(std::shared_ptr item) { +void Container::addItemBack(const std::shared_ptr &item) { addItem(item); updateItemWeight(item->getWeight()); @@ -723,7 +723,7 @@ void Container::updateThing(std::shared_ptr thing, uint16_t itemId, uint3 return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -740,7 +740,7 @@ void Container::updateThing(std::shared_ptr thing, uint16_t itemId, uint3 } void Container::replaceThing(uint32_t index, std::shared_ptr thing) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -763,7 +763,7 @@ void Container::replaceThing(uint32_t index, std::shared_ptr thing) { } void Container::removeThing(std::shared_ptr thing, uint32_t count) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -798,7 +798,7 @@ void Container::removeThing(std::shared_ptr thing, uint32_t count) { int32_t Container::getThingIndex(std::shared_ptr thing) const { int32_t index = 0; - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { if (item == thing) { return index; } @@ -817,7 +817,7 @@ size_t Container::getLastIndex() const { uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType /* = -1*/) const { uint32_t count = 0; - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { if (item->getID() == itemId) { count += countByType(item, subType); } @@ -826,7 +826,7 @@ uint32_t Container::getItemTypeCount(uint16_t itemId, int32_t subType /* = -1*/) } std::map &Container::getAllItemTypeCount(std::map &countMap) const { - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { countMap[item->getID()] += item->getItemCount(); } return countMap; @@ -843,7 +843,7 @@ ItemVector Container::getItems(bool recursive /*= false*/) { containerItems.push_back(*it); } } else { - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { containerItems.push_back(item); } } @@ -887,7 +887,7 @@ void Container::internalAddThing(uint32_t, std::shared_ptr thing) { return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return; } @@ -914,7 +914,7 @@ void Container::stopDecaying() { uint16_t Container::getFreeSlots() { uint16_t counter = std::max(0, capacity() - size()); - for (std::shared_ptr item : itemlist) { + for (const std::shared_ptr &item : itemlist) { if (std::shared_ptr container = item->getContainer()) { counter += std::max(0, container->getFreeSlots()); } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index 6bfb509b8d3..77c5aedd813 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -39,23 +39,23 @@ class Container : public Item, public Cylinder { public: explicit Container(uint16_t type); Container(uint16_t type, uint16_t size, bool unlocked = true, bool pagination = false); - ~Container(); + ~Container() override; static std::shared_ptr create(uint16_t type); static std::shared_ptr create(uint16_t type, uint16_t size, bool unlocked = true, bool pagination = false); - static std::shared_ptr create(std::shared_ptr type); + static std::shared_ptr create(const std::shared_ptr &type); // non-copyable Container(const Container &) = delete; Container &operator=(const Container &) = delete; - std::shared_ptr clone() const override final; + std::shared_ptr clone() const final; - std::shared_ptr getContainer() override final { + std::shared_ptr getContainer() final { return static_self_cast(); } - std::shared_ptr getContainer() const override final { + std::shared_ptr getContainer() const final { return static_self_cast(); } @@ -114,7 +114,7 @@ class Container : public Item, public Cylinder { bool countsToLootAnalyzerBalance(); bool hasParent(); - void addItem(std::shared_ptr item); + void addItem(const std::shared_ptr &item); StashContainerList getStowableItems() const; bool isStoreInbox() const; bool isStoreInboxFiltered() const; @@ -122,13 +122,13 @@ class Container : public Item, public Cylinder { std::vector getStoreInboxValidCategories() const; std::shared_ptr getFilteredItemByIndex(size_t index) const; std::shared_ptr getItemByIndex(size_t index) const; - bool isHoldingItem(std::shared_ptr item); - bool isHoldingItemWithId(const uint16_t id); + bool isHoldingItem(const std::shared_ptr &item); + bool isHoldingItemWithId(uint16_t id); uint32_t getItemHoldingCount(); uint32_t getContainerHoldingCount(); uint16_t getFreeSlots(); - uint32_t getWeight() const override final; + uint32_t getWeight() const final; bool isUnlocked() const { return !this->isCorpse() && unlocked; @@ -139,49 +139,49 @@ class Container : public Item, public Cylinder { // cylinder implementations virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; - ReturnValue queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override final; - ReturnValue queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override final; - std::shared_ptr queryDestination(int32_t &index, const std::shared_ptr &thing, std::shared_ptr* destItem, uint32_t &flags) override final; + ReturnValue queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; + ReturnValue queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) final; + std::shared_ptr queryDestination(int32_t &index, const std::shared_ptr &thing, std::shared_ptr* destItem, uint32_t &flags) final; - void addThing(std::shared_ptr thing) override final; - void addThing(int32_t index, std::shared_ptr thing) override final; - void addItemBack(std::shared_ptr item); + void addThing(std::shared_ptr thing) final; + void addThing(int32_t index, std::shared_ptr thing) final; + void addItemBack(const std::shared_ptr &item); - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override final; + void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) final; void replaceThing(uint32_t index, std::shared_ptr thing) override final; - void removeThing(std::shared_ptr thing, uint32_t count) override final; + void removeThing(std::shared_ptr thing, uint32_t count) final; - int32_t getThingIndex(std::shared_ptr thing) const override final; - size_t getFirstIndex() const override final; - size_t getLastIndex() const override final; - uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override final; - std::map &getAllItemTypeCount(std::map &countMap) const override final; - std::shared_ptr getThing(size_t index) const override final; + int32_t getThingIndex(std::shared_ptr thing) const final; + size_t getFirstIndex() const final; + size_t getLastIndex() const final; + uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const final; + std::map &getAllItemTypeCount(std::map &countMap) const final; + std::shared_ptr getThing(size_t index) const final; ItemVector getItems(bool recursive = false); void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void internalAddThing(std::shared_ptr thing) override final; - void internalAddThing(uint32_t index, std::shared_ptr thing) override final; + void internalAddThing(std::shared_ptr thing) final; + void internalAddThing(uint32_t index, std::shared_ptr thing) final; void startDecaying() override; void stopDecaying() override; virtual void removeItem(std::shared_ptr thing, bool sendUpdateToClient = false); - uint32_t getOwnerId() const override final; + uint32_t getOwnerId() const final; bool isAnyKindOfRewardChest(); bool isAnyKindOfRewardContainer(); bool isBrowseFieldAndHoldsRewardChest(); - bool isInsideContainerWithId(const uint16_t id); + bool isInsideContainerWithId(uint16_t id); protected: std::ostringstream &getContentDescription(std::ostringstream &os, bool oldProtocol); - uint32_t m_maxItems; + uint32_t m_maxItems {}; uint32_t maxSize; uint32_t totalWeight = 0; ItemDeque itemlist; @@ -193,9 +193,9 @@ class Container : public Item, public Cylinder { friend class MapCache; private: - void onAddContainerItem(std::shared_ptr item); - void onUpdateContainerItem(uint32_t index, std::shared_ptr oldItem, std::shared_ptr newItem); - void onRemoveContainerItem(uint32_t index, std::shared_ptr item); + void onAddContainerItem(const std::shared_ptr &item); + void onUpdateContainerItem(uint32_t index, const std::shared_ptr &oldItem, const std::shared_ptr &newItem); + void onRemoveContainerItem(uint32_t index, const std::shared_ptr &item); std::shared_ptr getParentContainer(); std::shared_ptr getTopParentContainer(); diff --git a/src/items/containers/depot/depotchest.cpp b/src/items/containers/depot/depotchest.cpp index 15488267f04..a1547b3a508 100644 --- a/src/items/containers/depot/depotchest.cpp +++ b/src/items/containers/depot/depotchest.cpp @@ -20,7 +20,7 @@ DepotChest::DepotChest(uint16_t type) : } ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor /* = nullptr*/) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/items/containers/depot/depotlocker.cpp b/src/items/containers/depot/depotlocker.cpp index 0be000794ef..ef8acdf2217 100644 --- a/src/items/containers/depot/depotlocker.cpp +++ b/src/items/containers/depot/depotlocker.cpp @@ -42,7 +42,7 @@ void DepotLocker::postRemoveNotification(std::shared_ptr thing, std::shar } } -void DepotLocker::removeInbox(std::shared_ptr inbox) { +void DepotLocker::removeInbox(const std::shared_ptr &inbox) { auto cit = std::find(itemlist.begin(), itemlist.end(), inbox); if (cit == itemlist.end()) { return; diff --git a/src/items/containers/depot/depotlocker.hpp b/src/items/containers/depot/depotlocker.hpp index 09d794c444f..d572e3b60b8 100644 --- a/src/items/containers/depot/depotlocker.hpp +++ b/src/items/containers/depot/depotlocker.hpp @@ -20,7 +20,7 @@ class DepotLocker final : public Container { return static_self_cast(); } - void removeInbox(std::shared_ptr inbox); + void removeInbox(const std::shared_ptr &inbox); // serialization Attr_ReadValue readAttr(AttrTypes_t attr, PropStream &propStream) override; diff --git a/src/items/containers/inbox/inbox.cpp b/src/items/containers/inbox/inbox.cpp index 9b22c53748a..797c4f168ec 100644 --- a/src/items/containers/inbox/inbox.cpp +++ b/src/items/containers/inbox/inbox.cpp @@ -24,7 +24,7 @@ ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr &thing, uint32 return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index c2c9b2f61e1..3371ac049ed 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -16,7 +16,7 @@ #include "map/spectators.hpp" ReturnValue Mailbox::queryAdd(int32_t, const std::shared_ptr &thing, uint32_t, uint32_t, std::shared_ptr) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item && Mailbox::canSend(item)) { return RETURNVALUE_NOERROR; } @@ -45,7 +45,7 @@ void Mailbox::addThing(int32_t, std::shared_ptr thing) { return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item && Mailbox::canSend(item)) { sendItem(item); } @@ -71,7 +71,7 @@ void Mailbox::postRemoveNotification(std::shared_ptr thing, std::shared_p getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } -bool Mailbox::sendItem(std::shared_ptr item) const { +bool Mailbox::sendItem(const std::shared_ptr &item) const { std::string receiver; if (!getReceiver(item, receiver)) { return false; @@ -88,9 +88,9 @@ bool Mailbox::sendItem(std::shared_ptr item) const { } } - std::shared_ptr player = g_game().getPlayerByName(receiver, true); + const auto player = g_game().getPlayerByName(receiver, true); std::string writer; - time_t date = time(0); + time_t date = time(nullptr); std::string text; if (item && item->getID() == ITEM_LETTER && !item->getAttribute(ItemAttribute_t::WRITER).empty()) { writer = item->getAttribute(ItemAttribute_t::WRITER); @@ -100,7 +100,7 @@ bool Mailbox::sendItem(std::shared_ptr item) const { if (player && item) { if (g_game().internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { auto newItem = g_game().transformItem(item, item->getID() + 1); - if (newItem && newItem->getID() == ITEM_LETTER_STAMPED && writer != "") { + if (newItem && newItem->getID() == ITEM_LETTER_STAMPED && !writer.empty()) { newItem->setAttribute(ItemAttribute_t::WRITER, writer); newItem->setAttribute(ItemAttribute_t::DATE, date); newItem->setAttribute(ItemAttribute_t::TEXT, text); @@ -116,10 +116,10 @@ bool Mailbox::sendItem(std::shared_ptr item) const { return false; } -bool Mailbox::getReceiver(std::shared_ptr item, std::string &name) const { +bool Mailbox::getReceiver(const std::shared_ptr &item, std::string &name) const { std::shared_ptr container = item->getContainer(); if (container) { - for (std::shared_ptr containerItem : container->getItemList()) { + for (const std::shared_ptr &containerItem : container->getItemList()) { if (containerItem->getID() == ITEM_LABEL && getReceiver(containerItem, name)) { return true; } @@ -137,6 +137,6 @@ bool Mailbox::getReceiver(std::shared_ptr item, std::string &name) const { return true; } -bool Mailbox::canSend(std::shared_ptr item) { +bool Mailbox::canSend(const std::shared_ptr &item) { return !item->hasOwner() && (item->getID() == ITEM_PARCEL || item->getID() == ITEM_LETTER); } diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index 116cd0ee1c4..03f8506b411 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -21,7 +21,7 @@ class Mailbox final : public Item, public Cylinder { return static_self_cast(); } - std::shared_ptr getCylinder() override final { + std::shared_ptr getCylinder() final { return getMailbox(); } @@ -43,8 +43,8 @@ class Mailbox final : public Item, public Cylinder { void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; private: - bool getReceiver(std::shared_ptr item, std::string &name) const; - bool sendItem(std::shared_ptr item) const; + bool getReceiver(const std::shared_ptr &item, std::string &name) const; + bool sendItem(const std::shared_ptr &item) const; - static bool canSend(std::shared_ptr item); + static bool canSend(const std::shared_ptr &item); }; diff --git a/src/items/containers/rewards/reward.cpp b/src/items/containers/rewards/reward.cpp index 4b1757bd6c8..fec8b6884df 100644 --- a/src/items/containers/rewards/reward.cpp +++ b/src/items/containers/rewards/reward.cpp @@ -23,7 +23,7 @@ ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr &thing, uint3 return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/items/decay/decay.cpp b/src/items/decay/decay.cpp index 5eaff61a7a9..94ca7d00ab3 100644 --- a/src/items/decay/decay.cpp +++ b/src/items/decay/decay.cpp @@ -19,7 +19,7 @@ Decay &Decay::getInstance() { return inject(); } -void Decay::startDecay(std::shared_ptr item) { +void Decay::startDecay(const std::shared_ptr &item) { if (!item) { return; } @@ -65,7 +65,7 @@ void Decay::startDecay(std::shared_ptr item) { } } -void Decay::stopDecay(std::shared_ptr item) { +void Decay::stopDecay(const std::shared_ptr &item) { if (item->hasAttribute(ItemAttribute_t::DECAYSTATE)) { auto timestamp = item->getAttribute(ItemAttribute_t::DURATION_TIMESTAMP); if (item->hasAttribute(ItemAttribute_t::DURATION_TIMESTAMP)) { @@ -148,7 +148,7 @@ void Decay::checkDecay() { } } -void Decay::internalDecayItem(std::shared_ptr item) { +void Decay::internalDecayItem(const std::shared_ptr &item) { const ItemType &it = Item::items[item->getID()]; // Remove the item and halt the decay process if a player triggers a bug where the item's decay ID matches its equip or de-equip transformation ID if (it.id == it.transformEquipTo || it.id == it.transformDeEquipTo) { @@ -163,7 +163,7 @@ void Decay::internalDecayItem(std::shared_ptr item) { } if (it.decayTo != 0) { - std::shared_ptr player = item->getHoldingPlayer(); + const auto player = item->getHoldingPlayer(); if (player) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { diff --git a/src/items/decay/decay.hpp b/src/items/decay/decay.hpp index e2916f6134f..2a91b36018a 100644 --- a/src/items/decay/decay.hpp +++ b/src/items/decay/decay.hpp @@ -20,12 +20,12 @@ class Decay { static Decay &getInstance(); - void startDecay(std::shared_ptr item); - void stopDecay(std::shared_ptr item); + void startDecay(const std::shared_ptr &item); + void stopDecay(const std::shared_ptr &item); private: void checkDecay(); - void internalDecayItem(std::shared_ptr item); + static void internalDecayItem(const std::shared_ptr &item); uint32_t eventId { 0 }; // order is important, so we use an std::map diff --git a/src/items/functions/item/attribute.cpp b/src/items/functions/item/attribute.cpp index c67c6ce38f7..b3ee3d64e0e 100644 --- a/src/items/functions/item/attribute.cpp +++ b/src/items/functions/item/attribute.cpp @@ -27,7 +27,7 @@ const std::string &ItemAttribute::getAttributeString(ItemAttribute_t type) const return emptyString; } - return *attribute->getString().get(); + return *attribute->getString(); } const int64_t &ItemAttribute::getAttributeValue(ItemAttribute_t type) const { diff --git a/src/items/functions/item/attribute.hpp b/src/items/functions/item/attribute.hpp index a2d3ba128ed..b89920a4f18 100644 --- a/src/items/functions/item/attribute.hpp +++ b/src/items/functions/item/attribute.hpp @@ -15,7 +15,7 @@ class ItemAttributeHelper { public: - bool isAttributeInteger(ItemAttribute_t type) const { + static bool isAttributeInteger(ItemAttribute_t type) { switch (type) { case ItemAttribute_t::STORE: case ItemAttribute_t::ACTIONID: @@ -48,7 +48,7 @@ class ItemAttributeHelper { } } - bool isAttributeString(ItemAttribute_t type) const { + static bool isAttributeString(ItemAttribute_t type) { switch (type) { case ItemAttribute_t::DESCRIPTION: case ItemAttribute_t::TEXT: @@ -88,10 +88,9 @@ class Attributes : public ItemAttributeHelper { } std::variant> getDefaultValueForType(ItemAttribute_t attributeType) const { - ItemAttributeHelper helper; - if (helper.isAttributeInteger(attributeType)) { + if (ItemAttributeHelper::isAttributeInteger(attributeType)) { return 0; - } else if (helper.isAttributeString(attributeType)) { + } else if (ItemAttributeHelper::isAttributeString(attributeType)) { return std::make_shared(); } else { return {}; @@ -116,7 +115,7 @@ class Attributes : public ItemAttributeHelper { return emptyValue; } - const std::shared_ptr getString() const { + std::shared_ptr getString() const { if (std::holds_alternative>(value)) { return std::get>(value); } @@ -138,10 +137,10 @@ class ItemAttribute : public ItemAttributeHelper { // CustomAttribute object methods const CustomAttribute* getCustomAttribute(const std::string &attributeName) const; - void setCustomAttribute(const std::string &key, const int64_t value); + void setCustomAttribute(const std::string &key, int64_t value); void setCustomAttribute(const std::string &key, const std::string &value); - void setCustomAttribute(const std::string &key, const double value); - void setCustomAttribute(const std::string &key, const bool value); + void setCustomAttribute(const std::string &key, double value); + void setCustomAttribute(const std::string &key, bool value); void addCustomAttribute(const std::string &key, const CustomAttribute &customAttribute); bool removeCustomAttribute(const std::string &attributeName); @@ -158,12 +157,9 @@ class ItemAttribute : public ItemAttributeHelper { } bool hasAttribute(ItemAttribute_t type) const { - for (const auto &attr : attributeVector) { - if (attr.getAttributeType() == type) { - return true; - } - } - return false; + return std::ranges::any_of(attributeVector, [type](const auto &attr) { + return attr.getAttributeType() == type; + }); } const Attributes* getAttribute(ItemAttribute_t type) const; diff --git a/src/items/functions/item/custom_attribute.cpp b/src/items/functions/item/custom_attribute.cpp index 202c57c0960..9987e8e7952 100644 --- a/src/items/functions/item/custom_attribute.cpp +++ b/src/items/functions/item/custom_attribute.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "items/functions/item/custom_attribute.hpp" @@ -17,20 +19,20 @@ CustomAttribute::CustomAttribute() = default; CustomAttribute::~CustomAttribute() = default; // Constructor for int64_t -CustomAttribute::CustomAttribute(const std::string &initStringKey, const int64_t initInt64) : - stringKey(initStringKey), value(initInt64) { +CustomAttribute::CustomAttribute(std::string initStringKey, const int64_t initInt64) : + stringKey(std::move(initStringKey)), value(initInt64) { } // Constructor for string -CustomAttribute::CustomAttribute(const std::string &initStringKey, const std::string &initStringValue) : - stringKey(initStringKey), value(initStringValue) { +CustomAttribute::CustomAttribute(std::string initStringKey, const std::string &initStringValue) : + stringKey(std::move(initStringKey)), value(initStringValue) { } // Constructor for double -CustomAttribute::CustomAttribute(const std::string &initStringKey, const double initDoubleValue) : - stringKey(initStringKey), value(initDoubleValue) { +CustomAttribute::CustomAttribute(std::string initStringKey, const double initDoubleValue) : + stringKey(std::move(initStringKey)), value(initDoubleValue) { } // Constructor for boolean -CustomAttribute::CustomAttribute(const std::string &initStringKey, const bool initBoolValue) : - stringKey(initStringKey), value(initBoolValue) { +CustomAttribute::CustomAttribute(std::string initStringKey, const bool initBoolValue) : + stringKey(std::move(initStringKey)), value(initBoolValue) { } const std::string &CustomAttribute::getStringKey() const { diff --git a/src/items/functions/item/custom_attribute.hpp b/src/items/functions/item/custom_attribute.hpp index e91832c6b6b..b44e20bf477 100644 --- a/src/items/functions/item/custom_attribute.hpp +++ b/src/items/functions/item/custom_attribute.hpp @@ -16,10 +16,10 @@ class CustomAttribute { CustomAttribute(); ~CustomAttribute(); - CustomAttribute(const std::string &initStringKey, const int64_t initInt64Value); - CustomAttribute(const std::string &initStringKey, const std::string &initStringValue); - CustomAttribute(const std::string &initStringKey, const double initDoubleValue); - CustomAttribute(const std::string &initStringKey, const bool initBoolValue); + CustomAttribute(std::string initStringKey, int64_t initInt64Value); + CustomAttribute(std::string initStringKey, const std::string &initStringValue); + CustomAttribute(std::string initStringKey, double initDoubleValue); + CustomAttribute(std::string initStringKey, bool initBoolValue); const std::string &getStringKey() const; diff --git a/src/items/functions/item/item_parse.cpp b/src/items/functions/item/item_parse.cpp index 41b35403bca..06215ccf650 100644 --- a/src/items/functions/item/item_parse.cpp +++ b/src/items/functions/item/item_parse.cpp @@ -124,7 +124,7 @@ void ItemParse::parseType(const std::string &tmpStrValue, pugi::xml_node attribu } void ItemParse::parseDescription(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "description") { itemType.description = valueAttribute.as_string(); if (g_configManager().getBoolean(TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY, __FUNCTION__) && itemType.id == ITEM_GOLD_POUCH) { @@ -136,70 +136,70 @@ void ItemParse::parseDescription(const std::string &tmpStrValue, pugi::xml_attri } void ItemParse::parseRuneSpellName(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "runespellname") { itemType.runeSpellName = valueAttribute.as_string(); } } void ItemParse::parseWeight(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "weight") { itemType.weight = pugi::cast(valueAttribute.value()); } } void ItemParse::parseShowCount(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "showcount") { itemType.showCount = valueAttribute.as_bool(); } } void ItemParse::parseArmor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "armor") { itemType.armor = pugi::cast(valueAttribute.value()); } } void ItemParse::parseDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "defense") { itemType.defense = pugi::cast(valueAttribute.value()); } } void ItemParse::parseExtraDefense(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "extradef") { itemType.extraDefense = pugi::cast(valueAttribute.value()); } } void ItemParse::parseAttack(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "attack") { itemType.attack = pugi::cast(valueAttribute.value()); } } void ItemParse::parseRotateTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "rotateto") { itemType.rotateTo = pugi::cast(valueAttribute.value()); } } void ItemParse::parseWrapContainer(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "wrapcontainer") { itemType.wrapContainer = valueAttribute.as_bool(); } } void ItemParse::parseWrapableTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "wrapableto") { itemType.wrapableTo = pugi::cast(valueAttribute.value()); itemType.wrapable = true; @@ -207,21 +207,21 @@ void ItemParse::parseWrapableTo(const std::string &tmpStrValue, pugi::xml_attrib } void ItemParse::parseMovable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "movable") { itemType.movable = valueAttribute.as_bool(); } } void ItemParse::parseBlockProjectTile(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "blockprojectile") { itemType.blockProjectile = valueAttribute.as_bool(); } } void ItemParse::parsePickupable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "allowpickupable" || stringValue == "pickupable") { itemType.pickupable = valueAttribute.as_bool(); } @@ -241,7 +241,7 @@ void ItemParse::parseFloorChange(const std::string &tmpStrValue, pugi::xml_attri } void ItemParse::parseContainerSize(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "containersize") { itemType.maxItems = pugi::cast(valueAttribute.value()); } @@ -261,7 +261,7 @@ void ItemParse::parseFluidSource(const std::string &tmpStrValue, pugi::xml_attri } void ItemParse::parseWriteables(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "readable") { itemType.canReadText = valueAttribute.as_bool(); } else if (stringValue == "writeable") { @@ -326,7 +326,7 @@ void ItemParse::parseSlotType(const std::string &tmpStrValue, pugi::xml_attribut } void ItemParse::parseAmmoType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "ammotype") { itemType.ammoType = getAmmoType(asLowerCaseString(valueAttribute.as_string())); if (itemType.ammoType == AMMO_NONE) { @@ -336,7 +336,7 @@ void ItemParse::parseAmmoType(const std::string &tmpStrValue, pugi::xml_attribut } void ItemParse::parseShootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "shoottype") { ShootType_t shoot = getShootType(asLowerCaseString(valueAttribute.as_string())); if (shoot != CONST_ANI_NONE) { @@ -348,7 +348,7 @@ void ItemParse::parseShootType(const std::string &tmpStrValue, pugi::xml_attribu } void ItemParse::parseMagicEffect(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "effect") { MagicEffectClasses effect = getMagicEffect(asLowerCaseString(valueAttribute.as_string())); if (effect != CONST_ME_NONE) { @@ -360,28 +360,28 @@ void ItemParse::parseMagicEffect(const std::string &tmpStrValue, pugi::xml_attri } void ItemParse::parseLootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "loottype") { itemType.type = Item::items.getLootType(valueAttribute.as_string()); } } void ItemParse::parseRange(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "range") { itemType.shootRange = pugi::cast(valueAttribute.value()); } } void ItemParse::parseDecayTo(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "decayto") { itemType.decayTo = pugi::cast(valueAttribute.value()); } } void ItemParse::parseDuration(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "duration") { itemType.decayTime = pugi::cast(valueAttribute.value()); } else if (stringValue == "stopduration") { @@ -392,7 +392,7 @@ void ItemParse::parseDuration(const std::string &tmpStrValue, pugi::xml_attribut } void ItemParse::parseTransform(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "transformequipto") { itemType.transformEquipTo = pugi::cast(valueAttribute.value()); if (itemType.transformEquipTo == itemType.decayTo) { @@ -418,7 +418,7 @@ void ItemParse::parseTransform(const std::string &tmpStrValue, pugi::xml_attribu } void ItemParse::parseCharges(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "charges") { itemType.charges = pugi::cast(valueAttribute.value()); } else if (stringValue == "showcharges") { @@ -434,7 +434,7 @@ void ItemParse::parseShowAttributes(const std::string &tmpStrValue, pugi::xml_at } void ItemParse::parseHitChance(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "hitchance") { itemType.hitChance = std::min(100, std::max(-100, pugi::cast(valueAttribute.value()))); } else if (stringValue == "maxhitchance") { @@ -443,21 +443,21 @@ void ItemParse::parseHitChance(const std::string &tmpStrValue, pugi::xml_attribu } void ItemParse::parseInvisible(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "invisible") { itemType.getAbilities().invisible = valueAttribute.as_bool(); } } void ItemParse::parseSpeed(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "speed") { itemType.getAbilities().speed = pugi::cast(valueAttribute.value()); } } void ItemParse::parseHealthAndMana(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "healthgain") { Abilities &abilities = itemType.getAbilities(); abilities.regeneration = true; @@ -480,7 +480,7 @@ void ItemParse::parseHealthAndMana(const std::string &tmpStrValue, pugi::xml_att } void ItemParse::parseSkills(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "skillsword") { itemType.getAbilities().skills[SKILL_SWORD] = pugi::cast(valueAttribute.value()); } else if (stringValue == "skillaxe") { @@ -499,7 +499,7 @@ void ItemParse::parseSkills(const std::string &tmpStrValue, pugi::xml_attribute } void ItemParse::parseCriticalHit(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "criticalhitchance") { itemType.getAbilities().skills[SKILL_CRITICAL_HIT_CHANCE] = pugi::cast(valueAttribute.value()); } else if (stringValue == "criticalhitdamage") { @@ -508,7 +508,7 @@ void ItemParse::parseCriticalHit(const std::string &tmpStrValue, pugi::xml_attri } void ItemParse::parseLifeAndManaLeech(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "lifeleechchance") { itemType.getAbilities().skills[SKILL_LIFE_LEECH_CHANCE] = pugi::cast(valueAttribute.value()); } else if (stringValue == "lifeleechamount") { @@ -521,7 +521,7 @@ void ItemParse::parseLifeAndManaLeech(const std::string &tmpStrValue, pugi::xml_ } void ItemParse::parseMaxHitAndManaPoints(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "maxhitpoints") { itemType.getAbilities().stats[STAT_MAXHITPOINTS] = pugi::cast(valueAttribute.value()); } else if (stringValue == "maxhitpointspercent") { @@ -534,7 +534,7 @@ void ItemParse::parseMaxHitAndManaPoints(const std::string &tmpStrValue, pugi::x } void ItemParse::parseMagicLevelPoint(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "magiclevelpoints" || stringValue == "magicpoints") { itemType.getAbilities().stats[STAT_MAGICPOINTS] = pugi::cast(valueAttribute.value()); } else if (stringValue == "magiclevelpointspercent") { @@ -543,7 +543,7 @@ void ItemParse::parseMagicLevelPoint(const std::string &tmpStrValue, pugi::xml_a } void ItemParse::parseFieldAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "fieldabsorbpercentenergy") { itemType.getAbilities().fieldAbsorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += pugi::cast(valueAttribute.value()); } else if (stringValue == "fieldabsorbpercentfire") { @@ -554,22 +554,22 @@ void ItemParse::parseFieldAbsorbPercent(const std::string &tmpStrValue, pugi::xm } void ItemParse::parseAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "absorbpercentall") { - int16_t value = pugi::cast(valueAttribute.value()); + auto value = pugi::cast(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); for (auto &i : abilities.absorbPercent) { i += value; } } else if (stringValue == "absorbpercentelements") { - int16_t value = pugi::cast(valueAttribute.value()); + auto value = pugi::cast(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_EARTHDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_ICEDAMAGE)] += value; } else if (stringValue == "absorbpercentmagic") { - int16_t value = pugi::cast(valueAttribute.value()); + auto value = pugi::cast(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; @@ -603,7 +603,7 @@ void ItemParse::parseAbsorbPercent(const std::string &tmpStrValue, pugi::xml_att } void ItemParse::parseSupressDrunk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (valueAttribute.as_bool()) { ConditionType_t conditionType = CONDITION_NONE; if (stringValue == "suppressdrunk") { @@ -673,7 +673,7 @@ CombatType_t ItemParse::parseFieldCombatType(std::string lowerStringValue, pugi: return COMBAT_NONE; } -void ItemParse::parseFieldCombatDamage(std::shared_ptr conditionDamage, std::string stringValue, pugi::xml_node attributeNode) { +void ItemParse::parseFieldCombatDamage(const std::shared_ptr &conditionDamage, std::string stringValue, pugi::xml_node attributeNode) { uint32_t combatTicks = 0; int32_t combatDamage = 0; int32_t combatStart = 0; @@ -744,27 +744,27 @@ void ItemParse::parseField(const std::string &tmpStrValue, pugi::xml_node attrib } void ItemParse::parseReplaceable(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "replaceable") { itemType.replaceable = valueAttribute.as_bool(); } } void ItemParse::parseLevelDoor(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "leveldoor") { itemType.levelDoor = pugi::cast(valueAttribute.value()); } } void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "partnerdirection") { itemType.bedPartnerDir = getDirection(valueAttribute.as_string()); } if (stringValue == "maletransformto") { - uint16_t valueMale = pugi::cast(valueAttribute.value()); + auto valueMale = pugi::cast(valueAttribute.value()); ItemType &other = Item::items.getItemType(valueMale); itemType.transformToOnUse[PLAYERSEX_MALE] = valueMale; if (other.transformToFree == 0) { @@ -775,7 +775,7 @@ void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute va itemType.transformToOnUse[PLAYERSEX_FEMALE] = valueMale; } } else if (stringValue == "femaletransformto") { - uint16_t valueFemale = pugi::cast(valueAttribute.value()); + auto valueFemale = pugi::cast(valueAttribute.value()); ItemType &other = Item::items.getItemType(valueFemale); itemType.transformToOnUse[PLAYERSEX_FEMALE] = valueFemale; @@ -797,7 +797,7 @@ void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute va } void ItemParse::parseElement(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "elementice") { Abilities &abilities = itemType.getAbilities(); abilities.elementDamage = pugi::cast(valueAttribute.value()); @@ -826,7 +826,7 @@ void ItemParse::parseElement(const std::string &tmpStrValue, pugi::xml_attribute } void ItemParse::parseWalk(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "walkstack") { itemType.walkStack = valueAttribute.as_bool(); } else if (stringValue == "blocking") { @@ -835,7 +835,7 @@ void ItemParse::parseWalk(const std::string &tmpStrValue, pugi::xml_attribute va } void ItemParse::parseAllowDistanceRead(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "allowdistread") { itemType.allowDistRead = booleanString(valueAttribute.as_string()); } @@ -924,7 +924,7 @@ void ItemParse::parseAugment(const std::string &tmpStrValue, pugi::xml_node attr } void ItemParse::parseStackSize(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; if (stringValue == "stacksize") { auto stackSize = pugi::cast(valueAttribute.value()); if (stackSize > 255) { @@ -936,7 +936,7 @@ void ItemParse::parseStackSize(const std::string &tmpStrValue, pugi::xml_attribu } void ItemParse::parseSpecializedMagicLevelPoint(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; Abilities &abilities = itemType.getAbilities(); if (stringValue == "deathmagiclevelpoints") { abilities.specializedMagicLevel[combatTypeToIndex(COMBAT_DEATHDAMAGE)] += pugi::cast(valueAttribute.value()); @@ -966,7 +966,7 @@ void ItemParse::parseSpecializedMagicLevelPoint(const std::string &tmpStrValue, } void ItemParse::parseMagicShieldCapacity(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; Abilities &abilities = itemType.getAbilities(); if (stringValue == "magicshieldcapacitypercent") { abilities.magicShieldCapacityPercent += pugi::cast(valueAttribute.value()); @@ -976,7 +976,7 @@ void ItemParse::parseMagicShieldCapacity(const std::string &tmpStrValue, pugi::x } void ItemParse::parsePerfecShot(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; Abilities &abilities = itemType.getAbilities(); if (stringValue == "perfectshotdamage") { abilities.perfectShotDamage = pugi::cast(valueAttribute.value()); @@ -986,7 +986,7 @@ void ItemParse::parsePerfecShot(const std::string &tmpStrValue, pugi::xml_attrib } void ItemParse::parseCleavePercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; Abilities &abilities = itemType.getAbilities(); if (stringValue == "cleavepercent") { abilities.cleavePercent += pugi::cast(valueAttribute.value()); @@ -994,12 +994,12 @@ void ItemParse::parseCleavePercent(const std::string &tmpStrValue, pugi::xml_att } void ItemParse::parseReflectDamage(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string stringValue = tmpStrValue; + const std::string &stringValue = tmpStrValue; Abilities &abilities = itemType.getAbilities(); if (stringValue == "reflectdamage") { abilities.reflectFlat[combatTypeToIndex(COMBAT_PHYSICALDAMAGE)] += pugi::cast(valueAttribute.value()); } else if (stringValue == "reflectpercentall") { - int32_t value = pugi::cast(valueAttribute.value()); + auto value = pugi::cast(valueAttribute.value()); std::transform(std::begin(abilities.reflectPercent), std::end(abilities.reflectPercent), std::begin(abilities.reflectPercent), [&](const auto &i) { return i + value; }); diff --git a/src/items/functions/item/item_parse.hpp b/src/items/functions/item/item_parse.hpp index e9f6133eb3a..2a0cc1c0a9f 100644 --- a/src/items/functions/item/item_parse.hpp +++ b/src/items/functions/item/item_parse.hpp @@ -329,6 +329,6 @@ class ItemParse : public Items { // Parent of the function: static void parseField static std::tuple parseFieldConditions(std::string lowerStringValue, pugi::xml_attribute valueAttribute); static CombatType_t parseFieldCombatType(std::string string, pugi::xml_attribute valueAttribute); - static void parseFieldCombatDamage(std::shared_ptr conditionDamage, std::string stringValue, pugi::xml_node attributeNode); + static void parseFieldCombatDamage(const std::shared_ptr &conditionDamage, std::string stringValue, pugi::xml_node attributeNode); static void createAndRegisterScript(ItemType &itemType, pugi::xml_node attributeNode, MoveEvent_t eventType = MOVE_EVENT_NONE, WeaponType_t weaponType = WEAPON_NONE); }; diff --git a/src/items/item.cpp b/src/items/item.cpp index dd2d5c965a6..81a2c2c4d30 100644 --- a/src/items/item.cpp +++ b/src/items/item.cpp @@ -100,7 +100,7 @@ void Item::setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { } void Item::addImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { - std::shared_ptr player = getHoldingPlayer(); + const auto player = getHoldingPlayer(); if (!player) { return; } @@ -226,7 +226,7 @@ Item::Item(const std::shared_ptr &i) : } std::shared_ptr Item::clone() const { - std::shared_ptr item = Item::CreateItem(id, count); + const auto item = Item::CreateItem(id, count); if (item == nullptr) { g_logger().error("[{}] item is nullptr", __FUNCTION__); return nullptr; @@ -239,7 +239,7 @@ std::shared_ptr Item::clone() const { return item; } -bool Item::equals(std::shared_ptr compareItem) const { +bool Item::equals(const std::shared_ptr &compareItem) const { if (!compareItem) { return false; } @@ -396,7 +396,7 @@ bool Item::isItemStorable() const { if (isStoreItem() || hasOwner()) { return false; } - auto isContainerAndHasSomethingInside = (getContainer() != NULL) && (getContainer()->getItemList().size() > 0); + auto isContainerAndHasSomethingInside = (getContainer() != nullptr) && (!getContainer()->getItemList().empty()); return (isStowable() || isContainerAndHasSomethingInside); } @@ -888,7 +888,7 @@ void Item::serializeAttr(PropWriteStream &propWriteStream) const { propWriteStream.writeString(text); } - if (const uint64_t writtenDate = getAttribute(ItemAttribute_t::DATE)) { + if (const auto writtenDate = getAttribute(ItemAttribute_t::DATE)) { propWriteStream.write(ATTR_WRITTENDATE); propWriteStream.write(writtenDate); } @@ -1027,7 +1027,7 @@ void Item::serializeAttr(PropWriteStream &propWriteStream) const { } } -void Item::setOwner(std::shared_ptr owner) { +void Item::setOwner(const std::shared_ptr &owner) { auto ownerId = owner->getID(); if (owner->getPlayer()) { ownerId = owner->getPlayer()->getGUID(); @@ -1035,7 +1035,7 @@ void Item::setOwner(std::shared_ptr owner) { setOwner(ownerId); } -bool Item::isOwner(std::shared_ptr owner) const { +bool Item::isOwner(const std::shared_ptr &owner) const { if (!owner) { return false; } @@ -1133,7 +1133,7 @@ uint32_t Item::getWeight() const { } std::vector> -Item::getDescriptions(const ItemType &it, std::shared_ptr item /*= nullptr*/) { +Item::getDescriptions(const ItemType &it, const std::shared_ptr &item /*= nullptr*/) { std::ostringstream ss; std::vector> descriptions; bool isTradeable = true; @@ -1412,7 +1412,7 @@ Item::getDescriptions(const ItemType &it, std::shared_ptr item /*= nullptr for (uint8_t i = 0; i < item->getImbuementSlot(); ++i) { slotName = fmt::format("Imbuement Slot {}", i + 1); ss.str(""); - const auto castItem = item; + const auto &castItem = item; if (!castItem) { continue; } @@ -1907,7 +1907,7 @@ Item::getDescriptions(const ItemType &it, std::shared_ptr item /*= nullptr return descriptions; } -std::string Item::parseImbuementDescription(std::shared_ptr item) { +std::string Item::parseImbuementDescription(const std::shared_ptr &item) { std::ostringstream s; if (item && item->getImbuementSlot() >= 1) { s << std::endl @@ -1944,7 +1944,7 @@ bool Item::isSavedToHouses() { return it.movable || it.isWrappable() || it.isCarpet() || getDoor() || (getContainer() && !getContainer()->empty()) || it.canWriteText || getBed() || it.m_transformOnUse; } -SoundEffect_t Item::getMovementSound(std::shared_ptr toCylinder) const { +SoundEffect_t Item::getMovementSound(const std::shared_ptr &toCylinder) const { if (!toCylinder) { return SoundEffect_t::ITEM_MOVE_DEFAULT; } @@ -2006,7 +2006,7 @@ SoundEffect_t Item::getMovementSound(std::shared_ptr toCylinder) const return SoundEffect_t::ITEM_MOVE_DEFAULT; } -std::string Item::parseClassificationDescription(std::shared_ptr item) { +std::string Item::parseClassificationDescription(const std::shared_ptr &item) { std::ostringstream string; if (item && item->getClassification() >= 1) { string << std::endl @@ -2039,7 +2039,7 @@ std::string Item::parseShowDurationSpeed(int32_t speed, bool &begin) { return description.str(); } -std::string Item::parseShowDuration(std::shared_ptr item) { +std::string Item::parseShowDuration(const std::shared_ptr &item) { if (!item) { return {}; } @@ -2082,7 +2082,7 @@ std::string Item::parseShowDuration(std::shared_ptr item) { return description.str(); } -std::string Item::parseShowAttributesDescription(std::shared_ptr item, const uint16_t itemId) { +std::string Item::parseShowAttributesDescription(const std::shared_ptr &item, const uint16_t itemId) { std::ostringstream itemDescription; const ItemType &itemType = Item::items[itemId]; @@ -2310,8 +2310,8 @@ std::string Item::parseShowAttributesDescription(std::shared_ptr item, con return itemDescription.str(); } -std::string Item::getDescription(const ItemType &it, int32_t lookDistance, std::shared_ptr item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { - std::string text = ""; +std::string Item::getDescription(const ItemType &it, int32_t lookDistance, const std::shared_ptr &item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { + std::string text; std::ostringstream s; s << getNameDescription(it, item, subType, addArticle); @@ -3078,7 +3078,7 @@ std::string Item::getDescription(int32_t lookDistance) { return getDescription(it, lookDistance, getItem()); } -std::string Item::getNameDescription(const ItemType &it, std::shared_ptr item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { +std::string Item::getNameDescription(const ItemType &it, const std::shared_ptr &item /*= nullptr*/, int32_t subType /*= -1*/, bool addArticle /*= true*/) { if (item) { subType = item->getSubType(); } @@ -3144,7 +3144,7 @@ std::string Item::getWeightDescription(uint32_t weight) const { std::string Item::getWeightDescription() const { uint32_t weight = getWeight(); if (weight == 0) { - return std::string(); + return {}; } return getWeightDescription(weight); } diff --git a/src/items/item.hpp b/src/items/item.hpp index a9774c902cd..f84896fca5a 100644 --- a/src/items/item.hpp +++ b/src/items/item.hpp @@ -215,27 +215,27 @@ class ItemProperties { class Item : virtual public Thing, public ItemProperties, public SharedObject { public: // Factory member to create item of right type based on type - static std::shared_ptr CreateItem(const uint16_t type, uint16_t count = 0, Position* itemPosition = nullptr); - static std::shared_ptr CreateItemAsContainer(const uint16_t type, uint16_t size); + static std::shared_ptr CreateItem(uint16_t type, uint16_t count = 0, Position* itemPosition = nullptr); + static std::shared_ptr CreateItemAsContainer(uint16_t type, uint16_t size); static std::shared_ptr CreateItem(uint16_t itemId, Position &itemPosition); static Items items; // Constructor for items - Item(const uint16_t type, uint16_t count = 0); - Item(const std::shared_ptr &i); + explicit Item(uint16_t type, uint16_t count = 0); + explicit Item(const std::shared_ptr &i); virtual std::shared_ptr clone() const; - virtual ~Item() = default; + ~Item() override = default; // non-assignable Item &operator=(const Item &) = delete; - bool equals(std::shared_ptr compareItem) const; + bool equals(const std::shared_ptr &compareItem) const; - std::shared_ptr getItem() override final { + std::shared_ptr getItem() final { return static_self_cast(); } - std::shared_ptr getItem() const override final { + std::shared_ptr getItem() const final { return static_self_cast(); } virtual std::shared_ptr getTeleport() { @@ -259,7 +259,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { bool isSavedToHouses(); - SoundEffect_t getMovementSound(std::shared_ptr toCylinder) const; + SoundEffect_t getMovementSound(const std::shared_ptr &toCylinder) const; void setIsLootTrackeable(bool value) { isLootTrackeable = value; @@ -273,7 +273,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { setAttribute(ItemAttribute_t::OWNER, owner); } - void setOwner(std::shared_ptr owner); + void setOwner(const std::shared_ptr &owner); virtual uint32_t getOwnerId() const; @@ -281,7 +281,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { std::string getOwnerName() const; - bool isOwner(std::shared_ptr owner) const; + bool isOwner(const std::shared_ptr &owner) const; bool hasOwner() const { return getOwnerId() != 0; @@ -291,24 +291,24 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return isStoreItem() || hasOwner(); } - static std::string parseAugmentDescription(std::shared_ptr item, bool inspect = false) { + static std::string parseAugmentDescription(const std::shared_ptr &item, bool inspect = false) { if (!item) { return ""; } return items[item->getID()].parseAugmentDescription(inspect); } - static std::string parseImbuementDescription(std::shared_ptr item); + static std::string parseImbuementDescription(const std::shared_ptr &item); static std::string parseShowDurationSpeed(int32_t speed, bool &begin); - static std::string parseShowDuration(std::shared_ptr item); - static std::string parseShowAttributesDescription(std::shared_ptr item, const uint16_t itemId); - static std::string parseClassificationDescription(std::shared_ptr item); + static std::string parseShowDuration(const std::shared_ptr &item); + static std::string parseShowAttributesDescription(const std::shared_ptr &item, uint16_t itemId); + static std::string parseClassificationDescription(const std::shared_ptr &item); - static std::vector> getDescriptions(const ItemType &it, std::shared_ptr item = nullptr); - static std::string getDescription(const ItemType &it, int32_t lookDistance, std::shared_ptr item = nullptr, int32_t subType = -1, bool addArticle = true); - static std::string getNameDescription(const ItemType &it, std::shared_ptr item = nullptr, int32_t subType = -1, bool addArticle = true); + static std::vector> getDescriptions(const ItemType &it, const std::shared_ptr &item = nullptr); + static std::string getDescription(const ItemType &it, int32_t lookDistance, const std::shared_ptr &item = nullptr, int32_t subType = -1, bool addArticle = true); + static std::string getNameDescription(const ItemType &it, const std::shared_ptr &item = nullptr, int32_t subType = -1, bool addArticle = true); static std::string getWeightDescription(const ItemType &it, uint32_t weight, uint32_t count = 1); - std::string getDescription(int32_t lookDistance) override final; + std::string getDescription(int32_t lookDistance) final; std::string getNameDescription(); std::string getWeightDescription() const; @@ -319,10 +319,10 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { virtual void serializeAttr(PropWriteStream &propWriteStream) const; - bool isPushable() override final { + bool isPushable() final { return isMovable(); } - int32_t getThrowRange() const override final { + int32_t getThrowRange() const final { return (isPickupable() ? 15 : 2); } @@ -428,7 +428,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { std::vector> getAugments() const { return items[id].augments; } - std::vector> getAugmentsBySpellNameAndType(std::string spellName, Augment_t augmentType) const { + std::vector> getAugmentsBySpellNameAndType(const std::string &spellName, Augment_t augmentType) const { std::vector> augments; for (auto &augment : items[id].augments) { if (strcasecmp(augment->spellName.c_str(), spellName.c_str()) == 0 && augment->type == augmentType) { @@ -438,7 +438,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return augments; } - std::vector> getAugmentsBySpellName(std::string spellName) const { + std::vector> getAugmentsBySpellName(const std::string &spellName) const { std::vector> augments; for (auto &augment : items[id].augments) { if (strcasecmp(augment->spellName.c_str(), spellName.c_str()) == 0) { @@ -565,7 +565,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { } return items[id].name; } - const std::string getPluralName() const { + std::string getPluralName() const { if (hasAttribute(ItemAttribute_t::PLURALNAME)) { return getString(ItemAttribute_t::PLURALNAME); } @@ -597,7 +597,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { count = n; } - static uint32_t countByType(std::shared_ptr item, int32_t subType) { + static uint32_t countByType(const std::shared_ptr &item, int32_t subType) { if (subType == -1 || subType == item->getSubType()) { return item->getItemCount(); } @@ -691,7 +691,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { void clearImbuement(uint8_t slot, uint16_t imbuementId) { return setImbuement(slot, imbuementId, 0); } - bool hasImbuementType(ImbuementTypes_t imbuementType, uint16_t imbuementTier) { + bool hasImbuementType(ImbuementTypes_t imbuementType, uint16_t imbuementTier) const { auto it = items[id].imbuementTypes.find(imbuementType); if (it != items[id].imbuementTypes.end()) { return (it->second >= imbuementTier); diff --git a/src/items/items.cpp b/src/items/items.cpp index ea07b2354a3..3d453901752 100644 --- a/src/items/items.cpp +++ b/src/items/items.cpp @@ -67,7 +67,7 @@ ItemTypes_t Items::getLootType(const std::string &strValue) { return ITEM_TYPE_NONE; } -const std::string Items::getAugmentNameByType(Augment_t augmentType) { +std::string Items::getAugmentNameByType(Augment_t augmentType) { std::string augmentTypeName = magic_enum::enum_name(augmentType).data(); augmentTypeName = toStartCaseWithSpace(augmentTypeName); if (!isAugmentWithoutValueDescription(augmentType)) { @@ -155,7 +155,7 @@ void Items::loadFromProtobuf() { // This attribute is only used on 10x protocol, so we should not waste our time iterating it when it's disabled. if (supportAnimation) { for (uint32_t frame_it = 0; frame_it < object.frame_group_size(); ++frame_it) { - FrameGroup objectFrame = object.frame_group(frame_it); + const FrameGroup &objectFrame = object.frame_group(frame_it); if (!objectFrame.has_sprite_info()) { continue; } @@ -265,8 +265,8 @@ bool Items::loadFromXml() { continue; } - uint16_t id = pugi::cast(fromIdAttribute.value()); - uint16_t toId = pugi::cast(toIdAttribute.value()); + auto id = pugi::cast(fromIdAttribute.value()); + auto toId = pugi::cast(toIdAttribute.value()); while (id <= toId) { parseItemNode(itemNode, id++); } diff --git a/src/items/items.hpp b/src/items/items.hpp index e56678af6f3..721c3cdc0f5 100644 --- a/src/items/items.hpp +++ b/src/items/items.hpp @@ -110,7 +110,7 @@ class ItemType { ItemType(const ItemType &other) = delete; ItemType &operator=(const ItemType &other) = delete; - ItemType(ItemType &&other) = default; + ItemType(ItemType &&other) noexcept = default; ItemType &operator=(ItemType &&other) = default; bool isGroundTile() const { @@ -255,7 +255,7 @@ class ItemType { std::string parseAugmentDescription(bool inspect = false) const; std::string getFormattedAugmentDescription(const std::shared_ptr &augmentInfo) const; - void addAugment(std::string spellName, Augment_t augmentType, int32_t value) { + void addAugment(const std::string &spellName, Augment_t augmentType, int32_t value) { auto augmentInfo = std::make_shared(spellName, augmentType, value); augments.emplace_back(augmentInfo); } @@ -445,7 +445,7 @@ class Items { return dummys; } - static const std::string getAugmentNameByType(Augment_t augmentType); + static std::string getAugmentNameByType(Augment_t augmentType); static bool isAugmentWithoutValueDescription(Augment_t augmentType) { static std::vector vector = { diff --git a/src/items/items_classification.hpp b/src/items/items_classification.hpp index 601abd328ed..f3e783617a6 100644 --- a/src/items/items_classification.hpp +++ b/src/items/items_classification.hpp @@ -32,6 +32,6 @@ class ItemClassification { table.convergenceTransferPrice = convergenceTransferPrice; } - uint8_t id; + uint8_t id {}; std::map tiers; }; diff --git a/src/items/items_definitions.hpp b/src/items/items_definitions.hpp index badac532951..0c8b62bd48c 100644 --- a/src/items/items_definitions.hpp +++ b/src/items/items_definitions.hpp @@ -621,7 +621,7 @@ enum ItemParseAttributes_t { }; struct ImbuementInfo { - Imbuement* imbuement; + Imbuement* imbuement {}; uint32_t duration = 0; }; diff --git a/src/items/tile.cpp b/src/items/tile.cpp index fc16dd5799c..5b1cb1a1835 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -7,6 +7,10 @@ * Website: https://docs.opentibiabr.com/ */ +#include + +#include + #include "pch.hpp" #include "items/tile.hpp" @@ -57,7 +61,7 @@ bool Tile::hasProperty(ItemProperty prop) const { } } -bool Tile::hasProperty(std::shared_ptr exclude, ItemProperty prop) const { +bool Tile::hasProperty(const std::shared_ptr &exclude, ItemProperty prop) const { if (!exclude) { g_logger().error("[{}]: exclude is nullptr", __FUNCTION__); return false; @@ -149,9 +153,9 @@ std::shared_ptr Tile::getTeleportItem() const { } if (const TileItemVector* items = getItemList()) { - for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { - if ((*it)->getTeleport()) { - return (*it)->getTeleport(); + for (const auto &item : std::ranges::reverse_view(*items)) { + if (item->getTeleport()) { + return item->getTeleport(); } } } @@ -168,9 +172,9 @@ std::shared_ptr Tile::getFieldItem() const { } if (const TileItemVector* items = getItemList()) { - for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { - if ((*it)->getMagicField()) { - return (*it)->getMagicField(); + for (const auto &item : std::ranges::reverse_view(*items)) { + if (item->getMagicField()) { + return item->getMagicField(); } } } @@ -187,9 +191,9 @@ std::shared_ptr Tile::getTrashHolder() const { } if (const TileItemVector* items = getItemList()) { - for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { - if ((*it)->getTrashHolder()) { - return (*it)->getTrashHolder(); + for (const auto &item : std::ranges::reverse_view(*items)) { + if (item->getTrashHolder()) { + return item->getTrashHolder(); } } } @@ -206,9 +210,9 @@ std::shared_ptr Tile::getMailbox() const { } if (const TileItemVector* items = getItemList()) { - for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { - if ((*it)->getMailbox()) { - return (*it)->getMailbox(); + for (const auto &item : std::ranges::reverse_view(*items)) { + if (item->getMailbox()) { + return item->getMailbox(); } } } @@ -225,9 +229,9 @@ std::shared_ptr Tile::getBedItem() const { } if (const TileItemVector* items = getItemList()) { - for (auto it = items->rbegin(), end = items->rend(); it != end; ++it) { - if ((*it)->getBed()) { - return (*it)->getBed(); + for (const auto &item : std::ranges::reverse_view(*items)) { + if (item->getBed()) { + return item->getBed(); } } } @@ -252,10 +256,10 @@ std::shared_ptr Tile::getBottomCreature() const { return nullptr; } -std::shared_ptr Tile::getTopVisibleCreature(std::shared_ptr creature) const { +std::shared_ptr Tile::getTopVisibleCreature(const std::shared_ptr &creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player && player->isAccessPlayer()) { return getTopCreature(); } @@ -268,7 +272,7 @@ std::shared_ptr Tile::getTopVisibleCreature(std::shared_ptr } else { for (auto &tileCreature : *creatures) { if (!tileCreature->isInvisible()) { - std::shared_ptr player = tileCreature->getPlayer(); + const auto player = tileCreature->getPlayer(); if (!player || !player->isInGhostMode()) { return tileCreature; } @@ -279,25 +283,25 @@ std::shared_ptr Tile::getTopVisibleCreature(std::shared_ptr return nullptr; } -std::shared_ptr Tile::getBottomVisibleCreature(std::shared_ptr creature) const { +std::shared_ptr Tile::getBottomVisibleCreature(const std::shared_ptr &creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player && player->isAccessPlayer()) { return getBottomCreature(); } - for (auto it = creatures->rbegin(), end = creatures->rend(); it != end; ++it) { - if (creature->canSeeCreature(*it)) { - return *it; + for (const auto &it : std::ranges::reverse_view(*creatures)) { + if (creature->canSeeCreature(it)) { + return it; } } } else { - for (auto it = creatures->rbegin(), end = creatures->rend(); it != end; ++it) { - if (!(*it)->isInvisible()) { - std::shared_ptr player = (*it)->getPlayer(); + for (const auto &creature : std::ranges::reverse_view(*creatures)) { + if (!creature->isInvisible()) { + const auto player = creature->getPlayer(); if (!player || !player->isInGhostMode()) { - return *it; + return creature; } } } @@ -336,8 +340,8 @@ std::shared_ptr Tile::getItemByTopOrder(int32_t topOrder) { return nullptr; } -std::shared_ptr Tile::getTopVisibleThing(std::shared_ptr creature) { - std::shared_ptr thing = getTopVisibleCreature(creature); +std::shared_ptr Tile::getTopVisibleThing(const std::shared_ptr &creature) { + const auto &thing = getTopVisibleCreature(creature); if (thing) { return thing; } @@ -362,7 +366,7 @@ std::shared_ptr Tile::getTopVisibleThing(std::shared_ptr creatu return ground; } -void Tile::onAddTileItem(std::shared_ptr item) { +void Tile::onAddTileItem(const std::shared_ptr &item) { if ((item->hasProperty(CONST_PROP_MOVABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(static_self_cast()); if (it != g_game().browseFields.end()) { @@ -422,7 +426,7 @@ void Tile::onAddTileItem(std::shared_ptr item) { } // Clear any existing carpet - for (auto tileItem : *tile->getItemList()) { + for (const auto &tileItem : *tile->getItemList()) { if (tileItem && tileItem->isCarpet()) { tile->removeThing(tileItem, tileItem->getItemCount()); } @@ -435,7 +439,7 @@ void Tile::onAddTileItem(std::shared_ptr item) { } } -void Tile::onUpdateTileItem(std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType) { +void Tile::onUpdateTileItem(const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType) { if ((newItem->hasProperty(CONST_PROP_MOVABLE) || newItem->getContainer()) || (newItem->isWrapable() && newItem->hasProperty(CONST_PROP_MOVABLE) && !oldItem->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(getTile()); if (it != g_game().browseFields.end()) { @@ -477,7 +481,7 @@ void Tile::onUpdateTileItem(std::shared_ptr oldItem, const ItemType &oldTy } } -void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector &oldStackPosVector, std::shared_ptr item) { +void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector &oldStackPosVector, const std::shared_ptr &item) { if ((item->hasProperty(CONST_PROP_MOVABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { auto it = g_game().browseFields.find(getTile()); if (it != g_game().browseFields.end()) { @@ -498,14 +502,14 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< // send to client size_t i = 0; - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { if (std::shared_ptr tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendRemoveTileThing(cylinderMapPos, oldStackPosVector[i++]); } } // event methods - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { spectator->onRemoveTileItem(static_self_cast(), cylinderMapPos, iType, item); } @@ -517,7 +521,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< } bool ret = false; - for (auto toCheck : *items) { + for (const auto &toCheck : *items) { if (toCheck->isCleanable()) { ret = true; break; @@ -551,7 +555,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< continue; } - for (auto tileItem : *tile->getItemList()) { + for (const auto &tileItem : *tile->getItemList()) { if (tileItem && tileItem->getID() == item->getID()) { tile->removeThing(tileItem, tileItem->getItemCount()); } @@ -564,7 +568,7 @@ void Tile::onUpdateTile(const CreatureVector &spectators) { const Position &cylinderMapPos = getPosition(); // send to clients - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { spectator->getPlayer()->sendUpdateTile(getTile(), cylinderMapPos); } } @@ -659,7 +663,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr &thing, uint32_ } const CreatureVector* creatures = getCreatures(); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, tileFlags) && !player->isAccessPlayer()) { for (auto &tileCreature : *creatures) { if (!player->canWalkthrough(tileCreature)) { @@ -851,7 +855,7 @@ ReturnValue Tile::queryRemove(const std::shared_ptr &thing, uint32_t coun return RETURNVALUE_NOTPOSSIBLE; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -1000,7 +1004,7 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { CreatureVector* creatures = makeCreatures(); creatures->insert(creatures->begin(), creature); } else { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1032,7 +1036,7 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { if (itemType.isSplash() && items) { // remove old splash if exists for (ItemVector::const_iterator it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - std::shared_ptr oldSplash = *it; + const std::shared_ptr &oldSplash = *it; if (!Item::items[oldSplash->getID()].isSplash()) { continue; } @@ -1101,7 +1105,7 @@ void Tile::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t c return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1118,7 +1122,7 @@ void Tile::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t c void Tile::replaceThing(uint32_t index, std::shared_ptr thing) { int32_t pos = index; - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1200,7 +1204,7 @@ void Tile::removeThing(std::shared_ptr thing, uint32_t count) { return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return; } @@ -1271,7 +1275,7 @@ void Tile::removeThing(std::shared_ptr thing, uint32_t count) { } } -void Tile::removeCreature(std::shared_ptr creature) { +void Tile::removeCreature(const std::shared_ptr &creature) { g_game().map.getMapSector(tilePos.x, tilePos.y)->removeCreature(creature); removeThing(creature, 0); } @@ -1287,7 +1291,7 @@ int32_t Tile::getThingIndex(std::shared_ptr thing) const { const TileItemVector* items = getItemList(); if (items) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item && item->isAlwaysOnTop()) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { ++n; @@ -1314,7 +1318,7 @@ int32_t Tile::getThingIndex(std::shared_ptr thing) const { } if (items) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item && !item->isAlwaysOnTop()) { for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { ++n; @@ -1327,7 +1331,7 @@ int32_t Tile::getThingIndex(std::shared_ptr thing) const { return -1; } -int32_t Tile::getClientIndexOfCreature(std::shared_ptr player, std::shared_ptr creature) const { +int32_t Tile::getClientIndexOfCreature(const std::shared_ptr &player, const std::shared_ptr &creature) const { int32_t n; if (ground) { n = 1; @@ -1341,10 +1345,10 @@ int32_t Tile::getClientIndexOfCreature(std::shared_ptr player, std::shar } if (const CreatureVector* creatures = getCreatures()) { - for (auto it = creatures->rbegin(); it != creatures->rend(); ++it) { - if (*it == creature) { + for (const auto &it : std::ranges::reverse_view(*creatures)) { + if (it == creature) { return n; - } else if (player->canSeeCreature(*it)) { + } else if (player->canSeeCreature(it)) { ++n; } } @@ -1352,7 +1356,7 @@ int32_t Tile::getClientIndexOfCreature(std::shared_ptr player, std::shar return -1; } -int32_t Tile::getStackposOfCreature(std::shared_ptr player, std::shared_ptr creature) const { +int32_t Tile::getStackposOfCreature(const std::shared_ptr &player, const std::shared_ptr &creature) const { int32_t n; if (ground) { n = 1; @@ -1369,10 +1373,10 @@ int32_t Tile::getStackposOfCreature(std::shared_ptr player, std::shared_ } if (const CreatureVector* creatures = getCreatures()) { - for (auto it = creatures->rbegin(); it != creatures->rend(); ++it) { - if (*it == creature) { + for (const auto &it : std::ranges::reverse_view(*creatures)) { + if (it == creature) { return n; - } else if (player->canSeeCreature(*it)) { + } else if (player->canSeeCreature(it)) { if (++n >= 10) { return -1; } @@ -1382,7 +1386,7 @@ int32_t Tile::getStackposOfCreature(std::shared_ptr player, std::shared_ return -1; } -int32_t Tile::getStackposOfItem(std::shared_ptr player, std::shared_ptr item) const { +int32_t Tile::getStackposOfItem(const std::shared_ptr &player, const std::shared_ptr &item) const { int32_t n = 0; if (ground) { if (ground == item) { @@ -1544,7 +1548,7 @@ void Tile::postRemoveNotification(std::shared_ptr thing, std::shared_ptr< if (creature) { g_moveEvents().onCreatureMove(creature, static_self_cast(), MOVE_EVENT_STEP_OUT); } else { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item) { g_moveEvents().onItemMove(item, static_self_cast(), false); } @@ -1558,7 +1562,7 @@ void Tile::internalAddThing(std::shared_ptr thing) { } if (auto house = thing->getTile()->getHouse()) { - if (std::shared_ptr item = thing->getItem()) { + if (const auto item = thing->getItem()) { if (item->getParent().get() != this) { return; } @@ -1588,7 +1592,7 @@ void Tile::internalAddThing(uint32_t, std::shared_ptr thing) { CreatureVector* creatures = makeCreatures(); creatures->insert(creatures->begin(), creature); } else { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return; } @@ -1808,7 +1812,7 @@ bool Tile::isMovableBlocking() const { std::shared_ptr Tile::getUseItem(int32_t index) const { const TileItemVector* items = getItemList(); - if (!items || items->size() == 0) { + if (!items || items->empty()) { return ground; } @@ -1821,7 +1825,7 @@ std::shared_ptr Tile::getUseItem(int32_t index) const { std::shared_ptr Tile::getDoorItem() const { const TileItemVector* items = getItemList(); - if (!items || items->size() == 0) { + if (!items || items->empty()) { return ground; } @@ -1837,7 +1841,7 @@ std::shared_ptr Tile::getDoorItem() const { return nullptr; } -void Tile::addZone(std::shared_ptr zone) { +void Tile::addZone(const std::shared_ptr &zone) { zones.emplace(zone); const auto &items = getItemList(); if (items) { diff --git a/src/items/tile.hpp b/src/items/tile.hpp index 71f9d4ae09c..f414677eced 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -104,7 +104,7 @@ class Tile : public Cylinder, public SharedObject { static const std::shared_ptr &nullptr_tile; Tile(uint16_t x, uint16_t y, uint8_t z) : tilePos(x, y, z) { } - virtual ~Tile() {}; + ~Tile() override {}; // non-copyable Tile(const Tile &) = delete; @@ -121,14 +121,14 @@ class Tile : public Cylinder, public SharedObject { return nullptr; } - int32_t getThrowRange() const override final { + int32_t getThrowRange() const final { return 0; } - bool isPushable() override final { + bool isPushable() final { return false; } - std::shared_ptr getTile() override final { + std::shared_ptr getTile() final { return static_self_cast(); } @@ -144,13 +144,13 @@ class Tile : public Cylinder, public SharedObject { std::shared_ptr getTopCreature() const; std::shared_ptr getBottomCreature() const; - std::shared_ptr getTopVisibleCreature(std::shared_ptr creature) const; + std::shared_ptr getTopVisibleCreature(const std::shared_ptr &creature) const; - std::shared_ptr getBottomVisibleCreature(std::shared_ptr creature) const; + std::shared_ptr getBottomVisibleCreature(const std::shared_ptr &creature) const; std::shared_ptr getTopTopItem() const; std::shared_ptr getTopDownItem() const; bool isMovableBlocking() const; - std::shared_ptr getTopVisibleThing(std::shared_ptr creature); + std::shared_ptr getTopVisibleThing(const std::shared_ptr &creature); std::shared_ptr getItemByTopOrder(int32_t topOrder); size_t getThingCount() const { @@ -167,7 +167,7 @@ class Tile : public Cylinder, public SharedObject { uint32_t getDownItemCount() const; bool hasProperty(ItemProperty prop) const; - bool hasProperty(std::shared_ptr exclude, ItemProperty prop) const; + bool hasProperty(const std::shared_ptr &exclude, ItemProperty prop) const; bool hasFlag(uint32_t flag) const { return hasBitSet(flag, this->flags); @@ -178,7 +178,7 @@ class Tile : public Cylinder, public SharedObject { void resetFlag(uint32_t flag) { this->flags &= ~flag; } - void addZone(std::shared_ptr zone); + void addZone(const std::shared_ptr &zone); void clearZones(); auto getZones() const { @@ -200,48 +200,48 @@ class Tile : public Cylinder, public SharedObject { bool hasHeight(uint32_t n) const; - std::string getDescription(int32_t lookDistance) override final; + std::string getDescription(int32_t lookDistance) final; - int32_t getClientIndexOfCreature(std::shared_ptr player, std::shared_ptr creature) const; - int32_t getStackposOfCreature(std::shared_ptr player, std::shared_ptr creature) const; - int32_t getStackposOfItem(std::shared_ptr player, std::shared_ptr item) const; + int32_t getClientIndexOfCreature(const std::shared_ptr &player, const std::shared_ptr &creature) const; + int32_t getStackposOfCreature(const std::shared_ptr &player, const std::shared_ptr &creature) const; + int32_t getStackposOfItem(const std::shared_ptr &player, const std::shared_ptr &item) const; // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; - ReturnValue queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override final; + ReturnValue queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; ReturnValue queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr actor = nullptr) override; std::shared_ptr queryDestination(int32_t &index, const std::shared_ptr &thing, std::shared_ptr* destItem, uint32_t &flags) override; std::vector> getSurroundingTiles(); - void addThing(std::shared_ptr thing) override final; + void addThing(std::shared_ptr thing) final; void addThing(int32_t index, std::shared_ptr thing) override; void updateTileFlags(const std::shared_ptr &item); - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override final; - void replaceThing(uint32_t index, std::shared_ptr thing) override final; + void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) final; + void replaceThing(uint32_t index, std::shared_ptr thing) final; - void removeThing(std::shared_ptr thing, uint32_t count) override final; + void removeThing(std::shared_ptr thing, uint32_t count) final; - void removeCreature(std::shared_ptr creature); + void removeCreature(const std::shared_ptr &creature); - int32_t getThingIndex(std::shared_ptr thing) const override final; - size_t getFirstIndex() const override final; - size_t getLastIndex() const override final; - uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override final; - std::shared_ptr getThing(size_t index) const override final; + int32_t getThingIndex(std::shared_ptr thing) const final; + size_t getFirstIndex() const final; + size_t getLastIndex() const final; + uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const final; + std::shared_ptr getThing(size_t index) const final; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override final; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override final; + void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; void internalAddThing(std::shared_ptr thing) override; void virtual internalAddThing(uint32_t index, std::shared_ptr thing) override; - const Position &getPosition() override final { + const Position &getPosition() final { return tilePos; } - bool isRemoved() override final { + bool isRemoved() final { return false; } @@ -262,9 +262,9 @@ class Tile : public Cylinder, public SharedObject { } private: - void onAddTileItem(std::shared_ptr item); - void onUpdateTileItem(std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType); - void onRemoveTileItem(const CreatureVector &spectators, const std::vector &oldStackPosVector, std::shared_ptr item); + void onAddTileItem(const std::shared_ptr &item); + void onUpdateTileItem(const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType); + void onRemoveTileItem(const CreatureVector &spectators, const std::vector &oldStackPosVector, const std::shared_ptr &item); void onUpdateTile(const CreatureVector &spectators); void setTileFlags(const std::shared_ptr &item); diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index 65676a75a37..4da1bc6a48d 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -13,7 +13,7 @@ #include "game/game.hpp" ReturnValue TrashHolder::queryAdd(int32_t, const std::shared_ptr &thing, uint32_t, uint32_t, std::shared_ptr actor) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOERROR; } @@ -45,7 +45,7 @@ void TrashHolder::addThing(int32_t, std::shared_ptr thing) { return; } - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return; } diff --git a/src/items/trashholder.hpp b/src/items/trashholder.hpp index 771c8687fbd..424ad5cd03e 100644 --- a/src/items/trashholder.hpp +++ b/src/items/trashholder.hpp @@ -21,7 +21,7 @@ class TrashHolder final : public Item, public Cylinder { return static_self_cast(); } - std::shared_ptr getCylinder() override final { + std::shared_ptr getCylinder() final { return getTrashHolder(); } diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 69d20d43e06..aaaafa8f179 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "creatures/combat/combat.hpp" @@ -19,7 +21,7 @@ Weapons::Weapons() = default; Weapons::~Weapons() = default; -const WeaponShared_ptr Weapons::getWeapon(std::shared_ptr item) const { +WeaponShared_ptr Weapons::getWeapon(const std::shared_ptr &item) const { if (!item) { return nullptr; } @@ -54,7 +56,7 @@ void Weapons::clear(bool isFromXML /*= false*/) { weapons.clear(); } -bool Weapons::registerLuaEvent(WeaponShared_ptr event, bool fromXML /*= false*/) { +bool Weapons::registerLuaEvent(const WeaponShared_ptr &event, bool fromXML /*= false*/) { weapons[event->getID()] = event; if (fromXML) { event->setFromXML(fromXML); @@ -81,7 +83,7 @@ void Weapon::configureWeapon(const ItemType &it) { id = it.id; } -int32_t Weapon::playerWeaponCheck(std::shared_ptr player, std::shared_ptr target, uint8_t shootRange) const { +int32_t Weapon::playerWeaponCheck(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t shootRange) const { const Position &playerPos = player->getPosition(); const Position &targetPos = target->getPosition(); if (playerPos.z != targetPos.z) { @@ -164,7 +166,7 @@ CombatDamage Weapon::getCombatDamage(CombatDamage combat, std::shared_ptr player, std::shared_ptr target) { +bool Weapon::useFist(const std::shared_ptr &player, const std::shared_ptr &target) { if (!Position::areInRange<1, 1>(player->getPosition(), target->getPosition())) { return false; } @@ -194,7 +196,7 @@ bool Weapon::useFist(std::shared_ptr player, std::shared_ptr t return true; } -void Weapon::internalUseWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target, int32_t damageModifier, int32_t cleavePercent) const { +void Weapon::internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target, int32_t damageModifier, int32_t cleavePercent) const { if (player) { if (params.soundCastEffect == SoundEffect_t::SILENCE) { g_game().sendDoubleSoundEffect(player->getPosition(), player->getHitSoundEffect(), player->getAttackSoundEffect(), player); @@ -258,7 +260,7 @@ void Weapon::internalUseWeapon(std::shared_ptr player, std::shared_ptrgetTile()); } -void Weapon::internalUseWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr tile) const { +void Weapon::internalUseWeapon(const std::shared_ptr &player, const auto item, const std::shared_ptr &tile) const { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_TARGETPOSITION; @@ -269,10 +271,10 @@ void Weapon::internalUseWeapon(std::shared_ptr player, std::shared_ptrgetPosition(), CONST_ME_POFF); g_game().sendSingleSoundEffect(tile->getPosition(), SoundEffect_t::PHYSICAL_RANGE_MISS, player); } - onUsedWeapon(player, item, tile); + onUsedWeapon(player, std::move(item), tile); } -void Weapon::onUsedWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr destTile) const { +void Weapon::onUsedWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &destTile) const { if (!player->hasFlag(PlayerFlags_t::NotGainSkill)) { skills_t skillType; uint32_t skillPoint; @@ -331,7 +333,7 @@ void Weapon::onUsedWeapon(std::shared_ptr player, std::shared_ptr } } -uint32_t Weapon::getManaCost(std::shared_ptr player) const { +uint32_t Weapon::getManaCost(const std::shared_ptr &player) const { if (mana != 0) { return mana; } @@ -343,7 +345,7 @@ uint32_t Weapon::getManaCost(std::shared_ptr player) const { return (player->getMaxMana() * manaPercent) / 100; } -int32_t Weapon::getHealthCost(std::shared_ptr player) const { +int32_t Weapon::getHealthCost(const std::shared_ptr &player) const { if (health != 0) { return health; } @@ -355,9 +357,9 @@ int32_t Weapon::getHealthCost(std::shared_ptr player) const { return (player->getMaxHealth() * healthPercent) / 100; } -bool Weapon::executeUseWeapon(std::shared_ptr player, const LuaVariant &var) const { +bool Weapon::executeUseWeapon(const std::shared_ptr &player, const LuaVariant &var) const { // onUseWeapon(player, var) - if (!getScriptInterface()->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { std::string playerName = player ? player->getName() : "Player nullptr"; g_logger().error("[Weapon::executeUseWeapon - Player {} weaponId {}]" "Call stack overflow. Too many lua script calls being nested.", @@ -365,7 +367,7 @@ bool Weapon::executeUseWeapon(std::shared_ptr player, const LuaVariant & return false; } - ScriptEnvironment* env = getScriptInterface()->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -373,12 +375,12 @@ bool Weapon::executeUseWeapon(std::shared_ptr player, const LuaVariant & getScriptInterface()->pushFunction(getScriptId()); LuaScriptInterface::pushUserdata(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - getScriptInterface()->pushVariant(L, var); + LuaScriptInterface::pushVariant(L, var); return getScriptInterface()->callFunction(2); } -void Weapon::decrementItemCount(std::shared_ptr item) { +void Weapon::decrementItemCount(const std::shared_ptr &item) { uint16_t count = item->getItemCount(); if (count > 1) { g_game().transformItem(item, item->getID(), count - 1); diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 59cc23636e2..527c6f61406 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -39,12 +39,12 @@ class Weapons final : public Scripts { return inject(); } - const WeaponShared_ptr getWeapon(std::shared_ptr item) const; + WeaponShared_ptr getWeapon(const std::shared_ptr &item) const; static int32_t getMaxMeleeDamage(int32_t attackSkill, int32_t attackValue); static int32_t getMaxWeaponDamage(uint32_t level, int32_t attackSkill, int32_t attackValue, float attackFactor, bool isMelee); - bool registerLuaEvent(WeaponShared_ptr event, bool fromXML = false); + bool registerLuaEvent(const WeaponShared_ptr &event, bool fromXML = false); void clear(bool isFromXML = false); private: @@ -62,9 +62,9 @@ class Weapon : public Script { return false; } - int32_t playerWeaponCheck(std::shared_ptr player, std::shared_ptr target, uint8_t shootRange) const; - static bool useFist(std::shared_ptr player, std::shared_ptr target); - virtual bool useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const; + int32_t playerWeaponCheck(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t shootRange) const; + static bool useFist(const std::shared_ptr &player, const std::shared_ptr &target); + virtual bool useWeapon(const std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const; virtual int32_t getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const = 0; virtual int32_t getElementDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const = 0; @@ -162,7 +162,7 @@ class Weapon : public Script { wieldInfo |= info; } - void addVocWeaponMap(std::string vocName) { + void addVocWeaponMap(const std::string &vocName) { int32_t vocationId = g_vocations().getVocationId(vocName); if (vocationId != -1) { vocWeaponMap[vocationId] = true; @@ -224,17 +224,17 @@ class Weapon : public Script { bool calculateSkillFormula(const std::shared_ptr &player, int32_t &attackSkill, int32_t &attackValue, float &attackFactor, int16_t &elementAttack, CombatDamage &damage, bool useCharges = false) const; protected: - void internalUseWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target, int32_t damageModifier, int32_t cleavePercent = 0) const; - void internalUseWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr tile) const; + void internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target, int32_t damageModifier, int32_t cleavePercent = 0) const; + void internalUseWeapon(const std::shared_ptr &player, const auto item, const std::shared_ptr &tile) const; private: virtual bool getSkillType(std::shared_ptr, std::shared_ptr, skills_t &, uint32_t &) const { return false; } - uint32_t getManaCost(std::shared_ptr player) const; - int32_t getHealthCost(std::shared_ptr player) const; - bool executeUseWeapon(std::shared_ptr player, const LuaVariant &var) const; + uint32_t getManaCost(const std::shared_ptr &player) const; + int32_t getHealthCost(const std::shared_ptr &player) const; + bool executeUseWeapon(const std::shared_ptr &player, const LuaVariant &var) const; uint16_t id = 0; @@ -252,11 +252,11 @@ class Weapon : public Script { bool premium = false; bool wieldUnproperly = false; bool m_isDisabledChain = false; - std::string vocationString = ""; + std::string vocationString; - void onUsedWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr destTile) const; + void onUsedWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &destTile) const; - static void decrementItemCount(std::shared_ptr item); + static void decrementItemCount(const std::shared_ptr &item); WeaponAction_t action = WEAPONACTION_NONE; CombatParams params; diff --git a/src/kv/kv.hpp b/src/kv/kv.hpp index fa32461b24b..f645ce87fee 100644 --- a/src/kv/kv.hpp +++ b/src/kv/kv.hpp @@ -18,6 +18,7 @@ #include #include #include + #include #endif #include "lib/logging/logger.hpp" @@ -91,8 +92,8 @@ class KVStore : public KV { store_.clear(); } - std::shared_ptr scoped(const std::string &scope) override final; - std::unordered_set keys(const std::string &prefix = ""); + std::shared_ptr scoped(const std::string &scope) final; + std::unordered_set keys(const std::string &prefix = "") override; protected: phmap::parallel_flat_hash_map::iterator>> getStore() { @@ -121,8 +122,8 @@ class KVStore : public KV { class ScopedKV final : public KV { public: - ScopedKV(Logger &logger, KVStore &rootKV, const std::string &prefix) : - logger(logger), rootKV_(rootKV), prefix_(prefix) { } + ScopedKV(Logger &logger, KVStore &rootKV, std::string prefix) : + logger(logger), rootKV_(rootKV), prefix_(std::move(prefix)) { } void set(const std::string &key, const std::initializer_list &init_list) override { rootKV_.set(buildKey(key), init_list); @@ -151,7 +152,7 @@ class ScopedKV final : public KV { return rootKV_.saveAll(); } - std::shared_ptr scoped(const std::string &scope) override final { + std::shared_ptr scoped(const std::string &scope) final { logger.trace("ScopedKV::scoped({})", buildKey(scope)); return std::make_shared(logger, rootKV_, buildKey(scope)); } diff --git a/src/kv/value_wrapper.cpp b/src/kv/value_wrapper.cpp index 78f828248a1..2de2b290275 100644 --- a/src/kv/value_wrapper.cpp +++ b/src/kv/value_wrapper.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "kv/value_wrapper.hpp" @@ -15,8 +17,8 @@ ValueWrapper::ValueWrapper(uint64_t timestamp) : timestamp_(timestamp == 0 ? getTimeMsNow() : timestamp) { } -ValueWrapper::ValueWrapper(const ValueVariant &value, uint64_t timestamp) : - data_(value), timestamp_(timestamp == 0 ? getTimeMsNow() : timestamp) { } +ValueWrapper::ValueWrapper(ValueVariant value, uint64_t timestamp) : + data_(std::move(value)), timestamp_(timestamp == 0 ? getTimeMsNow() : timestamp) { } ValueWrapper::ValueWrapper(const std::string &value, uint64_t timestamp) : data_(value), timestamp_(timestamp == 0 ? getTimeMsNow() : timestamp) { } diff --git a/src/kv/value_wrapper.hpp b/src/kv/value_wrapper.hpp index 0b388187dc3..2af0747e401 100644 --- a/src/kv/value_wrapper.hpp +++ b/src/kv/value_wrapper.hpp @@ -33,7 +33,7 @@ using ValueVariant = std::variant> { core::init {} } { } template - /*non explicit*/ injector(const T &bindings) : + /*non explicit*/ explicit injector(const T &bindings) : injector() { install(bindings); } diff --git a/src/lib/di/shared.hpp b/src/lib/di/shared.hpp index c1e2f0c6743..f57257d7abd 100644 --- a/src/lib/di/shared.hpp +++ b/src/lib/di/shared.hpp @@ -28,7 +28,7 @@ namespace extension { #if !defined(BOOST_DI_NOT_THREAD_SAFE) //<> - explicit scope(scope &&other) noexcept : + scope(scope &&other) noexcept : scope(std::move(other), std::scoped_lock(other.mutex_)) { } //<> scope(scope &&other, const std::scoped_lock &) noexcept : diff --git a/src/lua/callbacks/creaturecallback.cpp b/src/lua/callbacks/creaturecallback.cpp index 11e33a9b1e1..c2df33499ad 100644 --- a/src/lua/callbacks/creaturecallback.cpp +++ b/src/lua/callbacks/creaturecallback.cpp @@ -14,7 +14,7 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { return false; } - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { auto targetCreature = m_targetCreature.lock(); g_logger().error( "[CreatureCallback::startScriptInterface] - {} {} Call stack overflow. Too many lua script calls being nested.", @@ -24,8 +24,7 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { return false; } - scriptInterface - ->getScriptEnv() + LuaScriptInterface::getScriptEnv() ->setScriptId(scriptId, scriptInterface); L = scriptInterface->getLuaState(); @@ -35,12 +34,12 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { return true; } -void CreatureCallback::pushSpecificCreature(std::shared_ptr creature) { +void CreatureCallback::pushSpecificCreature(const std::shared_ptr &creature) { if (std::shared_ptr npc = creature->getNpc()) { LuaScriptInterface::pushUserdata(L, npc); } else if (std::shared_ptr monster = creature->getMonster()) { LuaScriptInterface::pushUserdata(L, monster); - } else if (std::shared_ptr player = creature->getPlayer()) { + } else if (const auto player = creature->getPlayer()) { LuaScriptInterface::pushUserdata(L, player); } else { return; @@ -50,7 +49,7 @@ void CreatureCallback::pushSpecificCreature(std::shared_ptr creature) LuaScriptInterface::setMetatable(L, -1, getCreatureClass(creature)); } -std::string CreatureCallback::getCreatureClass(std::shared_ptr creature) { +std::string CreatureCallback::getCreatureClass(const std::shared_ptr &creature) { if (!creature) { return ""; } diff --git a/src/lua/callbacks/creaturecallback.hpp b/src/lua/callbacks/creaturecallback.hpp index f7665720410..7d284623ee8 100644 --- a/src/lua/callbacks/creaturecallback.hpp +++ b/src/lua/callbacks/creaturecallback.hpp @@ -15,19 +15,19 @@ class Creature; class CreatureCallback { public: - CreatureCallback(LuaScriptInterface* scriptInterface, std::shared_ptr targetCreature) : + CreatureCallback(LuaScriptInterface* scriptInterface, const std::shared_ptr &targetCreature) : scriptInterface(scriptInterface), m_targetCreature(targetCreature) {}; - ~CreatureCallback() { } + ~CreatureCallback() = default; bool startScriptInterface(int32_t scriptId); - void pushSpecificCreature(std::shared_ptr creature); + void pushSpecificCreature(const std::shared_ptr &creature); bool persistLuaState() { return params > 0 && scriptInterface->callFunction(params); } - void pushCreature(std::shared_ptr creature) { + void pushCreature(const std::shared_ptr &creature) { params++; LuaScriptInterface::pushUserdata(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); @@ -54,7 +54,7 @@ class CreatureCallback { } protected: - static std::string getCreatureClass(std::shared_ptr creature); + static std::string getCreatureClass(const std::shared_ptr &creature); private: LuaScriptInterface* scriptInterface; diff --git a/src/lua/callbacks/event_callback.cpp b/src/lua/callbacks/event_callback.cpp index 950d4764338..fb9161c0633 100644 --- a/src/lua/callbacks/event_callback.cpp +++ b/src/lua/callbacks/event_callback.cpp @@ -368,7 +368,7 @@ void EventCallback::playerOnLook(const std::shared_ptr &player, const Po if (std::shared_ptr creature = thing->getCreature()) { LuaScriptInterface::pushUserdata(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - } else if (std::shared_ptr item = thing->getItem()) { + } else if (const auto item = thing->getItem()) { LuaScriptInterface::pushUserdata(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); } else { @@ -486,7 +486,7 @@ void EventCallback::playerOnRemoveCount(const std::shared_ptr &player, c getScriptInterface()->callFunction(2); } -bool EventCallback::playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPos, const Position &toPos, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { +bool EventCallback::playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPos, const Position &toPos, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) const { if (!getScriptInterface()) { g_logger().error("script interface nullptr"); return false; @@ -515,13 +515,13 @@ bool EventCallback::playerOnMoveItem(const std::shared_ptr &player, cons LuaScriptInterface::pushPosition(L, fromPos); LuaScriptInterface::pushPosition(L, toPos); - LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); - LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); + LuaScriptInterface::pushCylinder(L, fromCylinder); + LuaScriptInterface::pushCylinder(L, toCylinder); return getScriptInterface()->callFunction(7); } -void EventCallback::playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const { +void EventCallback::playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnItemMoved - " "Player {} item {}] " @@ -546,8 +546,8 @@ void EventCallback::playerOnItemMoved(const std::shared_ptr &player, con LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); - LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); + LuaScriptInterface::pushCylinder(L, fromCylinder); + LuaScriptInterface::pushCylinder(L, toCylinder); getScriptInterface()->callVoidFunction(7); } diff --git a/src/lua/callbacks/event_callback.hpp b/src/lua/callbacks/event_callback.hpp index 3558341035e..4d1333169a5 100644 --- a/src/lua/callbacks/event_callback.hpp +++ b/src/lua/callbacks/event_callback.hpp @@ -97,8 +97,8 @@ class EventCallback : public Script { void playerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance) const; void playerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance) const; bool playerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count) const; - bool playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; - void playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) const; + bool playerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) const; + void playerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) const; void playerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone) const; bool playerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition) const; void playerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) const; diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index ab92e6d029b..9e6795685ff 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -183,10 +183,10 @@ ReturnValue Actions::canUse(const std::shared_ptr &player, const Positio return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUse(std::shared_ptr player, const Position &pos, const std::shared_ptr &item) { +ReturnValue Actions::canUse(const std::shared_ptr &player, const Position &pos, const std::shared_ptr &item) { const std::shared_ptr action = getAction(item); if (action != nullptr) { - return action->canExecuteAction(std::move(player), pos); + return action->canExecuteAction(player, pos); } return RETURNVALUE_NOERROR; } @@ -236,7 +236,7 @@ std::shared_ptr Actions::getAction(const std::shared_ptr &item) { iteratePositions != actionPositionMap.end()) { if (std::shared_ptr tile = item->getTile(); tile) { - if (std::shared_ptr player = item->getHoldingPlayer(); + if (const auto player = item->getHoldingPlayer(); player && item->getTopParent() == player) { g_logger().debug("[Actions::getAction] - The position only is valid for use item in the map, player name {}", player->getName()); return nullptr; @@ -498,7 +498,7 @@ void Actions::showUseHotkeyMessage(const std::shared_ptr &player, const Action::Action(LuaScriptInterface* interface) : Script(interface) { } -ReturnValue Action::canExecuteAction(std::shared_ptr player, const Position &toPos) { +ReturnValue Action::canExecuteAction(const std::shared_ptr &player, const Position &toPos) { if (!allowFarUse) { return g_actions().canUse(player, toPos); } @@ -506,14 +506,14 @@ ReturnValue Action::canExecuteAction(std::shared_ptr player, const Posit return g_actions().canUseFar(player, toPos, checkLineOfSight, checkFloor); } -std::shared_ptr Action::getTarget(std::shared_ptr player, std::shared_ptr targetCreature, const Position &toPosition, uint8_t toStackPos) const { +std::shared_ptr Action::getTarget(const std::shared_ptr &player, std::shared_ptr targetCreature, const Position &toPosition, uint8_t toStackPos) const { if (targetCreature != nullptr) { return targetCreature; } - return g_game().internalGetThing(std::move(player), toPosition, toStackPos, 0, STACKPOS_USETARGET); + return g_game().internalGetThing(player, toPosition, toStackPos, 0, STACKPOS_USETARGET); } -bool Action::executeUse(std::shared_ptr player, std::shared_ptr item, const Position &fromPosition, std::shared_ptr target, const Position &toPosition, bool isHotkey) { +bool Action::executeUse(const std::shared_ptr &player, const std::shared_ptr &item, const Position &fromPosition, const std::shared_ptr &target, const Position &toPosition, bool isHotkey) { // onUse(player, item, fromPosition, target, toPosition, isHotkey) if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Action::executeUse - Player {}, on item {}] " @@ -535,7 +535,7 @@ bool Action::executeUse(std::shared_ptr player, std::shared_ptr it LuaScriptInterface::pushThing(L, item); LuaScriptInterface::pushPosition(L, fromPosition); - LuaScriptInterface::pushThing(L, std::move(target)); + LuaScriptInterface::pushThing(L, target); LuaScriptInterface::pushPosition(L, toPosition); LuaScriptInterface::pushBoolean(L, isHotkey); diff --git a/src/lua/creature/actions.hpp b/src/lua/creature/actions.hpp index b29e8b794db..fae38d5e0d0 100644 --- a/src/lua/creature/actions.hpp +++ b/src/lua/creature/actions.hpp @@ -21,7 +21,7 @@ class Action : public Script { explicit Action(LuaScriptInterface* interface); // Scripting - virtual bool executeUse(std::shared_ptr player, std::shared_ptr item, const Position &fromPosition, std::shared_ptr target, const Position &toPosition, bool isHotkey); + virtual bool executeUse(const std::shared_ptr &player, const std::shared_ptr &item, const Position &fromPosition, const std::shared_ptr &target, const Position &toPosition, bool isHotkey); bool getAllowFarUse() const { return allowFarUse; @@ -96,13 +96,13 @@ class Action : public Script { positions.emplace_back(pos); } - virtual ReturnValue canExecuteAction(std::shared_ptr player, const Position &toPos); + virtual ReturnValue canExecuteAction(const std::shared_ptr &player, const Position &toPos); virtual bool hasOwnErrorHandler() { return false; } - virtual std::shared_ptr getTarget(std::shared_ptr player, std::shared_ptr targetCreature, const Position &toPosition, uint8_t toStackPos) const; + virtual std::shared_ptr getTarget(const std::shared_ptr &player, std::shared_ptr targetCreature, const Position &toPosition, uint8_t toStackPos) const; private: std::string getScriptTypeName() const override { @@ -147,7 +147,7 @@ class Actions final : public Scripts { bool useItemEx(const std::shared_ptr &player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, const std::shared_ptr &item, bool isHotkey, const std::shared_ptr &creature = nullptr); ReturnValue canUse(const std::shared_ptr &player, const Position &pos); - ReturnValue canUse(std::shared_ptr player, const Position &pos, const std::shared_ptr &item); + ReturnValue canUse(const std::shared_ptr &player, const Position &pos, const std::shared_ptr &item); ReturnValue canUseFar(const std::shared_ptr &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor); bool registerLuaItemEvent(const std::shared_ptr &action); diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 78bd8ede9bc..c8782d1734f 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -593,7 +593,7 @@ void Events::eventPlayerOnLook(const std::shared_ptr &player, const Posi if (std::shared_ptr creature = thing->getCreature()) { LuaScriptInterface::pushUserdata(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - } else if (std::shared_ptr item = thing->getItem()) { + } else if (const auto item = thing->getItem()) { LuaScriptInterface::pushUserdata(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); } else { @@ -731,7 +731,7 @@ bool Events::eventPlayerOnRemoveCount(const std::shared_ptr &player, con return scriptInterface.callFunction(2); } -bool Events::eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { +bool Events::eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) { // Player:onMoveItem(item, count, fromPosition, toPosition) or Player.onMoveItem(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnMoveItem == -1) { return true; @@ -761,13 +761,13 @@ bool Events::eventPlayerOnMoveItem(const std::shared_ptr &player, const LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); - LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); + LuaScriptInterface::pushCylinder(L, fromCylinder); + LuaScriptInterface::pushCylinder(L, toCylinder); return scriptInterface.callFunction(7); } -void Events::eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder) { +void Events::eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder) { // Player:onItemMoved(item, count, fromPosition, toPosition) or Player.onItemMoved(self, item, count, fromPosition, toPosition, fromCylinder, toCylinder) if (info.playerOnItemMoved == -1) { return; @@ -797,8 +797,8 @@ void Events::eventPlayerOnItemMoved(const std::shared_ptr &player, const LuaScriptInterface::pushPosition(L, fromPosition); LuaScriptInterface::pushPosition(L, toPosition); - LuaScriptInterface::pushCylinder(L, std::move(fromCylinder)); - LuaScriptInterface::pushCylinder(L, std::move(toCylinder)); + LuaScriptInterface::pushCylinder(L, fromCylinder); + LuaScriptInterface::pushCylinder(L, toCylinder); scriptInterface.callVoidFunction(7); } @@ -1247,7 +1247,7 @@ void Events::eventPlayerOnRequestQuestLine(const std::shared_ptr &player scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) { +void Events::eventPlayerOnInventoryUpdate(const auto player, const std::shared_ptr &item, Slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { return; diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index 88dbf1f812b..c2f52f1b4e1 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -99,8 +99,8 @@ class Events { void eventPlayerOnLookInBattleList(const std::shared_ptr &player, const std::shared_ptr &creature, int32_t lookDistance); void eventPlayerOnLookInTrade(const std::shared_ptr &player, std::shared_ptr partner, const std::shared_ptr &item, int32_t lookDistance); bool eventPlayerOnLookInShop(const std::shared_ptr &player, const ItemType* itemType, uint8_t count); - bool eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); - void eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, std::shared_ptr fromCylinder, std::shared_ptr toCylinder); + bool eventPlayerOnMoveItem(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder); + void eventPlayerOnItemMoved(const std::shared_ptr &player, const std::shared_ptr &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr &fromCylinder, const std::shared_ptr &toCylinder); void eventPlayerOnChangeZone(const std::shared_ptr &player, ZoneType_t zone); bool eventPlayerOnMoveCreature(const std::shared_ptr &player, const std::shared_ptr &creature, const Position &fromPosition, const Position &toPosition); void eventPlayerOnReportRuleViolation(const std::shared_ptr &player, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation); @@ -116,7 +116,7 @@ class Events { void eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId); void eventOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime); void eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage); - void eventPlayerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip); + void eventPlayerOnInventoryUpdate(const auto player, const std::shared_ptr &item, Slots_t slot, bool equip); // Monster void eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse); diff --git a/src/lua/creature/movement.hpp b/src/lua/creature/movement.hpp index 3f3a72a85e6..a3e145d6247 100644 --- a/src/lua/creature/movement.hpp +++ b/src/lua/creature/movement.hpp @@ -214,27 +214,24 @@ class MoveEvent final : public Script, public SharedObject { void setSlot(uint32_t s) { slot = s; } - uint32_t getRequiredLevel() { + uint32_t getRequiredLevel() const { return reqLevel; } void setRequiredLevel(uint32_t level) { reqLevel = level; } - uint32_t getRequiredMagLevel() { + uint32_t getRequiredMagLevel() const { return reqMagLevel; } void setRequiredMagLevel(uint32_t level) { reqMagLevel = level; } - bool needPremium() { + bool needPremium() const { return premium; } void setNeedPremium(bool b) { premium = b; } - uint32_t getWieldInfo() { - return wieldInfo; - } void setWieldInfo(WieldInfo_t info) { wieldInfo |= info; } diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index fe5f218e373..c0c64e75e06 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -398,7 +398,7 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { pugi::xml_attribute attr; if ((attr = eventNode.attribute("radius"))) { - int32_t radius = pugi::cast(attr.value()); + auto radius = pugi::cast(attr.value()); Position centerPos; if ((attr = eventNode.attribute("centerx"))) { diff --git a/src/lua/functions/core/game/bank_functions.cpp b/src/lua/functions/core/game/bank_functions.cpp index f6732b8bf70..401ba9dab7c 100644 --- a/src/lua/functions/core/game/bank_functions.cpp +++ b/src/lua/functions/core/game/bank_functions.cpp @@ -154,7 +154,7 @@ std::shared_ptr BankFunctions::getBank(lua_State* L, int32_t arg, bool isG } return std::make_shared(guild); } - std::shared_ptr player = getPlayer(L, arg, true); + const auto player = getPlayer(L, arg, true); if (!player) { return nullptr; } diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index bfb1d3b6cb9..941ead55c3a 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -91,10 +91,10 @@ int GameFunctions::luaGameGetSpectators(lua_State* L) { const Position &position = getPosition(L, 1); bool multifloor = getBoolean(L, 2, false); bool onlyPlayers = getBoolean(L, 3, false); - int32_t minRangeX = getNumber(L, 4, 0); - int32_t maxRangeX = getNumber(L, 5, 0); - int32_t minRangeY = getNumber(L, 6, 0); - int32_t maxRangeY = getNumber(L, 7, 0); + auto minRangeX = getNumber(L, 4, 0); + auto maxRangeX = getNumber(L, 5, 0); + auto minRangeY = getNumber(L, 6, 0); + auto maxRangeY = getNumber(L, 7, 0); Spectators spectators; @@ -309,7 +309,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { } } - int32_t count = getNumber(L, 2, 1); + auto count = getNumber(L, 2, 1); int32_t itemCount = 1; int32_t subType = 1; @@ -344,7 +344,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { subType -= stackCount; } - std::shared_ptr item = Item::CreateItem(itemId, stackCount); + const auto item = Item::CreateItem(itemId, stackCount); if (!item) { if (!hasTable) { lua_pushnil(L); @@ -652,7 +652,7 @@ int GameFunctions::luaGameGetNormalizedPlayerName(lua_State* L) { // Game.getNormalizedPlayerName(name[, isNewName = false]) auto name = getString(L, 1); auto isNewName = getBoolean(L, 2, false); - std::shared_ptr player = g_game().getPlayerByName(name, true, isNewName); + const auto player = g_game().getPlayerByName(name, true, isNewName); if (player) { pushString(L, player->getName()); } else { @@ -743,7 +743,7 @@ int GameFunctions::luaGameGetDummies(lua_State* L) { int GameFunctions::luaGameMakeFiendishMonster(lua_State* L) { // Game.makeFiendishMonster(monsterId[default= 0]) - uint32_t monsterId = getNumber(L, 1, 0); + auto monsterId = getNumber(L, 1, 0); auto createForgeableMonsters = getBoolean(L, 2, false); lua_pushnumber(L, g_game().makeFiendishMonster(monsterId, createForgeableMonsters)); return 1; diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index f5bb38cee66..492526022d6 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -25,7 +25,7 @@ class Creature; int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { // doPlayerAddItem(cid, itemid, count/subtype, canDropOnMap) // doPlayerAddItem(cid, itemid, count, canDropOnMap, subtype) - std::shared_ptr player = getPlayer(L, 1); + const auto player = getPlayer(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -33,9 +33,9 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { } uint16_t itemId = getNumber(L, 2); - int32_t count = getNumber(L, 3, 1); + auto count = getNumber(L, 3, 1); bool canDropOnMap = getBoolean(L, 4, true); - uint16_t subType = getNumber(L, 5, 1); + auto subType = getNumber(L, 5, 1); const ItemType &it = Item::items[itemId]; int32_t itemCount; @@ -133,7 +133,7 @@ int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { int32_t itemCount = 1; int32_t subType = 1; - uint32_t count = getNumber(L, 3, 1); + auto count = getNumber(L, 3, 1); if (it.hasSubType()) { if (it.stackable) { diff --git a/src/lua/functions/core/libs/db_functions.cpp b/src/lua/functions/core/libs/db_functions.cpp index d5f5a62e0f8..2ca1bface33 100644 --- a/src/lua/functions/core/libs/db_functions.cpp +++ b/src/lua/functions/core/libs/db_functions.cpp @@ -24,7 +24,7 @@ int DBFunctions::luaDatabaseAsyncExecute(lua_State* L) { if (lua_gettop(L) > 1) { int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX); auto scriptId = getScriptEnv()->getScriptId(); - callback = [ref, scriptId](DBResult_ptr, bool success) { + callback = [ref, scriptId](const DBResult_ptr &, bool success) { lua_State* luaState = g_luaEnvironment().getLuaState(); if (!luaState) { return; @@ -62,7 +62,7 @@ int DBFunctions::luaDatabaseAsyncStoreQuery(lua_State* L) { if (lua_gettop(L) > 1) { int32_t ref = luaL_ref(L, LUA_REGISTRYINDEX); auto scriptId = getScriptEnv()->getScriptId(); - callback = [ref, scriptId](DBResult_ptr result, bool) { + callback = [ref, scriptId](const DBResult_ptr &result, bool) { lua_State* luaState = g_luaEnvironment().getLuaState(); if (!luaState) { return; diff --git a/src/lua/functions/core/libs/kv_functions.cpp b/src/lua/functions/core/libs/kv_functions.cpp index 5ed9c9cfe5d..f145c2c0b5d 100644 --- a/src/lua/functions/core/libs/kv_functions.cpp +++ b/src/lua/functions/core/libs/kv_functions.cpp @@ -96,7 +96,7 @@ int KVFunctions::luaKVRemove(lua_State* L) { int KVFunctions::luaKVKeys(lua_State* L) { // KV.keys([prefix = ""]) | scopedKV:keys([prefix = ""]) std::unordered_set keys; - std::string prefix = ""; + std::string prefix; if (isString(L, -1)) { prefix = getString(L, -1); diff --git a/src/lua/functions/core/network/network_message_functions.cpp b/src/lua/functions/core/network/network_message_functions.cpp index a1b66264fac..faaf752c267 100644 --- a/src/lua/functions/core/network/network_message_functions.cpp +++ b/src/lua/functions/core/network/network_message_functions.cpp @@ -232,14 +232,14 @@ int NetworkMessageFunctions::luaNetworkMessageAddDouble(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddItem(lua_State* L) { // networkMessage:addItem(item, player) - std::shared_ptr item = getUserdataShared(L, 2); + const auto item = getUserdataShared(L, 2); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); lua_pushnil(L); return 1; } - std::shared_ptr player = getUserdataShared(L, 3); + const auto player = getUserdataShared(L, 3); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -289,7 +289,7 @@ int NetworkMessageFunctions::luaNetworkMessageSendToPlayer(lua_State* L) { return 1; } - std::shared_ptr player = getPlayer(L, 2); + const auto player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; diff --git a/src/lua/functions/core/network/webhook_functions.cpp b/src/lua/functions/core/network/webhook_functions.cpp index 37372f8b23a..6b1bf5eea05 100644 --- a/src/lua/functions/core/network/webhook_functions.cpp +++ b/src/lua/functions/core/network/webhook_functions.cpp @@ -17,7 +17,7 @@ int WebhookFunctions::luaWebhookSendMessage(lua_State* L) { // Webhook.sendMessage(message, url = "WEBHOOK_DISCORD_URL") std::string title = getString(L, 1); std::string message = getString(L, 2); - uint32_t color = getNumber(L, 3, 0); + auto color = getNumber(L, 3, 0); std::string url = getString(L, -1); if (url == title) { g_webhook().sendMessage(title); diff --git a/src/lua/functions/creatures/combat/spell_functions.cpp b/src/lua/functions/creatures/combat/spell_functions.cpp index 5703c8f2086..a7ffac63a46 100644 --- a/src/lua/functions/creatures/combat/spell_functions.cpp +++ b/src/lua/functions/creatures/combat/spell_functions.cpp @@ -610,7 +610,7 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { } else { int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc for (int i = 0; i < parameters; ++i) { - if (getString(L, 2 + i).find(";") != std::string::npos) { + if (getString(L, 2 + i).find(';') != std::string::npos) { std::vector vocList = explodeString(getString(L, 2 + i), ";"); int32_t vocationId = g_vocations().getVocationId(vocList[0]); if (!vocList.empty()) { diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index 81a4a0b5304..ddca806acb2 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -485,7 +485,7 @@ int CreatureFunctions::luaCreatureSetHealth(lua_State* L) { creature->health = std::min(getNumber(L, 2), creature->healthMax); g_game().addCreatureHealth(creature); - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendStats(); } @@ -537,7 +537,7 @@ int CreatureFunctions::luaCreatureSetMaxHealth(lua_State* L) { creature->health = std::min(creature->health, creature->healthMax); g_game().addCreatureHealth(creature); - std::shared_ptr player = creature->getPlayer(); + const auto player = creature->getPlayer(); if (player) { player->sendStats(); } @@ -666,8 +666,8 @@ int CreatureFunctions::luaCreatureGetCondition(lua_State* L) { } ConditionType_t conditionType = getNumber(L, 2); - ConditionId_t conditionId = getNumber(L, 3, CONDITIONID_COMBAT); - uint32_t subId = getNumber(L, 4, 0); + auto conditionId = getNumber(L, 3, CONDITIONID_COMBAT); + auto subId = getNumber(L, 4, 0); const std::shared_ptr condition = creature->getCondition(conditionType, conditionId, subId); if (condition) { @@ -700,8 +700,8 @@ int CreatureFunctions::luaCreatureRemoveCondition(lua_State* L) { } ConditionType_t conditionType = getNumber(L, 2); - ConditionId_t conditionId = getNumber(L, 3, CONDITIONID_COMBAT); - uint32_t subId = getNumber(L, 4, 0); + auto conditionId = getNumber(L, 3, CONDITIONID_COMBAT); + auto subId = getNumber(L, 4, 0); const std::shared_ptr condition = creature->getCondition(conditionType, conditionId, subId); if (condition) { bool force = getBoolean(L, 5, false); @@ -726,7 +726,7 @@ int CreatureFunctions::luaCreatureHasCondition(lua_State* L) { } ConditionType_t conditionType = getNumber(L, 2); - uint32_t subId = getNumber(L, 3, 0); + auto subId = getNumber(L, 3, 0); pushBoolean(L, creature->hasCondition(conditionType, subId)); return 1; } @@ -764,7 +764,7 @@ int CreatureFunctions::luaCreatureRemove(lua_State* L) { } bool forced = getBoolean(L, 2, true); - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (forced) { player->removePlayer(true); } else { @@ -837,7 +837,7 @@ int CreatureFunctions::luaCreatureSay(lua_State* L) { bool ghost = getBoolean(L, 4, false); - SpeakClasses type = getNumber(L, 3, TALKTYPE_MONSTER_SAY); + auto type = getNumber(L, 3, TALKTYPE_MONSTER_SAY); const std::string &text = getString(L, 2); std::shared_ptr creature = getUserdataShared(L, 1); if (!creature) { @@ -1002,7 +1002,7 @@ int CreatureFunctions::luaCreatureGetZones(lua_State* L) { const auto zones = creature->getZones(); lua_createtable(L, static_cast(zones.size()), 0); int index = 0; - for (auto zone : zones) { + for (const auto &zone : zones) { index++; pushUserdata(L, zone); setMetatable(L, -1, "Zone"); diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 28e1fac9574..f67dd2d88a8 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -57,7 +57,7 @@ int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { return 1; } - uint8_t count = getNumber(L, 3, 0); + auto count = getNumber(L, 3, 0); if (count == 0) { lua_pushnil(L); return 1; @@ -913,7 +913,7 @@ int PlayerFunctions::luaPlayerSendSpellCooldown(lua_State* L) { return 1; } uint8_t spellId = getNumber(L, 2, 1); - uint32_t time = getNumber(L, 3, 0); + auto time = getNumber(L, 3, 0); player->sendSpellCooldown(spellId, time); pushBoolean(L, true); @@ -928,8 +928,8 @@ int PlayerFunctions::luaPlayerSendSpellGroupCooldown(lua_State* L) { lua_pushnil(L); return 1; } - SpellGroup_t groupId = getNumber(L, 2, SPELLGROUP_ATTACK); - uint32_t time = getNumber(L, 3, 0); + auto groupId = getNumber(L, 2, SPELLGROUP_ATTACK); + auto time = getNumber(L, 3, 0); player->sendSpellGroupCooldown(groupId, time); pushBoolean(L, true); @@ -1300,7 +1300,7 @@ int PlayerFunctions::luaPlayerGetItemCount(lua_State* L) { } } - int32_t subType = getNumber(L, 3, -1); + auto subType = getNumber(L, 3, -1); lua_pushnumber(L, player->getItemTypeCount(itemId, subType)); return 1; } @@ -1353,7 +1353,7 @@ int PlayerFunctions::luaPlayerGetItemById(lua_State* L) { } } bool deepSearch = getBoolean(L, 3); - int32_t subType = getNumber(L, 4, -1); + auto subType = getNumber(L, 4, -1); const auto &item = g_game().findItemOfType(player, itemId, deepSearch, subType); if (item) { @@ -1809,8 +1809,8 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { } } - int32_t count = getNumber(L, 3, 1); - int32_t subType = getNumber(L, 5, 1); + auto count = getNumber(L, 3, 1); + auto subType = getNumber(L, 5, 1); const ItemType &it = Item::items[itemId]; @@ -1837,7 +1837,7 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { } bool canDropOnMap = getBoolean(L, 4, true); - Slots_t slot = getNumber(L, 6, CONST_SLOT_WHEREEVER); + auto slot = getNumber(L, 6, CONST_SLOT_WHEREEVER); auto tier = getNumber(L, 7, 0); for (int32_t i = 1; i <= itemCount; ++i) { int32_t stackCount = subType; @@ -1904,11 +1904,11 @@ int PlayerFunctions::luaPlayerAddItemEx(lua_State* L) { bool canDropOnMap = getBoolean(L, 3, false); ReturnValue returnValue; if (canDropOnMap) { - Slots_t slot = getNumber(L, 4, CONST_SLOT_WHEREEVER); + auto slot = getNumber(L, 4, CONST_SLOT_WHEREEVER); returnValue = g_game().internalPlayerAddItem(player, item, true, slot); } else { - int32_t index = getNumber(L, 4, INDEX_WHEREEVER); - uint32_t flags = getNumber(L, 5, 0); + auto index = getNumber(L, 4, INDEX_WHEREEVER); + auto flags = getNumber(L, 5, 0); returnValue = g_game().internalAddItem(player, item, index, flags); } @@ -1985,7 +1985,7 @@ int PlayerFunctions::luaPlayerRemoveItem(lua_State* L) { } uint32_t count = getNumber(L, 3); - int32_t subType = getNumber(L, 4, -1); + auto subType = getNumber(L, 4, -1); bool ignoreEquipped = getBoolean(L, 5, false); pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped)); return 1; @@ -2058,7 +2058,7 @@ int PlayerFunctions::luaPlayerRemoveMoney(lua_State* L) { const auto &player = getUserdataShared(L, 1); if (player) { uint64_t money = getNumber(L, 2); - int32_t flags = getNumber(L, 3, 0); + auto flags = getNumber(L, 3, 0); bool useBank = getBoolean(L, 4, true); pushBoolean(L, g_game().removeMoney(player, money, flags, useBank)); } else { @@ -2075,7 +2075,7 @@ int PlayerFunctions::luaPlayerShowTextDialog(lua_State* L) { return 1; } - int32_t length = getNumber(L, 5, -1); + auto length = getNumber(L, 5, -1); bool canWrite = getBoolean(L, 4, false); std::string text; @@ -2189,7 +2189,7 @@ int PlayerFunctions::luaPlayerSendPrivateMessage(lua_State* L) { const auto &speaker = getUserdataShared(L, 2); const std::string &text = getString(L, 3); - SpeakClasses type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); + auto type = getNumber(L, 4, TALKTYPE_PRIVATE_FROM); player->sendPrivateMessage(speaker, type, text); pushBoolean(L, true); return 1; @@ -2324,7 +2324,7 @@ int PlayerFunctions::luaPlayerHasOutfit(lua_State* L) { const auto &player = getUserdataShared(L, 1); if (player) { uint16_t lookType = getNumber(L, 2); - uint8_t addon = getNumber(L, 3, 0); + auto addon = getNumber(L, 3, 0); pushBoolean(L, player->canWear(lookType, addon)); } else { lua_pushnil(L); diff --git a/src/lua/functions/events/global_event_functions.cpp b/src/lua/functions/events/global_event_functions.cpp index d23ad4bf2c9..16227aeb08b 100644 --- a/src/lua/functions/events/global_event_functions.cpp +++ b/src/lua/functions/events/global_event_functions.cpp @@ -136,7 +136,7 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { timeinfo->tm_min = min; timeinfo->tm_sec = sec; - time_t difference = static_cast(difftime(mktime(timeinfo), current_time)); + auto difference = static_cast(difftime(mktime(timeinfo), current_time)); // If the difference is negative, add 86400 seconds (1 day) to it if (difference < 0) { difference += 86400; diff --git a/src/lua/functions/items/container_functions.cpp b/src/lua/functions/items/container_functions.cpp index fd0c2c38a8b..ca17ec48180 100644 --- a/src/lua/functions/items/container_functions.cpp +++ b/src/lua/functions/items/container_functions.cpp @@ -144,7 +144,7 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { } } - uint32_t count = getNumber(L, 3, 1); + auto count = getNumber(L, 3, 1); const ItemType &it = Item::items[itemId]; if (it.stackable) { count = std::min(count, it.stackSize); @@ -157,8 +157,8 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { return 1; } - int32_t index = getNumber(L, 4, INDEX_WHEREEVER); - uint32_t flags = getNumber(L, 5, 0); + auto index = getNumber(L, 4, INDEX_WHEREEVER); + auto flags = getNumber(L, 5, 0); ReturnValue ret = g_game().internalAddItem(container, item, index, flags); if (ret == RETURNVALUE_NOERROR) { @@ -191,8 +191,8 @@ int ContainerFunctions::luaContainerAddItemEx(lua_State* L) { return 1; } - int32_t index = getNumber(L, 3, INDEX_WHEREEVER); - uint32_t flags = getNumber(L, 4, 0); + auto index = getNumber(L, 3, INDEX_WHEREEVER); + auto flags = getNumber(L, 4, 0); ReturnValue ret = g_game().internalAddItem(container, item, index, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); @@ -231,7 +231,7 @@ int ContainerFunctions::luaContainerGetItemCountById(lua_State* L) { } } - int32_t subType = getNumber(L, 3, -1); + auto subType = getNumber(L, 3, -1); lua_pushnumber(L, container->getItemTypeCount(itemId, subType)); return 1; } diff --git a/src/lua/functions/items/imbuement_functions.cpp b/src/lua/functions/items/imbuement_functions.cpp index f24a3f564d7..f0db5fcd411 100644 --- a/src/lua/functions/items/imbuement_functions.cpp +++ b/src/lua/functions/items/imbuement_functions.cpp @@ -29,7 +29,7 @@ int ImbuementFunctions::luaCreateImbuement(lua_State* L) { int ImbuementFunctions::luaImbuementGetName(lua_State* L) { // imbuement:getName() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (imbuement) { pushString(L, imbuement->getName()); } else { @@ -40,7 +40,7 @@ int ImbuementFunctions::luaImbuementGetName(lua_State* L) { int ImbuementFunctions::luaImbuementGetId(lua_State* L) { // imbuement:getId() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->getID()); } else { @@ -51,7 +51,7 @@ int ImbuementFunctions::luaImbuementGetId(lua_State* L) { int ImbuementFunctions::luaImbuementGetItems(lua_State* L) { // imbuement:getItems() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -72,7 +72,7 @@ int ImbuementFunctions::luaImbuementGetItems(lua_State* L) { int ImbuementFunctions::luaImbuementGetBase(lua_State* L) { // imbuement:getBase() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -97,7 +97,7 @@ int ImbuementFunctions::luaImbuementGetBase(lua_State* L) { int ImbuementFunctions::luaImbuementGetCategory(lua_State* L) { // imbuement:getCategory() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -118,7 +118,7 @@ int ImbuementFunctions::luaImbuementGetCategory(lua_State* L) { int ImbuementFunctions::luaImbuementIsPremium(lua_State* L) { // imbuement:isPremium() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -130,7 +130,7 @@ int ImbuementFunctions::luaImbuementIsPremium(lua_State* L) { int ImbuementFunctions::luaImbuementGetElementDamage(lua_State* L) { // imbuement:getElementDamage() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->elementDamage); } else { @@ -141,7 +141,7 @@ int ImbuementFunctions::luaImbuementGetElementDamage(lua_State* L) { int ImbuementFunctions::luaImbuementGetCombatType(lua_State* L) { // imbuement:getCombatType() - Imbuement* imbuement = getUserdata(L, 1); + auto* imbuement = getUserdata(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->combatType); } else { diff --git a/src/lua/functions/items/item_classification_functions.cpp b/src/lua/functions/items/item_classification_functions.cpp index aa8cf19d589..34848552d68 100644 --- a/src/lua/functions/items/item_classification_functions.cpp +++ b/src/lua/functions/items/item_classification_functions.cpp @@ -29,7 +29,7 @@ int ItemClassificationFunctions::luaItemClassificationCreate(lua_State* L) { int ItemClassificationFunctions::luaItemClassificationAddTier(lua_State* L) { // itemClassification:addTier(id, core, regularPrice, convergenceFusionPrice, convergenceTransferPrice) - ItemClassification* itemClassification = getUserdata(L, 1); + auto* itemClassification = getUserdata(L, 1); if (itemClassification) { itemClassification->addTier( getNumber(L, 2), diff --git a/src/lua/functions/items/item_functions.cpp b/src/lua/functions/items/item_functions.cpp index 565fa496bd7..7a4bed600de 100644 --- a/src/lua/functions/items/item_functions.cpp +++ b/src/lua/functions/items/item_functions.cpp @@ -159,7 +159,7 @@ int ItemFunctions::luaItemRemove(lua_State* L) { // item:remove([count = -1]) const auto &item = getUserdataShared(L, 1); if (item) { - int32_t count = getNumber(L, 2, -1); + auto count = getNumber(L, 2, -1); pushBoolean(L, g_game().internalRemoveItem(item, count) == RETURNVALUE_NOERROR); } else { lua_pushnil(L); @@ -626,7 +626,7 @@ int ItemFunctions::luaItemMoveTo(lua_State* L) { return 1; } - uint32_t flags = getNumber(L, 3, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVABLE); + auto flags = getNumber(L, 3, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVABLE); if (item->getParent() == VirtualCylinder::virtualCylinder) { pushBoolean(L, g_game().internalAddItem(toCylinder, item, INDEX_WHEREEVER, flags) == RETURNVALUE_NOERROR); @@ -666,7 +666,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { } } - int32_t subType = getNumber(L, 3, -1); + auto subType = getNumber(L, 3, -1); if (item->getID() == itemId && (subType == -1 || subType == item->getSubType())) { pushBoolean(L, true); return 1; @@ -725,7 +725,7 @@ int ItemFunctions::luaItemMoveToSlot(lua_State* L) { return 1; } - Slots_t slot = getNumber(L, 3, CONST_SLOT_WHEREEVER); + auto slot = getNumber(L, 3, CONST_SLOT_WHEREEVER); std::shared_ptr moveItem = nullptr; ReturnValue ret = g_game().internalMoveItem(item->getParent(), player, slot, item, item->getItemCount(), nullptr); diff --git a/src/lua/functions/items/item_type_functions.cpp b/src/lua/functions/items/item_type_functions.cpp index b528795a050..cdb80012cc9 100644 --- a/src/lua/functions/items/item_type_functions.cpp +++ b/src/lua/functions/items/item_type_functions.cpp @@ -30,7 +30,7 @@ int ItemTypeFunctions::luaItemTypeCreate(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsCorpse(lua_State* L) { // itemType:isCorpse() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isCorpse); } else { @@ -41,7 +41,7 @@ int ItemTypeFunctions::luaItemTypeIsCorpse(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsDoor(lua_State* L) { // itemType:isDoor() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isDoor()); } else { @@ -52,7 +52,7 @@ int ItemTypeFunctions::luaItemTypeIsDoor(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsContainer(lua_State* L) { // itemType:isContainer() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isContainer()); } else { @@ -63,7 +63,7 @@ int ItemTypeFunctions::luaItemTypeIsContainer(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsFluidContainer(lua_State* L) { // itemType:isFluidContainer() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isFluidContainer()); } else { @@ -74,7 +74,7 @@ int ItemTypeFunctions::luaItemTypeIsFluidContainer(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsMovable(lua_State* L) { // itemType:isMovable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->movable); } else { @@ -85,7 +85,7 @@ int ItemTypeFunctions::luaItemTypeIsMovable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsRune(lua_State* L) { // itemType:isRune() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isRune()); } else { @@ -96,7 +96,7 @@ int ItemTypeFunctions::luaItemTypeIsRune(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsStackable(lua_State* L) { // itemType:isStackable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->stackable); } else { @@ -107,7 +107,7 @@ int ItemTypeFunctions::luaItemTypeIsStackable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsStowable(lua_State* L) { // itemType:isStowable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->stackable && itemType->wareId > 0); } else { @@ -118,7 +118,7 @@ int ItemTypeFunctions::luaItemTypeIsStowable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsReadable(lua_State* L) { // itemType:isReadable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->canReadText); } else { @@ -129,7 +129,7 @@ int ItemTypeFunctions::luaItemTypeIsReadable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsWritable(lua_State* L) { // itemType:isWritable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->canWriteText); } else { @@ -140,7 +140,7 @@ int ItemTypeFunctions::luaItemTypeIsWritable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsBlocking(lua_State* L) { // itemType:isBlocking() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->blockProjectile || itemType->blockSolid); } else { @@ -151,7 +151,7 @@ int ItemTypeFunctions::luaItemTypeIsBlocking(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsGroundTile(lua_State* L) { // itemType:isGroundTile() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isGroundTile()); } else { @@ -162,7 +162,7 @@ int ItemTypeFunctions::luaItemTypeIsGroundTile(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsMagicField(lua_State* L) { // itemType:isMagicField() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isMagicField()); } else { @@ -173,7 +173,7 @@ int ItemTypeFunctions::luaItemTypeIsMagicField(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsMultiUse(lua_State* L) { // itemType:isMultiUse() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isMultiUse()); } else { @@ -184,7 +184,7 @@ int ItemTypeFunctions::luaItemTypeIsMultiUse(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsPickupable(lua_State* L) { // itemType:isPickupable() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isPickupable()); } else { @@ -195,7 +195,7 @@ int ItemTypeFunctions::luaItemTypeIsPickupable(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsKey(lua_State* L) { // itemType:isKey() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isKey()); } else { @@ -206,7 +206,7 @@ int ItemTypeFunctions::luaItemTypeIsKey(lua_State* L) { int ItemTypeFunctions::luaItemTypeIsQuiver(lua_State* L) { // itemType:isQuiver() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->isQuiver()); } else { @@ -217,7 +217,7 @@ int ItemTypeFunctions::luaItemTypeIsQuiver(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetType(lua_State* L) { // itemType:getType() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->type); } else { @@ -228,7 +228,7 @@ int ItemTypeFunctions::luaItemTypeGetType(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetId(lua_State* L) { // itemType:getId() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->id); } else { @@ -239,7 +239,7 @@ int ItemTypeFunctions::luaItemTypeGetId(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetName(lua_State* L) { // itemType:getName() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->name); } else { @@ -250,7 +250,7 @@ int ItemTypeFunctions::luaItemTypeGetName(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetPluralName(lua_State* L) { // itemType:getPluralName() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->getPluralName()); } else { @@ -261,7 +261,7 @@ int ItemTypeFunctions::luaItemTypeGetPluralName(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetArticle(lua_State* L) { // itemType:getArticle() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->article); } else { @@ -285,7 +285,7 @@ int ItemTypeFunctions::luaItemTypeGetDescription(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetSlotPosition(lua_State* L) { // itemType:getSlotPosition() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->slotPosition); } else { @@ -296,7 +296,7 @@ int ItemTypeFunctions::luaItemTypeGetSlotPosition(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetCharges(lua_State* L) { // itemType:getCharges() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->charges); } else { @@ -307,7 +307,7 @@ int ItemTypeFunctions::luaItemTypeGetCharges(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetFluidSource(lua_State* L) { // itemType:getFluidSource() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->fluidSource); } else { @@ -318,7 +318,7 @@ int ItemTypeFunctions::luaItemTypeGetFluidSource(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetCapacity(lua_State* L) { // itemType:getCapacity() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->maxItems); } else { @@ -329,9 +329,9 @@ int ItemTypeFunctions::luaItemTypeGetCapacity(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetWeight(lua_State* L) { // itemType:getWeight([count = 1]) - uint16_t count = getNumber(L, 2, 1); + auto count = getNumber(L, 2, 1); - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; @@ -344,20 +344,20 @@ int ItemTypeFunctions::luaItemTypeGetWeight(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetStackSize(lua_State* L) { // itemType:getStackSize() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; } - uint64_t stackSize = static_cast(itemType->stackSize); + auto stackSize = static_cast(itemType->stackSize); lua_pushnumber(L, stackSize); return 1; } int ItemTypeFunctions::luaItemTypeGetHitChance(lua_State* L) { // itemType:getHitChance() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->hitChance); } else { @@ -368,7 +368,7 @@ int ItemTypeFunctions::luaItemTypeGetHitChance(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetShootRange(lua_State* L) { // itemType:getShootRange() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->shootRange); } else { @@ -379,7 +379,7 @@ int ItemTypeFunctions::luaItemTypeGetShootRange(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetAttack(lua_State* L) { // itemType:getAttack() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->attack); } else { @@ -390,7 +390,7 @@ int ItemTypeFunctions::luaItemTypeGetAttack(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetDefense(lua_State* L) { // itemType:getDefense() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->defense); } else { @@ -401,7 +401,7 @@ int ItemTypeFunctions::luaItemTypeGetDefense(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetExtraDefense(lua_State* L) { // itemType:getExtraDefense() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->extraDefense); } else { @@ -412,7 +412,7 @@ int ItemTypeFunctions::luaItemTypeGetExtraDefense(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetImbuementSlot(lua_State* L) { // itemType:getImbuementSlot() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->imbuementSlot); } else { @@ -423,7 +423,7 @@ int ItemTypeFunctions::luaItemTypeGetImbuementSlot(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetArmor(lua_State* L) { // itemType:getArmor() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->armor); } else { @@ -434,7 +434,7 @@ int ItemTypeFunctions::luaItemTypeGetArmor(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetWeaponType(lua_State* L) { // itemType:getWeaponType() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->weaponType); } else { @@ -445,7 +445,7 @@ int ItemTypeFunctions::luaItemTypeGetWeaponType(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetAmmoType(lua_State* L) { // itemType:getAmmoType() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->ammoType); } else { @@ -456,7 +456,7 @@ int ItemTypeFunctions::luaItemTypeGetAmmoType(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetElementType(lua_State* L) { // itemType:getElementType() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; @@ -473,7 +473,7 @@ int ItemTypeFunctions::luaItemTypeGetElementType(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetElementDamage(lua_State* L) { // itemType:getElementDamage() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; @@ -490,7 +490,7 @@ int ItemTypeFunctions::luaItemTypeGetElementDamage(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetTransformEquipId(lua_State* L) { // itemType:getTransformEquipId() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->transformEquipTo); } else { @@ -501,7 +501,7 @@ int ItemTypeFunctions::luaItemTypeGetTransformEquipId(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetTransformDeEquipId(lua_State* L) { // itemType:getTransformDeEquipId() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->transformDeEquipTo); } else { @@ -512,7 +512,7 @@ int ItemTypeFunctions::luaItemTypeGetTransformDeEquipId(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetDestroyId(lua_State* L) { // itemType:getDestroyId() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->destroyTo); } else { @@ -523,7 +523,7 @@ int ItemTypeFunctions::luaItemTypeGetDestroyId(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetDecayId(lua_State* L) { // itemType:getDecayId() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->decayTo); } else { @@ -534,7 +534,7 @@ int ItemTypeFunctions::luaItemTypeGetDecayId(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetRequiredLevel(lua_State* L) { // itemType:getRequiredLevel() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->minReqLevel); } else { @@ -545,7 +545,7 @@ int ItemTypeFunctions::luaItemTypeGetRequiredLevel(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetSpeed(lua_State* L) { // itemType:getSpeed() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (!itemType) { lua_pushnil(L); return 1; @@ -562,7 +562,7 @@ int ItemTypeFunctions::luaItemTypeGetSpeed(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetBaseSpeed(lua_State* L) { // itemType:getBaseSpeed() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->speed); } else { @@ -573,7 +573,7 @@ int ItemTypeFunctions::luaItemTypeGetBaseSpeed(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetDecayTime(lua_State* L) { // itemType:getDecayTime() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->decayTime); } else { @@ -584,7 +584,7 @@ int ItemTypeFunctions::luaItemTypeGetDecayTime(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetShowDuration(lua_State* L) { // itemType:getShowDuration() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushboolean(L, itemType->showDuration); } else { @@ -594,7 +594,7 @@ int ItemTypeFunctions::luaItemTypeGetShowDuration(lua_State* L) { } int ItemTypeFunctions::luaItemTypeGetWrapableTo(lua_State* L) { // itemType:getWrapableTo() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { lua_pushnumber(L, itemType->wrapableTo); } else { @@ -605,7 +605,7 @@ int ItemTypeFunctions::luaItemTypeGetWrapableTo(lua_State* L) { int ItemTypeFunctions::luaItemTypeHasSubType(lua_State* L) { // itemType:hasSubType() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushBoolean(L, itemType->hasSubType()); } else { @@ -616,7 +616,7 @@ int ItemTypeFunctions::luaItemTypeHasSubType(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetVocationString(lua_State* L) { // itemType:getVocationString() - const ItemType* itemType = getUserdata(L, 1); + const auto* itemType = getUserdata(L, 1); if (itemType) { pushString(L, itemType->vocationString); } else { diff --git a/src/lua/functions/map/house_functions.cpp b/src/lua/functions/map/house_functions.cpp index af2248b255e..99e2c7eb975 100644 --- a/src/lua/functions/map/house_functions.cpp +++ b/src/lua/functions/map/house_functions.cpp @@ -137,7 +137,7 @@ int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { return 1; } - uint32_t guid = getNumber(L, 2, 0); + auto guid = getNumber(L, 2, 0); house->setNewOwnerGuid(guid, false); pushBoolean(L, true); } else { diff --git a/src/lua/functions/map/position_functions.cpp b/src/lua/functions/map/position_functions.cpp index 34f110786a0..ae095a652cd 100644 --- a/src/lua/functions/map/position_functions.cpp +++ b/src/lua/functions/map/position_functions.cpp @@ -27,9 +27,9 @@ int PositionFunctions::luaPositionCreate(lua_State* L) { const Position &position = getPosition(L, 2, stackpos); pushPosition(L, position, stackpos); } else { - uint16_t x = getNumber(L, 2, 0); - uint16_t y = getNumber(L, 3, 0); - uint8_t z = getNumber(L, 4, 0); + auto x = getNumber(L, 2, 0); + auto y = getNumber(L, 3, 0); + auto z = getNumber(L, 4, 0); stackpos = getNumber(L, 5, 0); pushPosition(L, Position(x, y, z), stackpos); diff --git a/src/lua/functions/map/tile_functions.cpp b/src/lua/functions/map/tile_functions.cpp index cfd3e5149bf..b9776ea7884 100644 --- a/src/lua/functions/map/tile_functions.cpp +++ b/src/lua/functions/map/tile_functions.cpp @@ -194,7 +194,7 @@ int TileFunctions::luaTileGetItemById(lua_State* L) { return 1; } } - int32_t subType = getNumber(L, 3, -1); + auto subType = getNumber(L, 3, -1); const auto &item = g_game().findItemOfType(tile, itemId, false, subType); if (item) { @@ -299,7 +299,7 @@ int TileFunctions::luaTileGetItemCountById(lua_State* L) { return 1; } - int32_t subType = getNumber(L, 3, -1); + auto subType = getNumber(L, 3, -1); uint16_t itemId; if (isNumber(L, 2)) { @@ -562,7 +562,7 @@ int TileFunctions::luaTileQueryAdd(lua_State* L) { const auto &thing = getThing(L, 2); if (thing) { - uint32_t flags = getNumber(L, 3, 0); + auto flags = getNumber(L, 3, 0); lua_pushnumber(L, tile->queryAdd(0, thing, 1, flags)); } else { lua_pushnil(L); @@ -589,7 +589,7 @@ int TileFunctions::luaTileAddItem(lua_State* L) { } } - uint32_t subType = getNumber(L, 3, 1); + auto subType = getNumber(L, 3, 1); const auto &item = Item::CreateItem(itemId, std::min(subType, Item::items[itemId].stackSize)); if (!item) { @@ -597,7 +597,7 @@ int TileFunctions::luaTileAddItem(lua_State* L) { return 1; } - uint32_t flags = getNumber(L, 4, 0); + auto flags = getNumber(L, 4, 0); ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { @@ -630,7 +630,7 @@ int TileFunctions::luaTileAddItemEx(lua_State* L) { return 1; } - uint32_t flags = getNumber(L, 3, 0); + auto flags = getNumber(L, 3, 0); ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); diff --git a/src/lua/global/baseevents.cpp b/src/lua/global/baseevents.cpp index d1bcaf4f191..5bc8578062e 100644 --- a/src/lua/global/baseevents.cpp +++ b/src/lua/global/baseevents.cpp @@ -152,7 +152,7 @@ bool CallBack::loadCallBack(LuaScriptInterface* interface, const std::string &na scriptInterface = interface; - int32_t id = scriptInterface->getEvent(name.c_str()); + int32_t id = scriptInterface->getEvent(name); if (id == -1) { g_logger().warn("[{}] - Event {} not found", __FUNCTION__, name); return false; diff --git a/src/lua/global/baseevents.hpp b/src/lua/global/baseevents.hpp index 9fe5c79b2ea..e053eb13c94 100644 --- a/src/lua/global/baseevents.hpp +++ b/src/lua/global/baseevents.hpp @@ -84,7 +84,7 @@ class Event { * * @return int32_t */ - int32_t getScriptId() { + int32_t getScriptId() const { return scriptId; } diff --git a/src/lua/modules/modules.hpp b/src/lua/modules/modules.hpp index 62cc736fbfa..a2994cf6c73 100644 --- a/src/lua/modules/modules.hpp +++ b/src/lua/modules/modules.hpp @@ -75,7 +75,7 @@ class Modules final : public BaseEvents { std::string getScriptBaseName() const override; Event_ptr getEvent(const std::string &nodeName) override; bool registerEvent(const Event_ptr &event, const pugi::xml_node &node) override; - void clear() override final; + void clear() final; using ModulesList = std::map; ModulesList recvbyteList; diff --git a/src/lua/scripts/script_environment.cpp b/src/lua/scripts/script_environment.cpp index 80dcbb7ce97..1a46457959e 100644 --- a/src/lua/scripts/script_environment.cpp +++ b/src/lua/scripts/script_environment.cpp @@ -34,7 +34,7 @@ void ScriptEnvironment::resetEnv() { auto pair = tempItems.equal_range(this); auto it = pair.first; while (it != pair.second) { - std::shared_ptr item = it->second; + const auto item = it->second; it = tempItems.erase(it); } } diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index f2cb26114bf..9e7287309a6 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "utils/pugicast.hpp" @@ -20,7 +22,7 @@ House::House(uint32_t houseId) : id(houseId) { } -void House::addTile(std::shared_ptr tile) { +void House::addTile(const std::shared_ptr &tile) { tile->setFlag(TILESTATE_PROTECTIONZONE); houseTiles.push_back(tile); updateDoorDescription(); @@ -65,7 +67,7 @@ void House::clearHouseInfo(bool preventOwnerDeletion) { } } -bool House::tryTransferOwnership(std::shared_ptr player, bool serverStartup) { +bool House::tryTransferOwnership(const std::shared_ptr &player, bool serverStartup) { bool transferSuccess = false; if (player) { transferSuccess = transferToDepot(player); @@ -87,7 +89,7 @@ bool House::tryTransferOwnership(std::shared_ptr player, bool serverStar return transferSuccess; } -void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, std::shared_ptr player /* = nullptr*/) { +void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, const std::shared_ptr &player /* = nullptr*/) { if (updateDatabase && owner != guid) { Database &db = Database::getInstance(); @@ -103,7 +105,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, std::shared isLoaded = true; if (owner != 0) { - tryTransferOwnership(std::move(player), false); + tryTransferOwnership(player, false); } else { std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); time_t currentTime = time(nullptr); @@ -169,7 +171,7 @@ void House::updateDoorDescription() const { } } -AccessHouseLevel_t House::getHouseAccessLevel(std::shared_ptr player) const { +AccessHouseLevel_t House::getHouseAccessLevel(const std::shared_ptr &player) const { if (!player) { return HOUSE_OWNER; } @@ -199,7 +201,7 @@ AccessHouseLevel_t House::getHouseAccessLevel(std::shared_ptr player) co return HOUSE_NOT_INVITED; } -bool House::kickPlayer(std::shared_ptr player, std::shared_ptr target) { +bool House::kickPlayer(const std::shared_ptr &player, const std::shared_ptr &target) { if (!target) { return false; } @@ -240,7 +242,7 @@ void House::setAccessList(uint32_t listId, const std::string &textlist) { for (const std::shared_ptr &tile : houseTiles) { if (CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { - std::shared_ptr player = (*creatures)[i]->getPlayer(); + const auto player = (*creatures)[i]->getPlayer(); if (player && !isInvited(player)) { kickPlayer(nullptr, player); } @@ -254,7 +256,7 @@ bool House::transferToDepot() const { return false; } - std::shared_ptr player = g_game().getPlayerByGUID(owner); + const auto player = g_game().getPlayerByGUID(owner); if (player) { transferToDepot(player); } else { @@ -268,7 +270,7 @@ bool House::transferToDepot() const { return true; } -bool House::transferToDepot(std::shared_ptr player) const { +bool House::transferToDepot(const std::shared_ptr &player) const { if (townId == 0 || !player) { return false; } @@ -280,7 +282,7 @@ bool House::transferToDepot(std::shared_ptr player) const { return true; } -bool House::transferToDepot(std::shared_ptr player, std::shared_ptr tile) const { +bool House::transferToDepot(const std::shared_ptr &player, const std::shared_ptr &tile) const { if (townId == 0 || !player) { return false; } @@ -362,7 +364,7 @@ void House::setNewOwnership() { hasNewOwnerOnStartup = true; } -void House::handleWrapableItem(ItemList &moveItemList, std::shared_ptr item, std::shared_ptr player, std::shared_ptr houseTile) const { +void House::handleWrapableItem(ItemList &moveItemList, const std::shared_ptr &item, const std::shared_ptr &player, const std::shared_ptr &houseTile) const { if (item->isWrapContainer()) { g_logger().debug("[{}] found wrapable item '{}'", __FUNCTION__, item->getName()); handleContainer(moveItemList, item); @@ -377,7 +379,7 @@ void House::handleWrapableItem(ItemList &moveItemList, std::shared_ptr ite moveItemList.push_back(newItem); } -void House::handleContainer(ItemList &moveItemList, std::shared_ptr item) const { +void House::handleContainer(ItemList &moveItemList, const std::shared_ptr &item) const { if (const auto container = item->getContainer()) { for (const std::shared_ptr &containerItem : container->getItemList()) { moveItemList.push_back(containerItem); @@ -402,25 +404,25 @@ bool House::getAccessList(uint32_t listId, std::string &list) const { return door->getAccessList(list); } -void House::addDoor(std::shared_ptr door) { +void House::addDoor(const std::shared_ptr &door) { doorList.push_back(door); door->setHouse(static_self_cast()); updateDoorDescription(); } -void House::removeDoor(std::shared_ptr door) { +void House::removeDoor(const std::shared_ptr &door) { auto it = std::find(doorList.begin(), doorList.end(), door); if (it != doorList.end()) { doorList.erase(it); } } -void House::addBed(std::shared_ptr bed) { +void House::addBed(const std::shared_ptr &bed) { bedsList.push_back(bed); bed->setHouse(static_self_cast()); } -void House::removeBed(std::shared_ptr bed) { +void House::removeBed(const std::shared_ptr &bed) { bed->setHouse(nullptr); bedsList.remove(bed); } @@ -476,7 +478,7 @@ void House::resetTransferItem() { } } -std::shared_ptr HouseTransferItem::createHouseTransferItem(std::shared_ptr house) { +std::shared_ptr HouseTransferItem::createHouseTransferItem(const std::shared_ptr &house) { std::shared_ptr transferItem = std::make_shared(house); transferItem->setID(ITEM_DOCUMENT_RO); transferItem->setSubType(1); @@ -511,7 +513,7 @@ void HouseTransferItem::onTradeEvent(TradeEvents_t event, std::shared_ptr item, std::shared_ptr newOwner) { +bool House::executeTransfer(const std::shared_ptr &item, const std::shared_ptr &newOwner) { if (transferItem != item) { return false; } @@ -585,7 +587,7 @@ void AccessList::parseList(const std::string &list) { } void AccessList::addPlayer(const std::string &name) { - std::shared_ptr player = g_game().getPlayerByName(name); + const auto player = g_game().getPlayerByName(name); if (player) { playerList.insert(player->getGUID()); } else { @@ -631,7 +633,7 @@ void AccessList::addGuildRank(const std::string &name, const std::string &guildN } } -bool AccessList::isInList(std::shared_ptr player) const { +bool AccessList::isInList(const std::shared_ptr &player) const { if (allowEveryone) { return true; } @@ -676,7 +678,7 @@ void Door::setHouse(std::shared_ptr newHouse) { } } -bool Door::canUse(std::shared_ptr player) const { +bool Door::canUse(const std::shared_ptr &player) const { if (!house) { return true; } @@ -736,7 +738,7 @@ bool Houses::loadHousesXML(const std::string &filename) { return false; } - int32_t houseId = pugi::cast(houseIdAttribute.value()); + auto houseId = pugi::cast(houseIdAttribute.value()); std::shared_ptr house = getHouse(houseId); if (!house) { diff --git a/src/map/house/house.hpp b/src/map/house/house.hpp index aa4b746cc0a..f1af2c4e41e 100644 --- a/src/map/house/house.hpp +++ b/src/map/house/house.hpp @@ -25,7 +25,7 @@ class AccessList { void addGuild(const std::string &name); void addGuildRank(const std::string &name, const std::string &rankName); - bool isInList(std::shared_ptr player) const; + bool isInList(const std::shared_ptr &player) const; void getList(std::string &list) const; @@ -63,7 +63,7 @@ class Door final : public Item { return getAttribute(ItemAttribute_t::DOORID); } - bool canUse(std::shared_ptr player) const; + bool canUse(const std::shared_ptr &player) const; void setAccessList(const std::string &textlist); bool getAccessList(std::string &list) const; @@ -83,10 +83,10 @@ using HouseBedItemList = std::list>; class HouseTransferItem final : public Item { public: - static std::shared_ptr createHouseTransferItem(std::shared_ptr house); + static std::shared_ptr createHouseTransferItem(const std::shared_ptr &house); explicit HouseTransferItem(std::shared_ptr newHouse) : - Item(0), house(newHouse) { } + Item(0), house(std::move(newHouse)) { } void onTradeEvent(TradeEvents_t event, std::shared_ptr owner) override; bool canTransform() const override { @@ -101,7 +101,7 @@ class House : public SharedObject { public: explicit House(uint32_t houseId); - void addTile(std::shared_ptr tile); + void addTile(const std::shared_ptr &tile); void updateDoorDescription() const; bool canEditAccessList(uint32_t listId, const std::shared_ptr &player) const; @@ -115,8 +115,8 @@ class House : public SharedObject { return getHouseAccessLevel(player) != HOUSE_NOT_INVITED; } - AccessHouseLevel_t getHouseAccessLevel(std::shared_ptr player) const; - bool kickPlayer(std::shared_ptr player, std::shared_ptr target); + AccessHouseLevel_t getHouseAccessLevel(const std::shared_ptr &player) const; + bool kickPlayer(const std::shared_ptr &player, const std::shared_ptr &target); void setEntryPos(Position pos) { posEntry = pos; @@ -126,7 +126,7 @@ class House : public SharedObject { } void setName(std::string newHouseName) { - this->houseName = newHouseName; + this->houseName = std::move(newHouseName); } const std::string &getName() const { return houseName; @@ -148,8 +148,8 @@ class House : public SharedObject { */ void setNewOwnerGuid(int32_t newOwnerGuid, bool serverStartup); void clearHouseInfo(bool preventOwnerDeletion); - bool tryTransferOwnership(std::shared_ptr player, bool serverStartup); - void setOwner(uint32_t guid, bool updateDatabase = true, std::shared_ptr player = nullptr); + bool tryTransferOwnership(const std::shared_ptr &player, bool serverStartup); + void setOwner(uint32_t guid, bool updateDatabase = true, const std::shared_ptr &player = nullptr); uint32_t getOwner() const { return owner; } @@ -192,14 +192,14 @@ class House : public SharedObject { return id; } - void addDoor(std::shared_ptr door); - void removeDoor(std::shared_ptr door); + void addDoor(const std::shared_ptr &door); + void removeDoor(const std::shared_ptr &door); std::shared_ptr getDoorByNumber(uint32_t doorId) const; std::shared_ptr getDoorByPosition(const Position &pos); std::shared_ptr getTransferItem(); void resetTransferItem(); - bool executeTransfer(std::shared_ptr item, std::shared_ptr player); + bool executeTransfer(const std::shared_ptr &item, const std::shared_ptr &player); const HouseTileList &getTiles() const { return houseTiles; @@ -209,8 +209,8 @@ class House : public SharedObject { return doorList; } - void addBed(std::shared_ptr bed); - void removeBed(std::shared_ptr bed); + void addBed(const std::shared_ptr &bed); + void removeBed(const std::shared_ptr &bed); const HouseBedItemList &getBeds() const { return bedsList; } @@ -226,8 +226,8 @@ class House : public SharedObject { return maxBeds; } - bool transferToDepot(std::shared_ptr player) const; - bool transferToDepot(std::shared_ptr player, std::shared_ptr tile) const; + bool transferToDepot(const std::shared_ptr &player) const; + bool transferToDepot(const std::shared_ptr &player, const std::shared_ptr &tile) const; bool hasItemOnTile() const; bool hasNewOwnership() const; @@ -268,8 +268,8 @@ class House : public SharedObject { bool isLoaded = false; - void handleContainer(ItemList &moveItemList, std::shared_ptr item) const; - void handleWrapableItem(ItemList &moveItemList, std::shared_ptr item, std::shared_ptr player, std::shared_ptr houseTile) const; + void handleContainer(ItemList &moveItemList, const std::shared_ptr &item) const; + void handleWrapableItem(ItemList &moveItemList, const std::shared_ptr &item, const std::shared_ptr &player, const std::shared_ptr &houseTile) const; }; using HouseMap = std::map>; diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 5e728a14ea3..572d04128a4 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "items/tile.hpp" @@ -16,7 +18,7 @@ #include "game/game.hpp" HouseTile::HouseTile(int32_t initX, int32_t initY, int32_t initZ, std::shared_ptr initHouse) : - DynamicTile(initX, initY, initZ), house(initHouse) { } + DynamicTile(initX, initY, initZ), house(std::move(initHouse)) { } void HouseTile::addThing(int32_t index, std::shared_ptr thing) { Tile::addThing(index, thing); @@ -25,7 +27,7 @@ void HouseTile::addThing(int32_t index, std::shared_ptr thing) { return; } - if (std::shared_ptr item = thing->getItem()) { + if (const auto item = thing->getItem()) { updateHouse(item); } } @@ -37,12 +39,12 @@ void HouseTile::internalAddThing(uint32_t index, std::shared_ptr thing) { return; } - if (std::shared_ptr item = thing->getItem()) { + if (const auto item = thing->getItem()) { updateHouse(item); } } -void HouseTile::updateHouse(std::shared_ptr item) { +void HouseTile::updateHouse(const std::shared_ptr &item) { if (item->getParent().get() != this) { return; } @@ -62,7 +64,7 @@ void HouseTile::updateHouse(std::shared_ptr item) { ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr actor /* = nullptr*/) { if (std::shared_ptr creature = thing->getCreature()) { - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } @@ -89,7 +91,7 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr &thi std::shared_ptr HouseTile::queryDestination(int32_t &index, const std::shared_ptr &thing, std::shared_ptr* destItem, uint32_t &tileFlags) { if (std::shared_ptr creature = thing->getCreature()) { - if (std::shared_ptr player = creature->getPlayer()) { + if (const auto player = creature->getPlayer()) { if (!house->isInvited(player)) { const Position &entryPos = house->getEntryPosition(); std::shared_ptr destTile = g_game().map.getTile(entryPos); @@ -115,7 +117,7 @@ std::shared_ptr HouseTile::queryDestination(int32_t &index, const std: } ReturnValue HouseTile::queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor /*= nullptr*/) { - std::shared_ptr item = thing->getItem(); + const auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/map/house/housetile.hpp b/src/map/house/housetile.hpp index b661251dbea..1e7e5a1984d 100644 --- a/src/map/house/housetile.hpp +++ b/src/map/house/housetile.hpp @@ -32,7 +32,7 @@ class HouseTile final : public DynamicTile { } private: - void updateHouse(std::shared_ptr item); + void updateHouse(const std::shared_ptr &item); std::shared_ptr house; }; diff --git a/src/map/map.cpp b/src/map/map.cpp index 85e7de50484..bbff7970dc3 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -209,7 +209,7 @@ void Map::refreshZones(uint16_t x, uint16_t y, uint8_t z) { } } -void Map::setTile(uint16_t x, uint16_t y, uint8_t z, std::shared_ptr newTile) { +void Map::setTile(uint16_t x, uint16_t y, uint8_t z, const std::shared_ptr &newTile) { if (z >= MAP_MAX_LAYERS) { g_logger().error("Attempt to set tile on invalid coordinate: {}", Position(x, y, z).toString()); return; @@ -222,7 +222,7 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, std::shared_ptr newTi } } -bool Map::placeCreature(const Position ¢erPos, std::shared_ptr creature, bool extendedPos /* = false*/, bool forceLogin /* = false*/) { +bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr &creature, bool extendedPos /* = false*/, bool forceLogin /* = false*/) { auto monster = creature->getMonster(); if (monster) { monster->ignoreFieldDamage = true; diff --git a/src/map/map.hpp b/src/map/map.hpp index f6e38cb3eac..787eb584570 100644 --- a/src/map/map.hpp +++ b/src/map/map.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "mapcache.hpp" #include "map/town.hpp" #include "map/house/house.hpp" @@ -59,7 +61,7 @@ class Map : public MapCache { * \param loadNpcs if true, the map custom npcs is loaded * \returns true if the custom map was loaded successfully */ - void loadMapCustom(const std::string &mapName, bool loadHouses, bool loadMonsters, bool loadNpcs, bool loadZones, const int customMapIndex); + void loadMapCustom(const std::string &mapName, bool loadHouses, bool loadMonsters, bool loadNpcs, bool loadZones, int customMapIndex); void loadHouseInfo(); @@ -95,7 +97,7 @@ class Map : public MapCache { * \param extendedPos If true, the creature will in first-hand be placed 2 tiles away * \param forceLogin If true, placing the creature will not fail becase of obstacles (creatures/chests) */ - bool placeCreature(const Position ¢erPos, std::shared_ptr creature, bool extendedPos = false, bool forceLogin = false); + bool placeCreature(const Position ¢erPos, const std::shared_ptr &creature, bool extendedPos = false, bool forceLogin = false); void moveCreature(const std::shared_ptr &creature, const std::shared_ptr &newTile, bool forceTeleport = false); @@ -147,8 +149,8 @@ class Map : public MapCache { /** * Set a single tile. */ - void setTile(uint16_t x, uint16_t y, uint8_t z, std::shared_ptr newTile); - void setTile(const Position &pos, std::shared_ptr newTile) { + void setTile(uint16_t x, uint16_t y, uint8_t z, const std::shared_ptr &newTile); + void setTile(const Position &pos, const std::shared_ptr &newTile) { setTile(pos.x, pos.y, pos.z, newTile); } std::shared_ptr getLoadedTile(uint16_t x, uint16_t y, uint8_t z); diff --git a/src/map/mapcache.cpp b/src/map/mapcache.cpp index e6e2f79b806..3d39fa8943f 100644 --- a/src/map/mapcache.cpp +++ b/src/map/mapcache.cpp @@ -40,7 +40,7 @@ void MapCache::flush() { tiles.clear(); } -void MapCache::parseItemAttr(const std::shared_ptr &BasicItem, std::shared_ptr item) { +void MapCache::parseItemAttr(const std::shared_ptr &BasicItem, const std::shared_ptr &item) { if (BasicItem->charges > 0) { item->setSubType(BasicItem->charges); } @@ -112,7 +112,7 @@ std::shared_ptr MapCache::getOrCreateTileFromCache(const std::unique_ptrgetZ(); - auto map = static_cast(this); + auto map = dynamic_cast(this); std::shared_ptr tile = nullptr; if (cachedTile->isHouse()) { diff --git a/src/map/mapcache.hpp b/src/map/mapcache.hpp index 429d786972b..1fea84885b5 100644 --- a/src/map/mapcache.hpp +++ b/src/map/mapcache.hpp @@ -116,6 +116,6 @@ class MapCache { std::unordered_map mapSectors; private: - void parseItemAttr(const std::shared_ptr &BasicItem, std::shared_ptr item); + void parseItemAttr(const std::shared_ptr &BasicItem, const std::shared_ptr &item); std::shared_ptr createItem(const std::shared_ptr &BasicItem, Position position); }; diff --git a/src/map/utils/astarnodes.cpp b/src/map/utils/astarnodes.cpp index 21ebe5f982f..5c739272a61 100644 --- a/src/map/utils/astarnodes.cpp +++ b/src/map/utils/astarnodes.cpp @@ -171,7 +171,7 @@ AStarNode* AStarNodes::getBestNode() { _mm_store_si128(reinterpret_cast<__m128i*>(indices_array), minindices); int32_t best_node = indices_array[(_mm_ctz(_mm_movemask_epi8(_mm_cmpeq_epi32(minvalues, res))) >> 2)]; - return (openNodes[best_node] ? &nodes[best_node] : NULL); + return (openNodes[best_node] ? &nodes[best_node] : nullptr); #else int32_t best_node_f = std::numeric_limits::max(); int32_t best_node = -1; diff --git a/src/map/utils/astarnodes.hpp b/src/map/utils/astarnodes.hpp index d66171f0d53..dcd74f7039d 100644 --- a/src/map/utils/astarnodes.hpp +++ b/src/map/utils/astarnodes.hpp @@ -40,8 +40,8 @@ class AStarNodes { static constexpr int32_t MAP_DIAGONALWALKCOST = 25; #if defined(__SSE2__) - alignas(16) uint32_t nodesTable[MAX_NODES]; - alignas(64) int32_t calculatedNodes[MAX_NODES]; + alignas(16) uint32_t nodesTable[MAX_NODES] {}; + alignas(64) int32_t calculatedNodes[MAX_NODES] {}; AStarNode nodes[MAX_NODES]; #else AStarNode nodes[MAX_NODES]; diff --git a/src/map/utils/mapsector.hpp b/src/map/utils/mapsector.hpp index 7b95db7f78b..45b963efa30 100644 --- a/src/map/utils/mapsector.hpp +++ b/src/map/utils/mapsector.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "map/map_const.hpp" class Creature; @@ -25,7 +27,7 @@ struct Floor { } void setTile(uint16_t x, uint16_t y, std::shared_ptr tile) { - tiles[x & SECTOR_MASK][y & SECTOR_MASK].first = tile; + tiles[x & SECTOR_MASK][y & SECTOR_MASK].first = std::move(tile); } std::shared_ptr getTileCache(uint16_t x, uint16_t y) const { diff --git a/src/security/argon.cpp b/src/security/argon.cpp index fe11ab0724a..c788ee91d17 100644 --- a/src/security/argon.cpp +++ b/src/security/argon.cpp @@ -26,7 +26,7 @@ void Argon2::updateConstants() { parallelism = g_configManager().getNumber(PARALLELISM, __FUNCTION__); } -uint32_t Argon2::parseBitShift(const std::string &bitShiftStr) const { +uint32_t Argon2::parseBitShift(const std::string &bitShiftStr) { std::stringstream ss(bitShiftStr); int base; int shift; @@ -41,7 +41,6 @@ uint32_t Argon2::parseBitShift(const std::string &bitShiftStr) const { } bool Argon2::verifyPassword(const std::string &password, const std::string &phash) const { - const std::regex re("\\$([A-Za-z0-9+/]+)\\$([A-Za-z0-9+/]+)"); std::smatch match; if (!std::regex_search(phash, match, re)) { @@ -63,7 +62,7 @@ bool Argon2::verifyPassword(const std::string &password, const std::string &phas return computed_hash == hash; } -std::vector Argon2::base64_decode(const std::string &input) const { +std::vector Argon2::base64_decode(const std::string &input) { const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; std::vector ret; int i = 0; diff --git a/src/security/argon.hpp b/src/security/argon.hpp index ea09dcffccb..3ca3b216af0 100644 --- a/src/security/argon.hpp +++ b/src/security/argon.hpp @@ -23,14 +23,14 @@ class Argon2 { bool argon(const std::string &password_attempt, const std::string &hashed_password) const; private: - uint32_t parseBitShift(const std::string &bitShiftStr) const; + static uint32_t parseBitShift(const std::string &bitShiftStr); bool verifyPassword(const std::string &password, const std::string &phash) const; - std::vector base64_decode(const std::string &input) const; + static std::vector base64_decode(const std::string &input); static const std::regex re; static const std::string base64_chars; std::string m_const_str; - uint32_t m_cost; - uint32_t t_cost; - uint32_t parallelism; + uint32_t m_cost {}; + uint32_t t_cost {}; + uint32_t parallelism {}; }; diff --git a/src/security/rsa.cpp b/src/security/rsa.cpp index fc28d931f66..d0dbc58148c 100644 --- a/src/security/rsa.cpp +++ b/src/security/rsa.cpp @@ -123,7 +123,7 @@ std::string RSA::base64Decrypt(const std::string &input) const { }; if (input.empty()) { - return std::string(); + return {}; } size_t length = input.length(); diff --git a/src/security/rsa.hpp b/src/security/rsa.hpp index a6de23b4e13..a6575a5515f 100644 --- a/src/security/rsa.hpp +++ b/src/security/rsa.hpp @@ -13,7 +13,7 @@ class Logger; class RSA { public: - RSA(Logger &logger); + explicit RSA(Logger &logger); ~RSA(); // Singleton - ensures we don't accidentally copy it @@ -34,8 +34,8 @@ class RSA { private: Logger &logger; - mpz_t n; - mpz_t d; + mpz_t n {}; + mpz_t d {}; }; constexpr auto g_RSA = RSA::getInstance; diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index 3072384420d..4a4732ba711 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -15,7 +15,7 @@ #include "game/scheduling/dispatcher.hpp" #include "server/server.hpp" -Connection_ptr ConnectionManager::createConnection(asio::io_service &io_service, ConstServicePort_ptr servicePort) { +Connection_ptr ConnectionManager::createConnection(asio::io_service &io_service, const ConstServicePort_ptr &servicePort) { auto connection = std::make_shared(io_service, servicePort); connections.emplace(connection); return connection; @@ -247,7 +247,7 @@ void Connection::parsePacket(const std::error_code &error) { checksum = 0; } - uint32_t recvChecksum = msg.get(); + auto recvChecksum = msg.get(); if (recvChecksum != checksum) { // it might not have been the checksum, step back msg.skipBytes(-CHECKSUM_LENGTH); @@ -392,7 +392,7 @@ void Connection::onWriteOperation(const std::error_code &error) { } } -void Connection::handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code &error) { +void Connection::handleTimeout(const ConnectionWeak_ptr &connectionWeak, const std::error_code &error) { if (error == asio::error::operation_aborted) { return; } diff --git a/src/server/network/connection/connection.hpp b/src/server/network/connection/connection.hpp index 76d9b1c1876..788ae0a3a43 100644 --- a/src/server/network/connection/connection.hpp +++ b/src/server/network/connection/connection.hpp @@ -37,7 +37,7 @@ class ConnectionManager { return inject(); } - Connection_ptr createConnection(asio::io_service &io_service, ConstServicePort_ptr servicePort); + Connection_ptr createConnection(asio::io_service &io_service, const ConstServicePort_ptr &servicePort); void releaseConnection(const Connection_ptr &connection); void closeAll(); @@ -76,7 +76,7 @@ class Connection : public std::enable_shared_from_this { void onWriteOperation(const std::error_code &error); - static void handleTimeout(ConnectionWeak_ptr connectionWeak, const std::error_code &error); + static void handleTimeout(const ConnectionWeak_ptr &connectionWeak, const std::error_code &error); void closeSocket(); void internalWorker(); diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index 255899f2f99..e79d00883c0 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -57,7 +57,7 @@ bool Protocol::sendRecvMessageCallback(NetworkMessage &msg) { bool Protocol::onRecvMessage(NetworkMessage &msg) { if (checksumMethod != CHECKSUM_METHOD_NONE) { - uint32_t recvChecksum = msg.get(); + auto recvChecksum = msg.get(); if (checksumMethod == CHECKSUM_METHOD_SEQUENCE) { if (recvChecksum == 0) { // checksum 0 indicate that the packet should be connection ping - 0x1C packet header @@ -169,7 +169,7 @@ bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { readPos += 8; } - uint16_t innerLength = msg.get(); + auto innerLength = msg.get(); if (std::cmp_greater(innerLength, msgLength - 2)) { return false; } @@ -202,7 +202,9 @@ bool Protocol::compression(OutputMessage &msg) const { return false; } - static const thread_local auto &compress = std::make_unique(); + static thread_local auto compress_ptr = std::make_unique(); + static const auto &compress = compress_ptr; + if (!compress->stream) { return false; } diff --git a/src/server/network/protocol/protocol.hpp b/src/server/network/protocol/protocol.hpp index 54e3dcfd4c3..d1b69ab8821 100644 --- a/src/server/network/protocol/protocol.hpp +++ b/src/server/network/protocol/protocol.hpp @@ -14,7 +14,7 @@ class Protocol : public std::enable_shared_from_this { public: - explicit Protocol(Connection_ptr initConnection) : + explicit Protocol(const Connection_ptr &initConnection) : connectionPtr(initConnection) { } virtual ~Protocol() = default; diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 60d9b3f74a1..0108513d137 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -29,7 +29,6 @@ #include "creatures/players/achievement/player_achievement.hpp" #include "creatures/players/cyclopedia/player_badge.hpp" #include "creatures/players/cyclopedia/player_cyclopedia.hpp" -#include "creatures/players/cyclopedia/player_title.hpp" #include "creatures/players/grouping/familiars.hpp" #include "server/network/protocol/protocolgame.hpp" #include "game/scheduling/dispatcher.hpp" @@ -73,7 +72,7 @@ namespace { return totalIterationCount; } - void addOutfitAndMountBytes(NetworkMessage &msg, std::shared_ptr item, const CustomAttribute* attribute, const std::string &head, const std::string &body, const std::string &legs, const std::string &feet, bool addAddon = false, bool addByte = false) { + void addOutfitAndMountBytes(NetworkMessage &msg, const std::shared_ptr &item, const CustomAttribute* attribute, const std::string &head, const std::string &body, const std::string &legs, const std::string &feet, bool addAddon = false, bool addByte = false) { auto look = attribute->getAttribute(); msg.add(look); if (look != 0) { @@ -118,7 +117,7 @@ namespace { * @param msg The network message to which the imbuement damage should be added. * @param player Pointer to the player for whom the imbuement damage should be handled. */ - void handleImbuementDamage(NetworkMessage &msg, std::shared_ptr player) { + void handleImbuementDamage(NetworkMessage &msg, const std::shared_ptr &player) { bool imbueDmg = false; std::shared_ptr weapon = player->getWeapon(); if (weapon) { @@ -156,7 +155,7 @@ namespace { * * @param[in] player The pointer to the player whose equipped items are considered. */ - void calculateAbsorbValues(std::shared_ptr player, NetworkMessage &msg, uint8_t &combats) { + void calculateAbsorbValues(const std::shared_ptr &player, NetworkMessage &msg, uint8_t &combats) { alignas(16) uint16_t damageModifiers[COMBAT_COUNT] = { 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000, 10000 }; for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { @@ -164,7 +163,7 @@ namespace { continue; } - std::shared_ptr item = player->getInventoryItem(static_cast(slot)); + const auto item = player->getInventoryItem(static_cast(slot)); if (!item) { continue; } @@ -247,12 +246,12 @@ namespace { } } // namespace -ProtocolGame::ProtocolGame(Connection_ptr initConnection) : +ProtocolGame::ProtocolGame(const Connection_ptr &initConnection) : Protocol(initConnection) { version = CLIENT_VERSION; } -void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier) { +void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier) const { const ItemType &it = Item::items[id]; msg.add(it.id); @@ -311,7 +310,7 @@ void ProtocolGame::AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint } } -void ProtocolGame::AddItem(NetworkMessage &msg, std::shared_ptr item) { +void ProtocolGame::AddItem(NetworkMessage &msg, const std::shared_ptr &item) { if (!item) { return; } @@ -349,7 +348,7 @@ void ProtocolGame::AddItem(NetworkMessage &msg, std::shared_ptr item) { if (container && containerType == 0 && container->getHoldingPlayer() == player) { uint32_t lootFlags = 0; uint32_t obtainFlags = 0; - for (auto [category, containerMap] : player->m_managedContainers) { + for (const auto &[category, containerMap] : player->m_managedContainers) { if (!isValidObjectCategory(category)) { continue; } @@ -372,7 +371,7 @@ void ProtocolGame::AddItem(NetworkMessage &msg, std::shared_ptr item) { // Quiver ammo count if (container && containerType == 0 && item->isQuiver() && player->getThing(CONST_SLOT_RIGHT) == item) { uint16_t ammoTotal = 0; - for (std::shared_ptr listItem : container->getItemList()) { + for (const std::shared_ptr &listItem : container->getItemList()) { if (player->getLevel() >= Item::items[listItem->getID()].minReqLevel) { ammoTotal += listItem->getItemCount(); } @@ -707,7 +706,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { return; } - OperatingSystem_t operatingSystem = static_cast(msg.get()); + auto operatingSystem = static_cast(msg.get()); version = msg.get(); // Protocol version g_logger().trace("Protocol version: {}", version); @@ -756,7 +755,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { std::ostringstream ss; std::string sessionKey = msg.getString(); std::string accountDescriptor = sessionKey; - std::string password = ""; + std::string password; if (authType != "session") { size_t pos = sessionKey.find('\n'); @@ -793,7 +792,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { foundPlayer->client->disconnectClient("You are already connected through another client. Please use only one client at a time!"); } - uint32_t timeStamp = msg.get(); + auto timeStamp = msg.get(); uint8_t randNumber = msg.getByte(); if (challengeTimestamp != timeStamp || challengeRandom != randNumber) { disconnect(); @@ -801,7 +800,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { } // OTCv8 version detection - uint16_t otcV8StringLength = msg.get(); + auto otcV8StringLength = msg.get(); if (otcV8StringLength == 5 && msg.getString(5) == "OTCv8") { otclientV8 = msg.get(); // 253, 260, 261, ... } @@ -887,7 +886,7 @@ void ProtocolGame::onConnect() { // To support 11.10-, not have problems with 11.11+ output->add(adlerChecksum(output->getOutputBuffer() + sizeof(uint32_t), 8)); - send(std::move(output)); + send(output); } void ProtocolGame::disconnectClient(const std::string &message) const { @@ -1380,12 +1379,12 @@ void ProtocolGame::parseHotkeyEquip(NetworkMessage &msg) { return; } - uint16_t itemId = msg.get(); - uint8_t tier = msg.get(); + auto itemId = msg.get(); + auto tier = msg.get(); g_game().playerEquipItem(player->getID(), itemId, Item::items[itemId].upgradeClassification > 0, tier); } -void ProtocolGame::GetTileDescription(std::shared_ptr tile, NetworkMessage &msg) { +void ProtocolGame::GetTileDescription(const std::shared_ptr &tile, NetworkMessage &msg) { if (oldProtocol) { msg.add(0x00); // Env effects } @@ -1416,8 +1415,7 @@ void ProtocolGame::GetTileDescription(std::shared_ptr tile, NetworkMessage const CreatureVector* creatures = tile->getCreatures(); if (creatures) { bool playerAdded = false; - for (auto it = creatures->rbegin(); it != creatures->rend(); ++it) { - std::shared_ptr creature = *it; + for (auto creature : std::ranges::reverse_view(*creatures)) { if (!player->canSeeCreature(creature)) { continue; } @@ -1541,7 +1539,7 @@ void ProtocolGame::checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &remo } } -bool ProtocolGame::canSee(std::shared_ptr c) const { +bool ProtocolGame::canSee(const std::shared_ptr &c) const { if (!c || !player || c->isRemoved()) { return false; } @@ -1594,12 +1592,12 @@ void ProtocolGame::parseChannelExclude(NetworkMessage &msg) { } void ProtocolGame::parseOpenChannel(NetworkMessage &msg) { - uint16_t channelId = msg.get(); + auto channelId = msg.get(); g_game().playerOpenChannel(player->getID(), channelId); } void ProtocolGame::parseCloseChannel(NetworkMessage &msg) { - uint16_t channelId = msg.get(); + auto channelId = msg.get(); g_game().playerCloseChannel(player->getID(), channelId); } @@ -1696,7 +1694,7 @@ void ProtocolGame::parseSetOutfit(NetworkMessage &msg) { msg.get(); } else if (outfitType == 2) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); newOutfit.lookMount = msg.get(); newOutfit.lookMountHead = std::min(132, msg.getByte()); @@ -1717,7 +1715,7 @@ void ProtocolGame::parseToggleMount(NetworkMessage &msg) { void ProtocolGame::parseApplyImbuement(NetworkMessage &msg) { uint8_t slot = msg.getByte(); - uint32_t imbuementId = msg.get(); + auto imbuementId = msg.get(); bool protectionCharm = msg.getByte() != 0x00; g_game().playerApplyImbuement(player->getID(), imbuementId, slot, protectionCharm); } @@ -1733,7 +1731,7 @@ void ProtocolGame::parseCloseImbuementWindow(NetworkMessage &) { void ProtocolGame::parseUseItem(NetworkMessage &msg) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); uint8_t index = msg.getByte(); g_game().playerUseItem(player->getID(), pos, stackpos, index, itemId); @@ -1741,19 +1739,19 @@ void ProtocolGame::parseUseItem(NetworkMessage &msg) { void ProtocolGame::parseUseItemEx(NetworkMessage &msg) { Position fromPos = msg.getPosition(); - uint16_t fromItemId = msg.get(); + auto fromItemId = msg.get(); uint8_t fromStackPos = msg.getByte(); Position toPos = msg.getPosition(); - uint16_t toItemId = msg.get(); + auto toItemId = msg.get(); uint8_t toStackPos = msg.getByte(); g_game().playerUseItemEx(player->getID(), fromPos, fromStackPos, fromItemId, toPos, toStackPos, toItemId); } void ProtocolGame::parseUseWithCreature(NetworkMessage &msg) { Position fromPos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t fromStackPos = msg.getByte(); - uint32_t creatureId = msg.get(); + auto creatureId = msg.get(); g_game().playerUseWithCreature(player->getID(), fromPos, fromStackPos, creatureId, itemId); } @@ -1779,7 +1777,7 @@ void ProtocolGame::parseTeleport(NetworkMessage &msg) { void ProtocolGame::parseThrow(NetworkMessage &msg) { Position fromPos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t fromStackpos = msg.getByte(); Position toPos = msg.getPosition(); uint8_t count = msg.getByte(); @@ -1791,13 +1789,13 @@ void ProtocolGame::parseThrow(NetworkMessage &msg) { void ProtocolGame::parseLookAt(NetworkMessage &msg) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerLookAt(player->getID(), itemId, pos, stackpos); } void ProtocolGame::parseLookInBattleList(NetworkMessage &msg) { - uint32_t creatureId = msg.get(); + auto creatureId = msg.get(); g_game().playerLookInBattleList(player->getID(), creatureId); } @@ -1808,7 +1806,7 @@ void ProtocolGame::parseQuickLoot(NetworkMessage &msg) { uint8_t variant = msg.getByte(); const Position pos = msg.getPosition(); - uint16_t itemId = 0; + auto itemId = 0; uint8_t stackpos = 0; bool lootAllCorpses = true; bool autoLoot = true; @@ -1822,7 +1820,6 @@ void ProtocolGame::parseQuickLoot(NetworkMessage &msg) { autoLoot = false; } g_logger().debug("[{}] variant {}, pos {}, itemId {}, stackPos {}", __FUNCTION__, variant, pos.toString(), itemId, stackpos); - g_game().playerQuickLoot(player->getID(), pos, itemId, stackpos, nullptr, lootAllCorpses, autoLoot); } @@ -1833,32 +1830,32 @@ void ProtocolGame::parseLootContainer(NetworkMessage &msg) { uint8_t action = msg.getByte(); if (action == 0) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerSetManagedContainer(player->getID(), category, pos, itemId, stackpos, true); } else if (action == 1) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); g_game().playerClearManagedContainer(player->getID(), category, true); } else if (action == 2) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); g_game().playerOpenManagedContainer(player->getID(), category, true); } else if (action == 3) { bool useMainAsFallback = msg.getByte() == 1; g_game().playerSetQuickLootFallback(player->getID(), useMainAsFallback); } else if (action == 4) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_logger().debug("[{}] action {}, category {}, pos {}, itemId {}, stackPos {}", __FUNCTION__, action, static_cast(category), pos.toString(), itemId, stackpos); g_game().playerSetManagedContainer(player->getID(), category, pos, itemId, stackpos, false); } else if (action == 5) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); g_game().playerClearManagedContainer(player->getID(), category, false); } else if (action == 6) { - ObjectCategory_t category = (ObjectCategory_t)msg.getByte(); + auto category = (ObjectCategory_t)msg.getByte(); g_game().playerOpenManagedContainer(player->getID(), category, false); } @@ -1870,10 +1867,10 @@ void ProtocolGame::parseQuickLootBlackWhitelist(NetworkMessage &msg) { return; } - QuickLootFilter_t filter = (QuickLootFilter_t)msg.getByte(); + auto filter = (QuickLootFilter_t)msg.getByte(); std::vector listedItems; - uint16_t size = msg.get(); + auto size = msg.get(); listedItems.reserve(size); for (int i = 0; i < size; i++) { @@ -1887,7 +1884,7 @@ void ProtocolGame::parseSay(NetworkMessage &msg) { std::string receiver; uint16_t channelId; - SpeakClasses type = static_cast(msg.getByte()); + auto type = static_cast(msg.getByte()); switch (type) { case TALKTYPE_PRIVATE_TO: case TALKTYPE_PRIVATE_RED_TO: @@ -1932,38 +1929,38 @@ void ProtocolGame::parseFightModes(NetworkMessage &msg) { } void ProtocolGame::parseAttack(NetworkMessage &msg) { - uint32_t creatureId = msg.get(); + auto creatureId = msg.get(); // msg.get(); creatureId (same as above) g_game().playerSetAttackedCreature(player->getID(), creatureId); } void ProtocolGame::parseFollow(NetworkMessage &msg) { - uint32_t creatureId = msg.get(); + auto creatureId = msg.get(); // msg.get(); creatureId (same as above) g_game().playerFollowCreature(player->getID(), creatureId); } void ProtocolGame::parseTextWindow(NetworkMessage &msg) { - uint32_t windowTextId = msg.get(); + auto windowTextId = msg.get(); const std::string newText = msg.getString(); g_game().playerWriteItem(player->getID(), windowTextId, newText); } void ProtocolGame::parseHouseWindow(NetworkMessage &msg) { uint8_t doorId = msg.getByte(); - uint32_t id = msg.get(); + auto id = msg.get(); const std::string text = msg.getString(); g_game().playerUpdateHouseWindow(player->getID(), doorId, id, text); } void ProtocolGame::parseLookInShop(NetworkMessage &msg) { - uint16_t id = msg.get(); + auto id = msg.get(); uint8_t count = msg.getByte(); g_game().playerLookInShop(player->getID(), id, count); } void ProtocolGame::parsePlayerBuyOnShop(NetworkMessage &msg) { - uint16_t id = msg.get(); + auto id = msg.get(); uint8_t count = msg.getByte(); uint16_t amount = oldProtocol ? static_cast(msg.getByte()) : msg.get(); bool ignoreCap = msg.getByte() != 0; @@ -1972,7 +1969,7 @@ void ProtocolGame::parsePlayerBuyOnShop(NetworkMessage &msg) { } void ProtocolGame::parsePlayerSellOnShop(NetworkMessage &msg) { - uint16_t id = msg.get(); + auto id = msg.get(); uint8_t count = std::max(msg.getByte(), (uint8_t)1); uint16_t amount = oldProtocol ? static_cast(msg.getByte()) : msg.get(); bool ignoreEquipped = msg.getByte() != 0; @@ -1982,9 +1979,9 @@ void ProtocolGame::parsePlayerSellOnShop(NetworkMessage &msg) { void ProtocolGame::parseRequestTrade(NetworkMessage &msg) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); - uint32_t playerId = msg.get(); + auto playerId = msg.get(); g_game().playerRequestTrade(player->getID(), pos, stackpos, playerId, itemId); } @@ -2000,13 +1997,13 @@ void ProtocolGame::parseAddVip(NetworkMessage &msg) { } void ProtocolGame::parseRemoveVip(NetworkMessage &msg) { - uint32_t guid = msg.get(); + auto guid = msg.get(); g_game().playerRequestRemoveVip(player->getID(), guid); } void ProtocolGame::parseEditVip(NetworkMessage &msg) { std::vector vipGroupsId; - uint32_t guid = msg.get(); + auto guid = msg.get(); const std::string description = msg.getString(); uint32_t icon = std::min(10, msg.get()); // 10 is max icon in 9.63 bool notify = msg.getByte() != 0; @@ -2046,7 +2043,7 @@ void ProtocolGame::parseVipGroupActions(NetworkMessage &msg) { void ProtocolGame::parseRotateItem(NetworkMessage &msg) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); const auto &itemType = Item::items[itemId]; if (itemType.isPodium) { @@ -2058,7 +2055,7 @@ void ProtocolGame::parseRotateItem(NetworkMessage &msg) { void ProtocolGame::parseWrapableItem(NetworkMessage &msg) { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerWrapableItem(player->getID(), pos, stackpos, itemId); } @@ -2073,7 +2070,7 @@ void ProtocolGame::parseInspectionObject(NetworkMessage &msg) { Position pos = msg.getPosition(); g_game().playerInspectItem(player, pos); } else if (inspectionType == INSPECT_NPCTRADE || inspectionType == INSPECT_CYCLOPEDIA) { - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint16_t itemCount = msg.getByte(); g_game().playerInspectItem(player, itemId, static_cast(itemCount), (inspectionType == INSPECT_CYCLOPEDIA)); } @@ -2089,7 +2086,7 @@ void ProtocolGame::sendSessionEndInformation(SessionEndInformations information) disconnect(); } -void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, std::shared_ptr item, bool cyclopedia) { +void ProtocolGame::sendItemInspection(uint16_t itemId, uint8_t itemCount, const std::shared_ptr &item, bool cyclopedia) { if (oldProtocol) { return; } @@ -2154,9 +2151,9 @@ void ProtocolGame::parseHighscores(NetworkMessage &msg) { return; } - HighscoreType_t type = static_cast(msg.getByte()); + auto type = static_cast(msg.getByte()); uint8_t category = msg.getByte(); - uint32_t vocation = msg.get(); + auto vocation = msg.get(); uint16_t page = 1; const std::string worldName = msg.getString(); msg.getByte(); // Game World Category @@ -2176,7 +2173,7 @@ void ProtocolGame::parseTaskHuntingAction(NetworkMessage &msg) { uint8_t slot = msg.getByte(); uint8_t action = msg.getByte(); bool upgrade = msg.getByte() != 0; - uint16_t raceId = msg.get(); + auto raceId = msg.get(); if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return; @@ -2279,7 +2276,7 @@ void ProtocolGame::parseConfigureShowOffSocket(NetworkMessage &msg) { } Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerConfigureShowOffSocket(player->getID(), pos, stackpos, itemId); } @@ -2310,7 +2307,7 @@ void ProtocolGame::parseBestiarysendRaces() { msg.add(BESTY_RACE_LAST); std::map mtype_list = g_game().getBestiaryList(); for (uint8_t i = BESTY_RACE_FIRST; i <= BESTY_RACE_LAST; i++) { - std::string BestClass = ""; + std::string BestClass; uint16_t count = 0; for (const auto &rit : mtype_list) { const auto mtype = g_monsters().getMonsterType(rit.second); @@ -2348,8 +2345,8 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) { return; } - uint16_t raceId = msg.get(); - std::string Class = ""; + auto raceId = msg.get(); + std::string Class; std::shared_ptr mtype = nullptr; std::map mtype_list = g_game().getBestiaryList(); @@ -2446,9 +2443,9 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) { std::map elements = g_iobestiary().getMonsterElements(mtype); newmsg.addByte(elements.size()); - for (auto it = std::begin(elements), end = std::end(elements); it != end; it++) { - newmsg.addByte(it->first); - newmsg.add(it->second); + for (auto &element : elements) { + newmsg.addByte(element.first); + newmsg.add(element.second); } newmsg.add(1); @@ -2471,7 +2468,7 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) { } void ProtocolGame::parseCyclopediaMonsterTracker(NetworkMessage &msg) { - uint16_t monsterRaceId = msg.get(); + auto monsterRaceId = msg.get(); // Bosstiary tracker: 0 = disabled, 1 = enabled // Bestiary tracker: 1 = enabled auto trackerButtonType = msg.getByte(); @@ -2726,16 +2723,16 @@ void ProtocolGame::parsePartyAnalyzerAction(NetworkMessage &msg) const { return; } - PartyAnalyzerAction_t action = static_cast(msg.getByte()); + auto action = static_cast(msg.getByte()); if (action == PARTYANALYZERACTION_RESET) { party->resetAnalyzer(); } else if (action == PARTYANALYZERACTION_PRICETYPE) { party->switchAnalyzerPriceType(); } else if (action == PARTYANALYZERACTION_PRICEVALUE) { - uint16_t size = msg.get(); + auto size = msg.get(); for (uint16_t i = 1; i <= size; i++) { - uint16_t itemId = msg.get(); - uint64_t price = msg.get(); + auto itemId = msg.get(); + auto price = msg.get(); player->setItemCustomPrice(itemId, price); } party->reloadPrices(); @@ -2759,7 +2756,7 @@ void ProtocolGame::parseLeaderFinderWindow(NetworkMessage &msg) { break; } case 2: { - uint32_t memberID = msg.get(); + auto memberID = msg.get(); std::shared_ptr member = g_game().getPlayerByGUID(memberID); if (!member) { return; @@ -2817,7 +2814,7 @@ void ProtocolGame::parseMemberFinderWindow(NetworkMessage &msg) { if (action == 0) { player->sendTeamFinderList(); } else { - uint32_t leaderID = msg.get(); + auto leaderID = msg.get(); std::shared_ptr leader = g_game().getPlayerByGUID(leaderID); if (!leader) { return; @@ -2848,9 +2845,9 @@ void ProtocolGame::parseSendBuyCharmRune(NetworkMessage &msg) { return; } - charmRune_t runeID = static_cast(msg.getByte()); + auto runeID = static_cast(msg.getByte()); uint8_t action = msg.getByte(); - uint16_t raceid = msg.get(); + auto raceid = msg.get(); g_iobestiary().sendBuyCharmRune(player, runeID, action, raceid); } @@ -2957,14 +2954,14 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) { std::ostringstream ss; std::map race = {}; - std::string text = ""; + std::string text; uint8_t search = msg.getByte(); if (search == 1) { - uint16_t monsterAmount = msg.get(); + auto monsterAmount = msg.get(); std::map mtype_list = g_game().getBestiaryList(); for (uint16_t monsterCount = 1; monsterCount <= monsterAmount; monsterCount++) { - uint16_t raceid = msg.get(); + auto raceid = msg.get(); if (player->getBestiaryKillCount(raceid) > 0) { auto it = mtype_list.find(raceid); if (it != mtype_list.end()) { @@ -3035,7 +3032,7 @@ void ProtocolGame::parseBugReport(NetworkMessage &msg) { } void ProtocolGame::parseGreet(NetworkMessage &msg) { - uint32_t npcId = msg.get(); + auto npcId = msg.get(); g_game().playerNpcGreet(player->getID(), npcId); } @@ -3089,22 +3086,22 @@ void ProtocolGame::parseSendResourceBalance() { } void ProtocolGame::parseInviteToParty(NetworkMessage &msg) { - uint32_t targetId = msg.get(); + auto targetId = msg.get(); g_game().playerInviteToParty(player->getID(), targetId); } void ProtocolGame::parseJoinParty(NetworkMessage &msg) { - uint32_t targetId = msg.get(); + auto targetId = msg.get(); g_game().playerJoinParty(player->getID(), targetId); } void ProtocolGame::parseRevokePartyInvite(NetworkMessage &msg) { - uint32_t targetId = msg.get(); + auto targetId = msg.get(); g_game().playerRevokePartyInvitation(player->getID(), targetId); } void ProtocolGame::parsePassPartyLeadership(NetworkMessage &msg) { - uint32_t targetId = msg.get(); + auto targetId = msg.get(); g_game().playerPassPartyLeadership(player->getID(), targetId); } @@ -3114,7 +3111,7 @@ void ProtocolGame::parseEnableSharedPartyExperience(NetworkMessage &msg) { } void ProtocolGame::parseQuestLine(NetworkMessage &msg) { - uint16_t questId = msg.get(); + auto questId = msg.get(); g_game().playerShowQuestLine(player->getID(), questId); } @@ -3130,8 +3127,8 @@ void ProtocolGame::parseMarketBrowse(NetworkMessage &msg) { } else if ((oldProtocol && browseId == MARKETREQUEST_OWN_HISTORY_OLD) || (!oldProtocol && browseId == MARKETREQUEST_OWN_HISTORY)) { g_game().playerBrowseMarketOwnHistory(player->getID()); } else if (!oldProtocol) { - uint16_t itemId = msg.get(); - uint8_t tier = msg.get(); + auto itemId = msg.get(); + auto tier = msg.get(); player->sendMarketEnter(player->getLastDepotId()); g_game().playerBrowseMarket(player->getID(), itemId, tier); } else { @@ -3141,13 +3138,13 @@ void ProtocolGame::parseMarketBrowse(NetworkMessage &msg) { void ProtocolGame::parseMarketCreateOffer(NetworkMessage &msg) { uint8_t type = msg.getByte(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t itemTier = 0; if (!oldProtocol && Item::items[itemId].upgradeClassification > 0) { itemTier = msg.getByte(); } - uint16_t amount = msg.get(); + auto amount = msg.get(); uint64_t price = oldProtocol ? static_cast(msg.get()) : msg.get(); bool anonymous = (msg.getByte() != 0); if (amount > 0 && price > 0) { @@ -3156,8 +3153,8 @@ void ProtocolGame::parseMarketCreateOffer(NetworkMessage &msg) { } void ProtocolGame::parseMarketCancelOffer(NetworkMessage &msg) { - uint32_t timestamp = msg.get(); - uint16_t counter = msg.get(); + auto timestamp = msg.get(); + auto counter = msg.get(); if (counter > 0) { g_game().playerCancelMarketOffer(player->getID(), timestamp, counter); } @@ -3166,9 +3163,9 @@ void ProtocolGame::parseMarketCancelOffer(NetworkMessage &msg) { } void ProtocolGame::parseMarketAcceptOffer(NetworkMessage &msg) { - uint32_t timestamp = msg.get(); - uint16_t counter = msg.get(); - uint16_t amount = msg.get(); + auto timestamp = msg.get(); + auto counter = msg.get(); + auto amount = msg.get(); if (amount > 0 && counter > 0) { g_game().playerAcceptMarketOffer(player->getID(), timestamp, counter, amount); } @@ -3177,7 +3174,7 @@ void ProtocolGame::parseMarketAcceptOffer(NetworkMessage &msg) { } void ProtocolGame::parseModalWindowAnswer(NetworkMessage &msg) { - uint32_t id = msg.get(); + auto id = msg.get(); uint8_t button = msg.getByte(); uint8_t choice = msg.getByte(); g_game().playerAnswerModalWindow(player->getID(), id, button, choice); @@ -3205,7 +3202,7 @@ void ProtocolGame::parseBrowseField(NetworkMessage &msg) { void ProtocolGame::parseSeekInContainer(NetworkMessage &msg) { uint8_t containerId = msg.getByte(); - uint16_t index = msg.get(); + auto index = msg.get(); auto primaryType = msg.getByte(); g_game().playerSeekInContainer(player->getID(), containerId, index, primaryType); } @@ -3239,7 +3236,7 @@ void ProtocolGame::sendChannelEvent(uint16_t channelId, const std::string &playe writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureOutfit(std::shared_ptr creature, const Outfit_t &outfit) { +void ProtocolGame::sendCreatureOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) { if (!canSee(creature)) { return; } @@ -3264,7 +3261,7 @@ void ProtocolGame::sendCreatureOutfit(std::shared_ptr creature, const writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureLight(std::shared_ptr creature) { +void ProtocolGame::sendCreatureLight(const std::shared_ptr &creature) { if (!canSee(creature)) { return; } @@ -3274,7 +3271,7 @@ void ProtocolGame::sendCreatureLight(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::addCreatureIcon(NetworkMessage &msg, std::shared_ptr creature) { +void ProtocolGame::addCreatureIcon(NetworkMessage &msg, const std::shared_ptr &creature) { if (!creature || !player || oldProtocol) { return; } @@ -3291,7 +3288,7 @@ void ProtocolGame::addCreatureIcon(NetworkMessage &msg, std::shared_ptr creature) { +void ProtocolGame::sendCreatureIcon(const std::shared_ptr &creature) { if (!creature || !player || oldProtocol) { return; } @@ -3323,7 +3320,7 @@ void ProtocolGame::sendTibiaTime(int32_t time) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureWalkthrough(std::shared_ptr creature, bool walkthrough) { +void ProtocolGame::sendCreatureWalkthrough(const std::shared_ptr &creature, bool walkthrough) { if (!canSee(creature)) { return; } @@ -3335,7 +3332,7 @@ void ProtocolGame::sendCreatureWalkthrough(std::shared_ptr creature, b writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureShield(std::shared_ptr creature) { +void ProtocolGame::sendCreatureShield(const std::shared_ptr &creature) { if (!canSee(creature)) { return; } @@ -3347,7 +3344,7 @@ void ProtocolGame::sendCreatureShield(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureEmblem(std::shared_ptr creature) { +void ProtocolGame::sendCreatureEmblem(const std::shared_ptr &creature) { if (!creature || !canSee(creature) || oldProtocol) { return; } @@ -3369,7 +3366,7 @@ void ProtocolGame::sendCreatureEmblem(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSkull(std::shared_ptr creature) { +void ProtocolGame::sendCreatureSkull(const std::shared_ptr &creature) { if (g_game().getWorldType() != WORLD_TYPE_PVP) { return; } @@ -3385,7 +3382,7 @@ void ProtocolGame::sendCreatureSkull(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureType(std::shared_ptr creature, uint8_t creatureType) { +void ProtocolGame::sendCreatureType(const std::shared_ptr &creature, uint8_t creatureType) { NetworkMessage msg; msg.addByte(0x95); msg.add(creature->getID()); @@ -3405,7 +3402,7 @@ void ProtocolGame::sendCreatureType(std::shared_ptr creature, uint8_t writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSquare(std::shared_ptr creature, SquareColor_t color) { +void ProtocolGame::sendCreatureSquare(const std::shared_ptr &creature, SquareColor_t color) { if (!canSee(creature)) { return; } @@ -3554,7 +3551,7 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() { if (i == SKILL_LIFE_LEECH_CHANCE || i == SKILL_MANA_LEECH_CHANCE) { continue; } - skills_t skill = static_cast(i); + auto skill = static_cast(i); msg.add(std::min(player->getSkillLevel(skill), std::numeric_limits::max())); msg.add(0); } @@ -3738,7 +3735,7 @@ void ProtocolGame::sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t writeToOutputBuffer(msg); } -void ProtocolGame::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, std::vector> achievementsUnlocked) { +void ProtocolGame::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked) { if (!player || oldProtocol) { return; } @@ -4622,7 +4619,7 @@ void ProtocolGame::sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8 writeToOutputBuffer(msg); } -void ProtocolGame::sendContainer(uint8_t cid, std::shared_ptr container, bool hasParent, uint16_t firstIndex) { +void ProtocolGame::sendContainer(uint8_t cid, const std::shared_ptr &container, bool hasParent, uint16_t firstIndex) { if (!player) { return; } @@ -4681,7 +4678,7 @@ void ProtocolGame::sendContainer(uint8_t cid, std::shared_ptr contain msg.addByte(std::min(maxItemsToSend, containerSize)); uint32_t i = 0; - for (ItemDeque::const_iterator it = itemList.begin() + firstIndex, end = itemList.end(); i < maxItemsToSend && it != end; ++it, ++i) { + for (auto it = itemList.begin() + firstIndex, end = itemList.end(); i < maxItemsToSend && it != end; ++it, ++i) { AddItem(msg, *it); } } @@ -4747,7 +4744,7 @@ void ProtocolGame::sendLootContainers() { msg.addByte(player->quickLootFallbackToMainContainer ? 1 : 0); std::map, std::shared_ptr>> managedContainersMap; - for (auto [category, containersPair] : player->m_managedContainers) { + for (const auto &[category, containersPair] : player->m_managedContainers) { if (containersPair.first && !containersPair.first->isRemoved()) { managedContainersMap[category].first = containersPair.first; } @@ -4759,7 +4756,7 @@ void ProtocolGame::sendLootContainers() { auto msgPosition = msg.getBufferPosition(); msg.skipBytes(1); uint8_t containers = 0; - for (auto [category, containersPair] : managedContainersMap) { + for (const auto &[category, containersPair] : managedContainersMap) { if (!isValidObjectCategory(category)) { continue; } @@ -4776,7 +4773,7 @@ void ProtocolGame::sendLootContainers() { writeToOutputBuffer(msg); } -void ProtocolGame::sendLootStats(std::shared_ptr item, uint8_t count) { +void ProtocolGame::sendLootStats(const std::shared_ptr &item, uint8_t count) { if (!item) { return; } @@ -4800,7 +4797,7 @@ void ProtocolGame::sendLootStats(std::shared_ptr item, uint8_t count) { lootedItem = nullptr; } -void ProtocolGame::sendShop(std::shared_ptr npc) { +void ProtocolGame::sendShop(const std::shared_ptr &npc) { Benchmark brenchmark; NetworkMessage msg; msg.addByte(0x7A); @@ -5593,9 +5590,9 @@ void ProtocolGame::parseForgeEnter(NetworkMessage &msg) { // 0xBF -> 0 = fusion, 1 = transfer, 2 = dust to sliver, 3 = sliver to core, 4 = increase dust limit auto actionType = static_cast(msg.getByte()); bool convergence = msg.getByte(); - uint16_t firstItem = msg.get(); + auto firstItem = msg.get(); uint8_t tier = msg.getByte(); - uint16_t secondItem = msg.get(); + auto secondItem = msg.get(); bool usedCore = msg.getByte(); bool reduceTierLoss = msg.getByte(); if (actionType == ForgeAction_t::FUSION) { @@ -6072,7 +6069,7 @@ void ProtocolGame::sendMarketDetail(uint16_t itemId, uint8_t tier) { writeToOutputBuffer(msg); } -void ProtocolGame::sendTradeItemRequest(const std::string &traderName, std::shared_ptr item, bool ack) { +void ProtocolGame::sendTradeItemRequest(const std::string &traderName, const std::shared_ptr &item, bool ack) { NetworkMessage msg; if (ack) { @@ -6123,7 +6120,7 @@ void ProtocolGame::sendCloseContainer(uint8_t cid) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureTurn(std::shared_ptr creature, uint32_t stackPos) { +void ProtocolGame::sendCreatureTurn(const std::shared_ptr &creature, uint32_t stackPos) { if (!canSee(creature)) { return; } @@ -6139,7 +6136,7 @@ void ProtocolGame::sendCreatureTurn(std::shared_ptr creature, uint32_t writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text, const Position* pos /* = nullptr*/) { +void ProtocolGame::sendCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, const Position* pos /* = nullptr*/) { NetworkMessage msg; msg.addByte(0xAA); @@ -6175,7 +6172,7 @@ void ProtocolGame::sendCreatureSay(std::shared_ptr creature, SpeakClas writeToOutputBuffer(msg); } -void ProtocolGame::sendToChannel(std::shared_ptr creature, SpeakClasses type, const std::string &text, uint16_t channelId) { +void ProtocolGame::sendToChannel(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, uint16_t channelId) { NetworkMessage msg; msg.addByte(0xAA); @@ -6217,7 +6214,7 @@ void ProtocolGame::sendToChannel(std::shared_ptr creature, SpeakClasse writeToOutputBuffer(msg); } -void ProtocolGame::sendPrivateMessage(std::shared_ptr speaker, SpeakClasses type, const std::string &text) { +void ProtocolGame::sendPrivateMessage(const std::shared_ptr &speaker, SpeakClasses type, const std::string &text) { NetworkMessage msg; msg.addByte(0xAA); static uint32_t statementId = 0; @@ -6252,7 +6249,7 @@ void ProtocolGame::sendCancelTarget() { writeToOutputBuffer(msg); } -void ProtocolGame::sendChangeSpeed(std::shared_ptr creature, uint16_t speed) { +void ProtocolGame::sendChangeSpeed(const std::shared_ptr &creature, uint16_t speed) { NetworkMessage msg; msg.addByte(0x8F); msg.add(creature->getID()); @@ -6392,7 +6389,7 @@ void ProtocolGame::removeMagicEffect(const Position &pos, uint16_t type) { writeToOutputBuffer(msg); } -void ProtocolGame::sendCreatureHealth(std::shared_ptr creature) { +void ProtocolGame::sendCreatureHealth(const std::shared_ptr &creature) { if (creature->isHealthHidden()) { return; } @@ -6409,7 +6406,7 @@ void ProtocolGame::sendCreatureHealth(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureUpdate(std::shared_ptr target) { +void ProtocolGame::sendPartyCreatureUpdate(const std::shared_ptr &target) { if (!player || oldProtocol) { return; } @@ -6427,7 +6424,7 @@ void ProtocolGame::sendPartyCreatureUpdate(std::shared_ptr target) { writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureShield(std::shared_ptr target) { +void ProtocolGame::sendPartyCreatureShield(const std::shared_ptr &target) { uint32_t cid = target->getID(); if (!knownCreatureSet.contains(cid)) { sendPartyCreatureUpdate(target); @@ -6441,7 +6438,7 @@ void ProtocolGame::sendPartyCreatureShield(std::shared_ptr target) { writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureSkull(std::shared_ptr target) { +void ProtocolGame::sendPartyCreatureSkull(const std::shared_ptr &target) { if (g_game().getWorldType() != WORLD_TYPE_PVP) { return; } @@ -6459,7 +6456,7 @@ void ProtocolGame::sendPartyCreatureSkull(std::shared_ptr target) { writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureHealth(std::shared_ptr target, uint8_t healthPercent) { +void ProtocolGame::sendPartyCreatureHealth(const std::shared_ptr &target, uint8_t healthPercent) { uint32_t cid = target->getID(); if (!knownCreatureSet.contains(cid)) { sendPartyCreatureUpdate(target); @@ -6473,7 +6470,7 @@ void ProtocolGame::sendPartyCreatureHealth(std::shared_ptr target, uin writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyPlayerMana(std::shared_ptr target, uint8_t manaPercent) { +void ProtocolGame::sendPartyPlayerMana(const std::shared_ptr &target, uint8_t manaPercent) { uint32_t cid = target->getID(); if (!knownCreatureSet.contains(cid)) { sendPartyCreatureUpdate(target); @@ -6491,7 +6488,7 @@ void ProtocolGame::sendPartyPlayerMana(std::shared_ptr target, uint8_t m writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyCreatureShowStatus(std::shared_ptr target, bool showStatus) { +void ProtocolGame::sendPartyCreatureShowStatus(const std::shared_ptr &target, bool showStatus) { uint32_t cid = target->getID(); if (!knownCreatureSet.contains(cid)) { sendPartyCreatureUpdate(target); @@ -6509,7 +6506,7 @@ void ProtocolGame::sendPartyCreatureShowStatus(std::shared_ptr target, writeToOutputBuffer(msg); } -void ProtocolGame::sendPartyPlayerVocation(std::shared_ptr target) { +void ProtocolGame::sendPartyPlayerVocation(const std::shared_ptr &target) { if (!target) { return; } @@ -6532,7 +6529,7 @@ void ProtocolGame::sendPartyPlayerVocation(std::shared_ptr target) { writeToOutputBuffer(msg); } -void ProtocolGame::sendPlayerVocation(std::shared_ptr target) { +void ProtocolGame::sendPlayerVocation(const std::shared_ptr &target) { if (!player || !target || oldProtocol) { return; } @@ -6561,7 +6558,7 @@ void ProtocolGame::sendMapDescription(const Position &pos) { writeToOutputBuffer(msg); } -void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, std::shared_ptr item) { +void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, const std::shared_ptr &item) { if (!canSee(pos)) { return; } @@ -6574,7 +6571,7 @@ void ProtocolGame::sendAddTileItem(const Position &pos, uint32_t stackpos, std:: writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTileItem(const Position &pos, uint32_t stackpos, std::shared_ptr item) { +void ProtocolGame::sendUpdateTileItem(const Position &pos, uint32_t stackpos, const std::shared_ptr &item) { if (!canSee(pos)) { return; } @@ -6597,7 +6594,7 @@ void ProtocolGame::sendRemoveTileThing(const Position &pos, uint32_t stackpos) { writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTileCreature(const Position &pos, uint32_t stackpos, const std::shared_ptr creature) { +void ProtocolGame::sendUpdateTileCreature(const Position &pos, uint32_t stackpos, const std::shared_ptr &creature) { if (!canSee(pos)) { return; } @@ -6614,7 +6611,7 @@ void ProtocolGame::sendUpdateTileCreature(const Position &pos, uint32_t stackpos writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateTile(std::shared_ptr tile, const Position &pos) { +void ProtocolGame::sendUpdateTile(const std::shared_ptr &tile, const Position &pos) { if (!canSee(pos)) { return; } @@ -6672,7 +6669,7 @@ void ProtocolGame::sendAllowBugReport() { writeToOutputBuffer(msg); } -void ProtocolGame::sendAddCreature(std::shared_ptr creature, const Position &pos, int32_t stackpos, bool isLogin) { +void ProtocolGame::sendAddCreature(const std::shared_ptr &creature, const Position &pos, int32_t stackpos, bool isLogin) { if (!canSee(pos)) { return; } @@ -6827,7 +6824,7 @@ void ProtocolGame::sendAddCreature(std::shared_ptr creature, const Pos } } -void ProtocolGame::sendMoveCreature(std::shared_ptr creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { +void ProtocolGame::sendMoveCreature(const std::shared_ptr &creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { if (creature == player) { if (oldStackPos >= 10) { sendMapDescription(newPos); @@ -6889,7 +6886,7 @@ void ProtocolGame::sendMoveCreature(std::shared_ptr creature, const Po } } -void ProtocolGame::sendInventoryItem(Slots_t slot, std::shared_ptr item) { +void ProtocolGame::sendInventoryItem(Slots_t slot, const std::shared_ptr &item) { NetworkMessage msg; if (item) { msg.addByte(0x78); @@ -6931,7 +6928,7 @@ void ProtocolGame::sendInventoryIds() { writeToOutputBuffer(msg); } -void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr item) { +void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &item) { NetworkMessage msg; msg.addByte(0x70); msg.addByte(cid); @@ -6940,7 +6937,7 @@ void ProtocolGame::sendAddContainerItem(uint8_t cid, uint16_t slot, std::shared_ writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr item) { +void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &item) { NetworkMessage msg; msg.addByte(0x71); msg.addByte(cid); @@ -6949,7 +6946,7 @@ void ProtocolGame::sendUpdateContainerItem(uint8_t cid, uint16_t slot, std::shar writeToOutputBuffer(msg); } -void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr lastItem) { +void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &lastItem) { NetworkMessage msg; msg.addByte(0x72); msg.addByte(cid); @@ -6962,7 +6959,7 @@ void ProtocolGame::sendRemoveContainerItem(uint8_t cid, uint16_t slot, std::shar writeToOutputBuffer(msg); } -void ProtocolGame::sendTextWindow(uint32_t windowTextId, std::shared_ptr item, uint16_t maxlen, bool canWrite) { +void ProtocolGame::sendTextWindow(uint32_t windowTextId, const std::shared_ptr &item, uint16_t maxlen, bool canWrite) { NetworkMessage msg; msg.addByte(0x96); msg.add(windowTextId); @@ -7226,7 +7223,7 @@ void ProtocolGame::sendOutfitWindow() { writeToOutputBuffer(msg); } -void ProtocolGame::sendPodiumWindow(std::shared_ptr podium, const Position &position, uint16_t itemId, uint8_t stackpos) { +void ProtocolGame::sendPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos) { if (!podium || oldProtocol) { g_logger().error("[{}] item is nullptr", __FUNCTION__); return; @@ -7608,7 +7605,7 @@ void ProtocolGame::sendModalWindow(const ModalWindow &modalWindow) { } ////////////// Add common messages -void ProtocolGame::AddCreature(NetworkMessage &msg, std::shared_ptr creature, bool known, uint32_t remove) { +void ProtocolGame::AddCreature(NetworkMessage &msg, const std::shared_ptr &creature, bool known, uint32_t remove) { CreatureType_t creatureType = creature->getType(); std::shared_ptr otherPlayer = creature->getPlayer(); @@ -7791,7 +7788,7 @@ void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) { if (oldProtocol) { for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; ++i) { - skills_t skill = static_cast(i); + auto skill = static_cast(i); msg.add(std::min(player->getSkillLevel(skill), std::numeric_limits::max())); msg.add(player->getBaseSkill(skill)); msg.addByte(std::min(100, static_cast(player->getSkillPercent(skill)))); @@ -7803,7 +7800,7 @@ void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) { msg.add(player->getMagicLevelPercent() * 100); for (uint8_t i = SKILL_FIRST; i <= SKILL_FISHING; ++i) { - skills_t skill = static_cast(i); + auto skill = static_cast(i); msg.add(std::min(player->getSkillLevel(skill), std::numeric_limits::max())); msg.add(player->getBaseSkill(skill)); msg.add(player->getLoyaltySkill(skill)); @@ -7815,7 +7812,7 @@ void ProtocolGame::AddPlayerSkills(NetworkMessage &msg) { if (!oldProtocol && (i == SKILL_LIFE_LEECH_CHANCE || i == SKILL_MANA_LEECH_CHANCE)) { continue; } - skills_t skill = static_cast(i); + auto skill = static_cast(i); msg.add(std::min(player->getSkillLevel(skill), std::numeric_limits::max())); msg.add(player->getBaseSkill(skill)); } @@ -7880,7 +7877,7 @@ void ProtocolGame::addImbuementInfo(NetworkMessage &msg, uint16_t imbuementId) c msg.add(baseImbuement->protectionPrice); } -void ProtocolGame::openImbuementWindow(std::shared_ptr item) { +void ProtocolGame::openImbuementWindow(const std::shared_ptr &item) { if (!item || item->isRemoved()) { return; } @@ -7947,7 +7944,7 @@ void ProtocolGame::sendMessageDialog(const std::string &message) { writeToOutputBuffer(msg); } -void ProtocolGame::sendImbuementResult(const std::string message) { +void ProtocolGame::sendImbuementResult(const std::string &message) { NetworkMessage msg; msg.addByte(0xED); msg.addByte(0x01); @@ -7979,7 +7976,7 @@ void ProtocolGame::sendSpecialContainersAvailable() { writeToOutputBuffer(msg); } -void ProtocolGame::updatePartyTrackerAnalyzer(const std::shared_ptr party) { +void ProtocolGame::updatePartyTrackerAnalyzer(const std::shared_ptr &party) { if (oldProtocol || !player || !party || !party->getLeader()) { return; } @@ -8019,7 +8016,7 @@ void ProtocolGame::updatePartyTrackerAnalyzer(const std::shared_ptr party writeToOutputBuffer(msg); } -void ProtocolGame::AddCreatureLight(NetworkMessage &msg, std::shared_ptr creature) { +void ProtocolGame::AddCreatureLight(NetworkMessage &msg, const std::shared_ptr &creature) { LightInfo lightInfo = creature->getCreatureLight(); msg.addByte(0x8D); @@ -8039,7 +8036,7 @@ void ProtocolGame::RemoveTileThing(NetworkMessage &msg, const Position &pos, uin msg.addByte(static_cast(stackpos)); } -void ProtocolGame::sendKillTrackerUpdate(std::shared_ptr corpse, const std::string &name, const Outfit_t creatureOutfit) { +void ProtocolGame::sendKillTrackerUpdate(const std::shared_ptr &corpse, const std::string &name, const Outfit_t creatureOutfit) { if (oldProtocol) { return; } @@ -8066,7 +8063,7 @@ void ProtocolGame::sendKillTrackerUpdate(std::shared_ptr corpse, cons writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateSupplyTracker(std::shared_ptr item) { +void ProtocolGame::sendUpdateSupplyTracker(const std::shared_ptr &item) { if (oldProtocol || !player || !item) { return; } @@ -8101,7 +8098,7 @@ void ProtocolGame::sendUpdateImpactTracker(CombatType_t type, int32_t amount) { writeToOutputBuffer(msg); } -void ProtocolGame::sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target) { +void ProtocolGame::sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, const std::string &target) { if (!player || oldProtocol) { return; } @@ -8190,7 +8187,7 @@ void ProtocolGame::sendTaskHuntingData(const std::unique_ptr &s writeToOutputBuffer(msg); } -void ProtocolGame::MoveUpCreature(NetworkMessage &msg, std::shared_ptr creature, const Position &newPos, const Position &oldPos) { +void ProtocolGame::MoveUpCreature(NetworkMessage &msg, const std::shared_ptr &creature, const Position &newPos, const Position &oldPos) { if (creature != player) { return; } @@ -8234,7 +8231,7 @@ void ProtocolGame::MoveUpCreature(NetworkMessage &msg, std::shared_ptr GetMapDescription(oldPos.x - MAP_MAX_CLIENT_VIEW_PORT_X, oldPos.y - MAP_MAX_CLIENT_VIEW_PORT_Y, newPos.z, (MAP_MAX_CLIENT_VIEW_PORT_X + 1) * 2, 1, msg); } -void ProtocolGame::MoveDownCreature(NetworkMessage &msg, std::shared_ptr creature, const Position &newPos, const Position &oldPos) { +void ProtocolGame::MoveDownCreature(NetworkMessage &msg, const std::shared_ptr &creature, const Position &newPos, const Position &oldPos) { if (creature != player) { return; } @@ -8353,7 +8350,7 @@ void ProtocolGame::parseInventoryImbuements(NetworkMessage &msg) { g_game().playerRequestInventoryImbuements(player->getID(), isTrackerOpen); } -void ProtocolGame::sendInventoryImbuements(const std::map> items) { +void ProtocolGame::sendInventoryImbuements(const std::map> &items) { if (oldProtocol) { return; } @@ -8446,7 +8443,7 @@ void ProtocolGame::sendItemsPrice() { writeToOutputBuffer(msg); } -void ProtocolGame::reloadCreature(std::shared_ptr creature) { +void ProtocolGame::reloadCreature(const std::shared_ptr &creature) { if (!creature || !canSee(creature)) { return; } @@ -8508,11 +8505,11 @@ void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) { return; } - Supply_Stash_Actions_t action = static_cast(msg.getByte()); + auto action = static_cast(msg.getByte()); switch (action) { case SUPPLY_STASH_ACTION_STOW_ITEM: { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); uint32_t count = msg.getByte(); g_game().playerStowItem(player->getID(), pos, itemId, stackpos, count, false); @@ -8520,21 +8517,21 @@ void ProtocolGame::parseStashWithdraw(NetworkMessage &msg) { } case SUPPLY_STASH_ACTION_STOW_CONTAINER: { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerStowItem(player->getID(), pos, itemId, stackpos, 0, false); break; } case SUPPLY_STASH_ACTION_STOW_STACK: { Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerStowItem(player->getID(), pos, itemId, stackpos, 0, true); break; } case SUPPLY_STASH_ACTION_WITHDRAW: { - uint16_t itemId = msg.get(); - uint32_t count = msg.get(); + auto itemId = msg.get(); + auto count = msg.get(); uint8_t stackpos = msg.getByte(); g_game().playerStashWithdraw(player->getID(), itemId, count, stackpos); break; @@ -8645,7 +8642,7 @@ void ProtocolGame::parseDepotSearchItemRequest(NetworkMessage &msg) { return; } - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t itemTier = 0; if (Item::items[itemId].upgradeClassification > 0) { itemTier = msg.getByte(); @@ -8659,7 +8656,7 @@ void ProtocolGame::parseRetrieveDepotSearch(NetworkMessage &msg) { return; } - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t itemTier = 0; if (Item::items[itemId].upgradeClassification > 0) { itemTier = msg.getByte(); @@ -8678,7 +8675,7 @@ void ProtocolGame::parseOpenParentContainer(NetworkMessage &msg) { g_game().playerRequestOpenContainerFromDepotSearch(player->getID(), pos); } -void ProtocolGame::sendUpdateCreature(std::shared_ptr creature) { +void ProtocolGame::sendUpdateCreature(const std::shared_ptr &creature) { if (oldProtocol || !creature || !player) { return; } @@ -8705,7 +8702,7 @@ void ProtocolGame::sendUpdateCreature(std::shared_ptr creature) { writeToOutputBuffer(msg); } -void ProtocolGame::getForgeInfoMap(std::shared_ptr item, std::map> &itemsMap) const { +void ProtocolGame::getForgeInfoMap(const std::shared_ptr &item, std::map> &itemsMap) const { std::map itemInfo; itemInfo.insert({ item->getTier(), item->getItemCount() }); auto [first, inserted] = itemsMap.try_emplace(item->getID(), itemInfo); @@ -8725,7 +8722,7 @@ void ProtocolGame::sendForgeSkillStats(NetworkMessage &msg) const { std::vector slots { CONST_SLOT_LEFT, CONST_SLOT_ARMOR, CONST_SLOT_HEAD, CONST_SLOT_LEGS }; for (const auto &slot : slots) { double_t skill = 0; - if (std::shared_ptr item = player->getInventoryItem(slot); item) { + if (const auto item = player->getInventoryItem(slot); item) { const ItemType &it = Item::items[item->getID()]; if (it.isWeapon()) { skill = item->getFatalChance() * 100; @@ -8961,7 +8958,7 @@ void ProtocolGame::parseBosstiarySlot(NetworkMessage &msg) { } uint8_t slotBossId = msg.getByte(); - uint32_t selectedBossId = msg.get(); + auto selectedBossId = msg.get(); g_game().playerBosstiarySlot(player->getID(), slotBossId, selectedBossId); } @@ -9004,7 +9001,7 @@ void ProtocolGame::sendPodiumDetails(NetworkMessage &msg, const std::vector podium, const Position &position, uint16_t itemId, uint8_t stackPos) { +void ProtocolGame::sendMonsterPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackPos) { if (!podium || oldProtocol) { g_logger().error("[{}] item is nullptr", __FUNCTION__); return; @@ -9069,9 +9066,9 @@ void ProtocolGame::parseSetMonsterPodium(NetworkMessage &msg) const { } // For some reason the cip sends uint32_t, but we use uint16_t, so let's just ignore that - uint16_t monsterRaceId = (uint16_t)msg.get(); + auto monsterRaceId = (uint16_t)msg.get(); Position pos = msg.getPosition(); - uint16_t itemId = msg.get(); + auto itemId = msg.get(); uint8_t stackpos = msg.getByte(); uint8_t direction = msg.getByte(); uint8_t podiumVisible = msg.getByte(); diff --git a/src/server/network/protocol/protocolgame.hpp b/src/server/network/protocol/protocolgame.hpp index 2a5fde6c6c4..174fd9cba7c 100644 --- a/src/server/network/protocol/protocolgame.hpp +++ b/src/server/network/protocol/protocolgame.hpp @@ -25,7 +25,6 @@ class House; class Container; class Tile; class Connection; -class Quest; class ProtocolGame; class PreySlot; class TaskHuntingSlot; @@ -46,7 +45,7 @@ struct TextMessage { MessageClasses type = MESSAGE_STATUS; std::string text; Position position; - uint16_t channelId; + uint16_t channelId {}; struct { int32_t value = 0; @@ -66,13 +65,13 @@ class ProtocolGame final : public Protocol { return "gameworld protocol"; } - explicit ProtocolGame(Connection_ptr initConnection); + explicit ProtocolGame(const Connection_ptr &initConnection); void login(const std::string &name, uint32_t accnumber, OperatingSystem_t operatingSystem); void logout(bool displayEffect, bool forced); - void AddItem(NetworkMessage &msg, std::shared_ptr item); - void AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier); + void AddItem(NetworkMessage &msg, const std::shared_ptr &item); + void AddItem(NetworkMessage &msg, uint16_t id, uint8_t count, uint8_t tier) const; uint16_t getVersion() const { return version; @@ -91,7 +90,7 @@ class ProtocolGame final : public Protocol { void checkCreatureAsKnown(uint32_t id, bool &known, uint32_t &removedKnown); bool canSee(int32_t x, int32_t y, int32_t z) const; - bool canSee(std::shared_ptr) const; + bool canSee(const std::shared_ptr &) const; bool canSee(const Position &pos) const; // we have all the parse methods @@ -129,7 +128,7 @@ class ProtocolGame final : public Protocol { void sendSessionEndInformation(SessionEndInformations information); - void sendItemInspection(uint16_t itemId, uint8_t itemCount, std::shared_ptr item, bool cyclopedia); + void sendItemInspection(uint16_t itemId, uint8_t itemCount, const std::shared_ptr &item, bool cyclopedia); void parseInspectionObject(NetworkMessage &msg); void parseFriendSystemAction(NetworkMessage &msg); @@ -162,7 +161,6 @@ class ProtocolGame final : public Protocol { void parseSendBuyCharmRune(NetworkMessage &msg); void parseBestiarysendMonsterData(NetworkMessage &msg); void parseCyclopediaMonsterTracker(NetworkMessage &msg); - void parseObjectInfo(NetworkMessage &msg); void parseTeleport(NetworkMessage &msg); void parseThrow(NetworkMessage &msg); @@ -240,14 +238,14 @@ class ProtocolGame final : public Protocol { void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers); void sendOpenPrivateChannel(const std::string &receiver); void sendExperienceTracker(int64_t rawExp, int64_t finalExp); - void sendToChannel(std::shared_ptr creature, SpeakClasses type, const std::string &text, uint16_t channelId); - void sendPrivateMessage(std::shared_ptr speaker, SpeakClasses type, const std::string &text); + void sendToChannel(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, uint16_t channelId); + void sendPrivateMessage(const std::shared_ptr &speaker, SpeakClasses type, const std::string &text); void sendIcons(const std::unordered_set &iconSet, const IconBakragore iconBakragore); void sendIconBakragore(const IconBakragore icon); void sendFYIBox(const std::string &message); - void openImbuementWindow(std::shared_ptr item); - void sendImbuementResult(const std::string message); + void openImbuementWindow(const std::shared_ptr &item); + void sendImbuementResult(const std::string &message); void closeImbuementWindow(); void sendItemsPrice(); @@ -255,18 +253,11 @@ class ProtocolGame final : public Protocol { // Forge System void sendForgingData(); void sendOpenForge(); - void sendForgeError(const ReturnValue returnValue); + void sendForgeError(ReturnValue returnValue); void closeForgeWindow(); void parseForgeEnter(NetworkMessage &msg); void parseForgeBrowseHistory(NetworkMessage &msg); - void sendForgeFusionItem( - uint16_t itemId, - uint8_t tier, - bool success, - uint8_t bonus, - uint8_t coreCount, - bool convergence - ); + void sendForgeResult(ForgeAction_t actionType, uint16_t leftItemId, uint8_t leftTier, uint16_t rightItemId, uint8_t rightTier, bool success, uint8_t bonus, uint8_t coreCount, bool convergence); void sendForgeHistory(uint8_t page); void sendForgeSkillStats(NetworkMessage &msg) const; @@ -276,7 +267,7 @@ class ProtocolGame final : public Protocol { void parseSendBosstiarySlots(); void parseBosstiarySlot(NetworkMessage &msg); void sendPodiumDetails(NetworkMessage &msg, const std::vector &toSendMonsters, bool isBoss) const; - void sendMonsterPodiumWindow(std::shared_ptr podium, const Position &position, uint16_t itemId, uint8_t stackPos); + void sendMonsterPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackPos); void parseSetMonsterPodium(NetworkMessage &msg) const; void sendBosstiaryCooldownTimer(); void sendBosstiaryEntryChanged(uint32_t bossid); @@ -286,28 +277,28 @@ class ProtocolGame final : public Protocol { void sendMagicEffect(const Position &pos, uint16_t type); void removeMagicEffect(const Position &pos, uint16_t type); void sendRestingStatus(uint8_t protection); - void sendCreatureHealth(std::shared_ptr creature); - void sendPartyCreatureUpdate(std::shared_ptr target); - void sendPartyCreatureShield(std::shared_ptr target); - void sendPartyCreatureSkull(std::shared_ptr target); - void sendPartyCreatureHealth(std::shared_ptr target, uint8_t healthPercent); - void sendPartyPlayerMana(std::shared_ptr target, uint8_t manaPercent); - void sendPartyCreatureShowStatus(std::shared_ptr target, bool showStatus); - void sendPartyPlayerVocation(std::shared_ptr target); - void sendPlayerVocation(std::shared_ptr target); + void sendCreatureHealth(const std::shared_ptr &creature); + void sendPartyCreatureUpdate(const std::shared_ptr &target); + void sendPartyCreatureShield(const std::shared_ptr &target); + void sendPartyCreatureSkull(const std::shared_ptr &target); + void sendPartyCreatureHealth(const std::shared_ptr &target, uint8_t healthPercent); + void sendPartyPlayerMana(const std::shared_ptr &target, uint8_t manaPercent); + void sendPartyCreatureShowStatus(const std::shared_ptr &target, bool showStatus); + void sendPartyPlayerVocation(const std::shared_ptr &target); + void sendPlayerVocation(const std::shared_ptr &target); void sendSkills(); void sendPing(); void sendPingBack(); - void sendCreatureTurn(std::shared_ptr creature, uint32_t stackpos); - void sendCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr); + void sendCreatureTurn(const std::shared_ptr &creature, uint32_t stackpos); + void sendCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr); // Unjust Panel void sendUnjustifiedPoints(const uint8_t &dayProgress, const uint8_t &dayLeft, const uint8_t &weekProgress, const uint8_t &weekLeft, const uint8_t &monthProgress, const uint8_t &monthLeft, const uint8_t &skullDuration); void sendCancelWalk(); - void sendChangeSpeed(std::shared_ptr creature, uint16_t speed); + void sendChangeSpeed(const std::shared_ptr &creature, uint16_t speed); void sendCancelTarget(); - void sendCreatureOutfit(std::shared_ptr creature, const Outfit_t &outfit); + void sendCreatureOutfit(const std::shared_ptr &creature, const Outfit_t &outfit); void sendStats(); void sendBasicData(); void sendTextMessage(const TextMessage &message); @@ -322,7 +313,7 @@ class ProtocolGame final : public Protocol { void sendCyclopediaCharacterCombatStats(); void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries); void sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries); - void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, std::vector> achievementsUnlocked); + void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked); void sendCyclopediaCharacterItemSummary(const ItemsTierCountList &inventoryItems, const ItemsTierCountList &storeInboxItems, const StashItemList &supplyStashItems, const ItemsTierCountList &depotBoxItems, const ItemsTierCountList &inboxItems); void sendCyclopediaCharacterOutfitsMounts(); void sendCyclopediaCharacterStoreSummary(); @@ -330,13 +321,13 @@ class ProtocolGame final : public Protocol { void sendCyclopediaCharacterBadges(); void sendCyclopediaCharacterTitles(); - void sendCreatureWalkthrough(std::shared_ptr creature, bool walkthrough); - void sendCreatureShield(std::shared_ptr creature); - void sendCreatureEmblem(std::shared_ptr creature); - void sendCreatureSkull(std::shared_ptr creature); - void sendCreatureType(std::shared_ptr creature, uint8_t creatureType); + void sendCreatureWalkthrough(const std::shared_ptr &creature, bool walkthrough); + void sendCreatureShield(const std::shared_ptr &creature); + void sendCreatureEmblem(const std::shared_ptr &creature); + void sendCreatureSkull(const std::shared_ptr &creature); + void sendCreatureType(const std::shared_ptr &creature, uint8_t creatureType); - void sendShop(std::shared_ptr npc); + void sendShop(const std::shared_ptr &npc); void sendCloseShop(); void sendClientCheck(); void sendGameNews(); @@ -352,15 +343,15 @@ class ProtocolGame final : public Protocol { void sendMarketCancelOffer(const MarketOfferEx &offer); void sendMarketBrowseOwnHistory(const HistoryMarketOfferList &buyOffers, const HistoryMarketOfferList &sellOffers); void sendMarketDetail(uint16_t itemId, uint8_t tier); - void sendTradeItemRequest(const std::string &traderName, std::shared_ptr item, bool ack); + void sendTradeItemRequest(const std::string &traderName, const std::shared_ptr &item, bool ack); void sendCloseTrade(); - void updatePartyTrackerAnalyzer(const std::shared_ptr party); + void updatePartyTrackerAnalyzer(const std::shared_ptr &party); void sendTextWindow(uint32_t windowTextId, uint32_t itemId, const std::string &text); - void sendTextWindow(uint32_t windowTextId, std::shared_ptr item, uint16_t maxlen, bool canWrite); + void sendTextWindow(uint32_t windowTextId, const std::shared_ptr &item, uint16_t maxlen, bool canWrite); void sendHouseWindow(uint32_t windowTextId, const std::string &text); void sendOutfitWindow(); - void sendPodiumWindow(std::shared_ptr podium, const Position &position, uint16_t itemId, uint8_t stackpos); + void sendPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos); void sendUpdatedVIPStatus(uint32_t guid, VipStatus_t newStatus); void sendVIP(uint32_t guid, const std::string &name, const std::string &description, uint32_t icon, bool notify, VipStatus_t status); @@ -371,13 +362,13 @@ class ProtocolGame final : public Protocol { void sendFightModes(); - void sendCreatureLight(std::shared_ptr creature); - void sendCreatureIcon(std::shared_ptr creature); - void sendUpdateCreature(std::shared_ptr creature); + void sendCreatureLight(const std::shared_ptr &creature); + void sendCreatureIcon(const std::shared_ptr &creature); + void sendUpdateCreature(const std::shared_ptr &creature); void sendWorldLight(const LightInfo &lightInfo); void sendTibiaTime(int32_t time); - void sendCreatureSquare(std::shared_ptr creature, SquareColor_t color); + void sendCreatureSquare(const std::shared_ptr &creature, SquareColor_t color); void sendSpellCooldown(uint16_t spellId, uint32_t time); void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time); @@ -392,46 +383,46 @@ class ProtocolGame final : public Protocol { // tiles void sendMapDescription(const Position &pos); - void sendAddTileItem(const Position &pos, uint32_t stackpos, std::shared_ptr item); - void sendUpdateTileItem(const Position &pos, uint32_t stackpos, std::shared_ptr item); + void sendAddTileItem(const Position &pos, uint32_t stackpos, const std::shared_ptr &item); + void sendUpdateTileItem(const Position &pos, uint32_t stackpos, const std::shared_ptr &item); void sendRemoveTileThing(const Position &pos, uint32_t stackpos); - void sendUpdateTileCreature(const Position &pos, uint32_t stackpos, const std::shared_ptr creature); - void sendUpdateTile(std::shared_ptr tile, const Position &pos); + void sendUpdateTileCreature(const Position &pos, uint32_t stackpos, const std::shared_ptr &creature); + void sendUpdateTile(const std::shared_ptr &tile, const Position &pos); - void sendAddCreature(std::shared_ptr creature, const Position &pos, int32_t stackpos, bool isLogin); - void sendMoveCreature(std::shared_ptr creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport); + void sendAddCreature(const std::shared_ptr &creature, const Position &pos, int32_t stackpos, bool isLogin); + void sendMoveCreature(const std::shared_ptr &creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport); // containers - void sendAddContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr item); - void sendUpdateContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr item); - void sendRemoveContainerItem(uint8_t cid, uint16_t slot, std::shared_ptr lastItem); + void sendAddContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &item); + void sendUpdateContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &item); + void sendRemoveContainerItem(uint8_t cid, uint16_t slot, const std::shared_ptr &lastItem); - void sendContainer(uint8_t cid, std::shared_ptr container, bool hasParent, uint16_t firstIndex); + void sendContainer(uint8_t cid, const std::shared_ptr &container, bool hasParent, uint16_t firstIndex); void sendCloseContainer(uint8_t cid); // quickloot void sendLootContainers(); - void sendLootStats(std::shared_ptr item, uint8_t count); + void sendLootStats(const std::shared_ptr &item, uint8_t count); // inventory - void sendInventoryItem(Slots_t slot, std::shared_ptr item); + void sendInventoryItem(Slots_t slot, const std::shared_ptr &item); void sendInventoryIds(); // messages void sendModalWindow(const ModalWindow &modalWindow); // analyzers - void sendKillTrackerUpdate(std::shared_ptr corpse, const std::string &name, const Outfit_t creatureOutfit); - void sendUpdateSupplyTracker(std::shared_ptr item); + void sendKillTrackerUpdate(const std::shared_ptr &corpse, const std::string &name, Outfit_t creatureOutfit); + void sendUpdateSupplyTracker(const std::shared_ptr &item); void sendUpdateImpactTracker(CombatType_t type, int32_t amount); - void sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, std::string target); + void sendUpdateInputAnalyzer(CombatType_t type, int32_t amount, const std::string &target); // Hotkey equip/dequip item void parseHotkeyEquip(NetworkMessage &msg); // Help functions // translate a tile to clientreadable format - void GetTileDescription(std::shared_ptr tile, NetworkMessage &msg); + void GetTileDescription(const std::shared_ptr &tile, NetworkMessage &msg); // translate a floor to clientreadable format void GetFloorDescription(NetworkMessage &msg, int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, int32_t offset, int32_t &skip); @@ -439,7 +430,7 @@ class ProtocolGame final : public Protocol { // translate a map area to clientreadable format void GetMapDescription(int32_t x, int32_t y, int32_t z, int32_t width, int32_t height, NetworkMessage &msg); - void AddCreature(NetworkMessage &msg, std::shared_ptr creature, bool known, uint32_t remove); + void AddCreature(NetworkMessage &msg, const std::shared_ptr &creature, bool known, uint32_t remove); void AddPlayerStats(NetworkMessage &msg); void AddOutfit(NetworkMessage &msg, const Outfit_t &outfit, bool addMount = true); void AddPlayerSkills(NetworkMessage &msg); @@ -447,15 +438,15 @@ class ProtocolGame final : public Protocol { void sendPremiumTrigger(); void sendMessageDialog(const std::string &message); void AddWorldLight(NetworkMessage &msg, LightInfo lightInfo); - void AddCreatureLight(NetworkMessage &msg, std::shared_ptr creature); + void AddCreatureLight(NetworkMessage &msg, const std::shared_ptr &creature); // tiles static void RemoveTileThing(NetworkMessage &msg, const Position &pos, uint32_t stackpos); void sendTaskHuntingData(const std::unique_ptr &slot); - void MoveUpCreature(NetworkMessage &msg, std::shared_ptr creature, const Position &newPos, const Position &oldPos); - void MoveDownCreature(NetworkMessage &msg, std::shared_ptr creature, const Position &newPos, const Position &oldPos); + void MoveUpCreature(NetworkMessage &msg, const std::shared_ptr &creature, const Position &newPos, const Position &oldPos); + void MoveDownCreature(NetworkMessage &msg, const std::shared_ptr &creature, const Position &newPos, const Position &oldPos); // shop void AddHiddenShopItem(NetworkMessage &msg); @@ -468,12 +459,12 @@ class ProtocolGame final : public Protocol { void sendFeatures(); void parseInventoryImbuements(NetworkMessage &msg); - void sendInventoryImbuements(const std::map> items); + void sendInventoryImbuements(const std::map> &items); // reloadCreature - void reloadCreature(std::shared_ptr creature); + void reloadCreature(const std::shared_ptr &creature); - void getForgeInfoMap(std::shared_ptr item, std::map> &itemsMap) const; + void getForgeInfoMap(const std::shared_ptr &item, std::map> &itemsMap) const; // Wheel void parseOpenWheel(NetworkMessage &msg); @@ -506,13 +497,12 @@ class ProtocolGame final : public Protocol { uint16_t otclientV8 = 0; bool isOTC = false; - void sendInventory(); void sendOpenStash(); void parseStashWithdraw(NetworkMessage &msg); void sendSpecialContainersAvailable(); void addBless(); void parsePacketDead(uint8_t recvbyte); - void addCreatureIcon(NetworkMessage &msg, std::shared_ptr creature); + void addCreatureIcon(NetworkMessage &msg, const std::shared_ptr &creature); void sendSingleSoundEffect(const Position &pos, SoundEffect_t id, SourceEffect_t source); void sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundId, SourceEffect_t mainSource, SoundEffect_t secondarySoundId, SourceEffect_t secondarySource); diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index d6e9e3cb9f1..f1a9ec31acf 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -107,7 +107,7 @@ void ProtocolLogin::onRecvFirstMessage(NetworkMessage &msg) { msg.skipBytes(2); // client OS - uint16_t version = msg.get(); + auto version = msg.get(); // Old protocol support oldProtocol = version == 1100; diff --git a/src/server/network/protocol/protocollogin.hpp b/src/server/network/protocol/protocollogin.hpp index 6652a85625e..ebddac68c14 100644 --- a/src/server/network/protocol/protocollogin.hpp +++ b/src/server/network/protocol/protocollogin.hpp @@ -24,10 +24,10 @@ class ProtocolLogin : public Protocol { return "login protocol"; } - explicit ProtocolLogin(Connection_ptr loginConnection) : + explicit ProtocolLogin(const Connection_ptr &loginConnection) : Protocol(loginConnection) { } - void onRecvFirstMessage(NetworkMessage &msg); + void onRecvFirstMessage(NetworkMessage &msg) override; private: void disconnectClient(const std::string &message); diff --git a/src/server/network/protocol/protocolstatus.cpp b/src/server/network/protocol/protocolstatus.cpp index 15a3f74be07..71b835e7501 100644 --- a/src/server/network/protocol/protocolstatus.cpp +++ b/src/server/network/protocol/protocolstatus.cpp @@ -55,7 +55,7 @@ void ProtocolStatus::onRecvFirstMessage(NetworkMessage &msg) { // Another ServerInfo protocol case 0x01: { - uint16_t requestedInfo = msg.get(); // only a Byte is necessary, though we could add new info here + auto requestedInfo = msg.get(); // only a Byte is necessary, though we could add new info here std::string characterName; if (requestedInfo & REQUEST_PLAYER_STATUS_INFO) { characterName = msg.getString(); diff --git a/src/server/network/protocol/protocolstatus.hpp b/src/server/network/protocol/protocolstatus.hpp index 78b03a74333..2902e7eea51 100644 --- a/src/server/network/protocol/protocolstatus.hpp +++ b/src/server/network/protocol/protocolstatus.hpp @@ -22,7 +22,7 @@ class ProtocolStatus final : public Protocol { return "status protocol"; } - explicit ProtocolStatus(Connection_ptr conn) : + explicit ProtocolStatus(const Connection_ptr &conn) : Protocol(conn) { } void onRecvFirstMessage(NetworkMessage &msg) override; diff --git a/src/server/network/webhook/webhook.cpp b/src/server/network/webhook/webhook.cpp index f80ff4e59b3..a617b114389 100644 --- a/src/server/network/webhook/webhook.cpp +++ b/src/server/network/webhook/webhook.cpp @@ -25,7 +25,7 @@ Webhook::Webhook(ThreadPool &threadPool) : headers = curl_slist_append(headers, "content-type: application/json"); headers = curl_slist_append(headers, "accept: application/json"); - if (headers == NULL) { + if (headers == nullptr) { g_logger().error("Failed to init curl, appending request headers failed"); return; } @@ -44,7 +44,7 @@ void Webhook::run() { ); } -void Webhook::sendPayload(const std::string &payload, std::string url) { +void Webhook::sendPayload(const std::string &payload, const std::string &url) { std::scoped_lock lock { taskLock }; webhooks.push_back(std::make_shared(payload, url)); } diff --git a/src/server/network/webhook/webhook.hpp b/src/server/network/webhook/webhook.hpp index bae62a64c35..4ce989099c1 100644 --- a/src/server/network/webhook/webhook.hpp +++ b/src/server/network/webhook/webhook.hpp @@ -30,7 +30,7 @@ class Webhook { void run(); - void sendPayload(const std::string &payload, std::string url); + void sendPayload(const std::string &payload, const std::string &url); void sendMessage(const std::string &title, const std::string &message, int color, std::string url = "", bool embed = true); void sendMessage(const std::string &message, std::string url = ""); diff --git a/src/utils/benchmark.hpp b/src/utils/benchmark.hpp index 961547efc94..39e4f1874ca 100644 --- a/src/utils/benchmark.hpp +++ b/src/utils/benchmark.hpp @@ -74,7 +74,7 @@ class Benchmark { } private: - int64_t time() const noexcept { + static int64_t time() noexcept { return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); } diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index f89b2c2f217..e802b1b65f3 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -25,7 +25,7 @@ void printXMLError(const std::string &where, const std::string &fileName, const uint32_t currentLine = 1; std::string line; - size_t offset = static_cast(result.offset); + auto offset = static_cast(result.offset); size_t lineOffsetPosition = 0; size_t index = 0; size_t bytes; @@ -187,7 +187,7 @@ std::string transformToSHA1(const std::string &input) { return std::string(hexstring, 40); } -uint16_t getStashSize(StashItemList itemList) { +uint16_t getStashSize(const StashItemList &itemList) { uint16_t size = 0; for (auto item : itemList) { size += ceil(item.second / (float_t)Item::items[item.first].stackSize); @@ -1073,7 +1073,7 @@ std::string getWeaponName(WeaponType_t weaponType) { case WEAPON_MISSILE: return "missile"; default: - return std::string(); + return {}; } } @@ -1551,7 +1551,7 @@ SpellGroup_t stringToSpellGroup(const std::string &value) { */ void capitalizeWords(std::string &source) { toLowerCaseString(source); - uint8_t size = (uint8_t)source.size(); + auto size = (uint8_t)source.size(); for (uint8_t i = 0; i < size; i++) { if (i == 0) { source[i] = (char)toupper(source[i]); @@ -1561,7 +1561,7 @@ void capitalizeWords(std::string &source) { } } -void capitalizeWordsIgnoringString(std::string &source, const std::string stringToIgnore) { +void capitalizeWordsIgnoringString(std::string &source, const std::string &stringToIgnore) { toLowerCaseString(source); auto size = static_cast(source.size()); auto indexFound = source.find(stringToIgnore); @@ -1586,7 +1586,6 @@ void consoleHandlerExit() { if (isatty(STDIN_FILENO)) { getchar(); } - return; } NameEval_t validateName(const std::string &name) { @@ -1607,7 +1606,7 @@ NameEval_t validateName(const std::string &name) { return INVALID_CHARACTER; } - for (std::string str : toks) { + for (const std::string &str : toks) { if (str.length() < 2) { return INVALID_TOKEN_LENGTH; } else if (std::find(prohibitedWords.begin(), prohibitedWords.end(), str) != prohibitedWords.end()) { // searching for prohibited words @@ -1677,7 +1676,7 @@ std::string getObjectCategoryName(ObjectCategory_t category) { case OBJECTCATEGORY_DEFAULT: return "Unassigned Loot"; default: - return std::string(); + return {}; } } diff --git a/src/utils/tools.hpp b/src/utils/tools.hpp index a4426a066a8..4803dfc393a 100644 --- a/src/utils/tools.hpp +++ b/src/utils/tools.hpp @@ -27,7 +27,7 @@ void printXMLError(const std::string &where, const std::string &fileName, const std::string transformToSHA1(const std::string &input); -uint16_t getStashSize(StashItemList itemList); +uint16_t getStashSize(const StashItemList &itemList); std::string generateToken(const std::string &secret, uint32_t ticks); @@ -60,7 +60,7 @@ int32_t uniform_random(int32_t minNumber, int32_t maxNumber); int32_t normal_random(int32_t minNumber, int32_t maxNumber); bool boolean_random(double probability = 0.5); -BedItemPart_t getBedPart(const std::string_view string); +BedItemPart_t getBedPart(std::string_view string); Direction getDirection(const std::string &string); Position getNextPosition(Direction direction, Position pos); @@ -138,7 +138,7 @@ const char* getReturnMessage(ReturnValue value); void sleep_for(uint64_t ms); void capitalizeWords(std::string &source); -void capitalizeWordsIgnoringString(std::string &source, const std::string stringToIgnore); +void capitalizeWordsIgnoringString(std::string &source, const std::string &stringToIgnore); void consoleHandlerExit(); NameEval_t validateName(const std::string &name); From 9956d7ae11435e19d6955dbf7a846ab25a3ce692 Mon Sep 17 00:00:00 2001 From: Beats Date: Wed, 31 Jul 2024 20:56:06 -0300 Subject: [PATCH 03/34] test --- src/game/scheduling/task.cpp | 24 ++++++++++++++++++++++++ src/game/scheduling/task.hpp | 22 ++++------------------ 2 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/game/scheduling/task.cpp b/src/game/scheduling/task.cpp index 758b86d9a3e..59fcff86715 100644 --- a/src/game/scheduling/task.cpp +++ b/src/game/scheduling/task.cpp @@ -16,6 +16,30 @@ std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0; +Task::Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, + const std::source_location& location) : + func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME()), + expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { + if (this->context.empty()) { + g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); + return; + } + + assert(!this->context.empty() && "Context cannot be empty!"); +} + +Task::Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle /* = false*/, bool log /*= true*/, + const std::source_location& location) : + func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME() + delay), delay(delay), + cycle(cycle), log(log) { + if (this->context.empty()) { + g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); + return; + } + + assert(!this->context.empty() && "Context cannot be empty!"); +} + bool Task::execute() const { metrics::task_latency measure(context); if (isCanceled()) { diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index 2508c1328aa..419298b4196 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -14,25 +14,11 @@ class Task { public: - Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, const std::source_location &location = std::source_location::current()) : - func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME()), - expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { - if (this->context.empty()) { - g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); - return; - } - assert(!this->context.empty() && "Context cannot be empty!"); - } + Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, + const std::source_location& location = std::source_location::current()); - Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true, const std::source_location &location = std::source_location::current()) : - func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME() + delay), delay(delay), - cycle(cycle), log(log) { - if (this->context.empty()) { - g_logger().error("[{}]: task context cannot be empty! Function: {}", __FUNCTION__, functionName); - return; - } - assert(!this->context.empty() && "Context cannot be empty!"); - } + Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true, + const std::source_location& location = std::source_location::current()); ~Task() = default; From 1a3e48badcf1e18b6b309f5cbe16b0ccf4683bd5 Mon Sep 17 00:00:00 2001 From: Beats Date: Thu, 1 Aug 2024 00:23:04 -0300 Subject: [PATCH 04/34] improve --- src/account/account.cpp | 4 +- src/account/account_repository_db.cpp | 16 ++--- src/creatures/appearance/mounts/mounts.hpp | 4 +- src/creatures/appearance/outfit/outfit.cpp | 2 +- src/creatures/combat/combat.cpp | 60 +++++++++--------- src/creatures/combat/condition.cpp | 72 +++++++++++----------- src/creatures/combat/condition.hpp | 24 ++++---- src/creatures/combat/spells.cpp | 50 +++++++-------- src/creatures/combat/spells.hpp | 18 +++--- src/creatures/creature.cpp | 5 +- src/game/scheduling/dispatcher.cpp | 8 +-- src/game/scheduling/dispatcher.hpp | 6 +- src/game/scheduling/task.cpp | 6 +- src/game/scheduling/task.hpp | 24 ++++---- src/map/mapcache.cpp | 3 +- 15 files changed, 147 insertions(+), 155 deletions(-) diff --git a/src/account/account.cpp b/src/account/account.cpp index af82a9ae62c..aa2ab0b070c 100644 --- a/src/account/account.cpp +++ b/src/account/account.cpp @@ -12,8 +12,6 @@ #include "account/account.hpp" #include "account/account_repository_db.hpp" -#include "config/configmanager.hpp" -#include "utils/definitions.hpp" #include "security/argon.hpp" #include "utils/tools.hpp" #include "lib/logging/log_with_spd_log.hpp" @@ -164,7 +162,7 @@ void Account::registerCoinTransaction(const uint8_t &transactionType, const uint [[nodiscard]] uint32_t Account::getID() const { return m_account.id; -}; +} std::string Account::getDescriptor() const { return m_descriptor; diff --git a/src/account/account_repository_db.cpp b/src/account/account_repository_db.cpp index b150a636a97..2d691020a95 100644 --- a/src/account/account_repository_db.cpp +++ b/src/account/account_repository_db.cpp @@ -25,13 +25,13 @@ AccountRepositoryDB::AccountRepositoryDB() : bool AccountRepositoryDB::loadByID(const uint32_t &id, AccountInfo &acc) { auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `id` = {}", id); return load(query, acc); -}; +} bool AccountRepositoryDB::loadByEmailOrName(bool oldProtocol, const std::string &emailOrName, AccountInfo &acc) { auto identifier = oldProtocol ? "name" : "email"; auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `{}` = {}", identifier, g_database().escapeString(emailOrName)); return load(query, acc); -}; +} bool AccountRepositoryDB::loadBySession(const std::string &sessionKey, AccountInfo &acc) { auto query = fmt::format( @@ -42,7 +42,7 @@ bool AccountRepositoryDB::loadBySession(const std::string &sessionKey, AccountIn g_database().escapeString(transformToSHA1(sessionKey)) ); return load(query, acc); -}; +} bool AccountRepositoryDB::save(const AccountInfo &accInfo) { bool successful = g_database().executeQuery( @@ -62,7 +62,7 @@ bool AccountRepositoryDB::save(const AccountInfo &accInfo) { } return successful; -}; +} bool AccountRepositoryDB::getPassword(const uint32_t &id, std::string &password) { auto result = g_database().storeQuery(fmt::format("SELECT * FROM `accounts` WHERE `id` = {}", id)); @@ -73,7 +73,7 @@ bool AccountRepositoryDB::getPassword(const uint32_t &id, std::string &password) password = result->getString("password"); return true; -}; +} bool AccountRepositoryDB::getCoins(const uint32_t &id, const uint8_t &type, uint32_t &coins) { if (coinTypeToColumn.find(type) == coinTypeToColumn.end()) { @@ -94,7 +94,7 @@ bool AccountRepositoryDB::getCoins(const uint32_t &id, const uint8_t &type, uint coins = result->getNumber(coinTypeToColumn.at(type)); return true; -}; +} bool AccountRepositoryDB::setCoins(const uint32_t &id, const uint8_t &type, const uint32_t &amount) { if (coinTypeToColumn.find(type) == coinTypeToColumn.end()) { @@ -114,7 +114,7 @@ bool AccountRepositoryDB::setCoins(const uint32_t &id, const uint8_t &type, cons } return successful; -}; +} bool AccountRepositoryDB::registerCoinsTransaction( const uint32_t &id, @@ -146,7 +146,7 @@ bool AccountRepositoryDB::registerCoinsTransaction( } return successful; -}; +} bool AccountRepositoryDB::loadAccountPlayers(AccountInfo &acc) { auto result = g_database().storeQuery( diff --git a/src/creatures/appearance/mounts/mounts.hpp b/src/creatures/appearance/mounts/mounts.hpp index ca4f969842a..d5e6c965bd2 100644 --- a/src/creatures/appearance/mounts/mounts.hpp +++ b/src/creatures/appearance/mounts/mounts.hpp @@ -30,10 +30,10 @@ class Mounts { std::shared_ptr getMountByName(const std::string &name); std::shared_ptr getMountByClientID(uint16_t clientId); - [[nodiscard]] const phmap::parallel_flat_hash_set> &getMounts() const { + [[nodiscard]] const phmap::flat_hash_set> &getMounts() const { return mounts; } private: - phmap::parallel_flat_hash_set> mounts; + phmap::flat_hash_set> mounts; }; diff --git a/src/creatures/appearance/outfit/outfit.cpp b/src/creatures/appearance/outfit/outfit.cpp index 251bf7bde35..697ed776c3d 100644 --- a/src/creatures/appearance/outfit/outfit.cpp +++ b/src/creatures/appearance/outfit/outfit.cpp @@ -34,7 +34,7 @@ bool Outfits::loadFromXml() { return false; } - for (auto outfitNode : doc.child("outfits").children()) { + for (const auto &outfitNode : doc.child("outfits").children()) { pugi::xml_attribute attr; if ((attr = outfitNode.attribute("enabled")) && !attr.as_bool()) { continue; diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 1d023ae1c1b..a2eb8411ce8 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -323,15 +323,15 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const } if (attacker) { - const std::shared_ptr attackerMaster = attacker->getMaster(); + const auto &attackerMaster = attacker->getMaster(); if (targetPlayer) { if (targetPlayer->hasFlag(PlayerFlags_t::CannotBeAttacked)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } - const std::shared_ptr targetPlayerTile = targetPlayer->getTile(); + const auto &targetPlayerTile = targetPlayer->getTile(); - if (const std::shared_ptr attackerPlayer = attacker->getPlayer()) { + if (const auto &attackerPlayer = attacker->getPlayer()) { if (attackerPlayer->hasFlag(PlayerFlags_t::CannotAttackPlayer)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -354,7 +354,7 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const } if (attackerMaster) { - if (const std::shared_ptr masterAttackerPlayer = attackerMaster->getPlayer()) { + if (const auto &masterAttackerPlayer = attackerMaster->getPlayer()) { if (masterAttackerPlayer->hasFlag(PlayerFlags_t::CannotAttackPlayer)) { return RETURNVALUE_YOUMAYNOTATTACKTHISPLAYER; } @@ -379,7 +379,7 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE; } - if (const std::shared_ptr attackerPlayer = attacker->getPlayer()) { + if (const auto &attackerPlayer = attacker->getPlayer()) { if (attackerPlayer->hasFlag(PlayerFlags_t::CannotAttackMonster)) { return RETURNVALUE_YOUMAYNOTATTACKTHISCREATURE; } @@ -388,7 +388,7 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; } } else if (attacker->getMonster()) { - const std::shared_ptr targetMaster = target->getMaster(); + const auto &targetMaster = target->getMaster(); if ((!targetMaster || !targetMaster->getPlayer()) && attacker->getFaction() == FACTION_DEFAULT) { if (!attackerMaster || !attackerMaster->getPlayer()) { @@ -598,7 +598,7 @@ void Combat::CombatHealthFunc(const std::shared_ptr &caster, const std } if (attackerPlayer) { - const auto item = attackerPlayer->getWeapon(); + const auto &item = attackerPlayer->getWeapon(); damage = applyImbuementElementalDamage(attackerPlayer, item, damage); g_events().eventPlayerOnCombat(attackerPlayer, target, item, damage); @@ -621,7 +621,7 @@ void Combat::CombatHealthFunc(const std::shared_ptr &caster, const std // Player attacking monster if (attackerPlayer && targetMonster) { - const std::unique_ptr &slot = attackerPlayer->getPreyWithMonster(targetMonster->getRaceId()); + const auto &slot = attackerPlayer->getPreyWithMonster(targetMonster->getRaceId()); if (slot && slot->isOccupied() && slot->bonus == PreyBonus_Damage && slot->bonusTimeLeft > 0) { damage.primary.value += static_cast(std::ceil((damage.primary.value * slot->bonusPercentage) / 100)); damage.secondary.value += static_cast(std::ceil((damage.secondary.value * slot->bonusPercentage) / 100)); @@ -630,7 +630,7 @@ void Combat::CombatHealthFunc(const std::shared_ptr &caster, const std // Monster attacking player if (attackerMonster && targetPlayer) { - const std::unique_ptr &slot = targetPlayer->getPreyWithMonster(attackerMonster->getRaceId()); + const auto &slot = targetPlayer->getPreyWithMonster(attackerMonster->getRaceId()); if (slot && slot->isOccupied() && slot->bonus == PreyBonus_Defense && slot->bonusTimeLeft > 0) { damage.primary.value -= static_cast(std::ceil((damage.primary.value * slot->bonusPercentage) / 100)); damage.secondary.value -= static_cast(std::ceil((damage.secondary.value * slot->bonusPercentage) / 100)); @@ -713,7 +713,7 @@ bool Combat::checkFearConditionAffected(const std::shared_ptr &player) { return false; } - auto party = player->getParty(); + const auto &party = player->getParty(); if (party) { auto affectedCount = (party->getMemberCount() + 5) / 5; g_logger().debug("[{}] Player is member of a party, {} members can be feared", __FUNCTION__, affectedCount); @@ -750,7 +750,7 @@ void Combat::CombatConditionFunc(const std::shared_ptr &caster, const } else if (caster && caster->getMonster()) { uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_CLEANSE, false, 0); if (playerCharmRaceid != 0) { - const auto mType = g_monsters().getMonsterType(caster->getName()); + const auto &mType = g_monsters().getMonsterType(caster->getName()); if (mType && playerCharmRaceid == mType->info.raceid) { const auto charm = g_iobestiary().getBestiaryCharm(CHARM_CLEANSE); if (charm && (charm->chance > normal_random(0, 100))) { @@ -903,7 +903,7 @@ void Combat::addDistanceEffect(const std::shared_ptr &caster, const Po return; } - const auto player = caster->getPlayer(); + const auto &player = caster->getPlayer(); if (!player) { return; } @@ -1134,7 +1134,7 @@ void Combat::CombatFunc(const std::shared_ptr &caster, const Position uint32_t maxY = 0; // calculate the max viewable range - for (const std::shared_ptr &tile : tileList) { + for (const auto &tile : tileList) { const Position &tilePos = tile->getPosition(); uint32_t diff = Position::getDistanceX(tilePos, pos); @@ -1152,14 +1152,14 @@ void Combat::CombatFunc(const std::shared_ptr &caster, const Position const int32_t rangeY = maxY + MAP_MAX_VIEW_PORT_Y; int affected = 0; - for (const std::shared_ptr &tile : tileList) { + for (const auto &tile : tileList) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } if (CreatureVector* creatures = tile->getCreatures()) { - const std::shared_ptr topCreature = tile->getTopCreature(); - for (auto &creature : *creatures) { + const auto &topCreature = tile->getTopCreature(); + for (const auto &creature : *creatures) { if (params.targetCasterOrTopMost) { if (caster && caster->getTile() == tile) { if (creature != caster) { @@ -1207,14 +1207,14 @@ void Combat::CombatFunc(const std::shared_ptr &caster, const Position uint8_t beamAffectedCurrent = 0; tmpDamage.affected = affected; - for (const std::shared_ptr &tile : tileList) { + for (const auto &tile : tileList) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } if (CreatureVector* creatures = tile->getCreatures()) { - const std::shared_ptr topCreature = tile->getTopCreature(); - for (auto &creature : *creatures) { + const auto topCreature = tile->getTopCreature(); + for (const auto &creature : *creatures) { if (params.targetCasterOrTopMost) { if (caster && caster->getTile() == tile) { if (creature != caster) { @@ -1527,9 +1527,9 @@ uint32_t ValueCallback::getMagicLevelSkill(const std::shared_ptr &player uint32_t magicLevelSkill = player->getMagicLevel(); // Wheel of destiny if (player && player->wheel()->getInstant("Runic Mastery") && damage.instantSpellName.empty()) { - const std::shared_ptr spell = g_spells().getRuneSpellByName(damage.runeSpellName); + const std::shared_ptr &spell = g_spells().getRuneSpellByName(damage.runeSpellName); // Rune conjuring spell have the same name as the rune item spell. - const std::shared_ptr conjuringSpell = g_spells().getInstantSpellByName(damage.runeSpellName); + const std::shared_ptr &conjuringSpell = g_spells().getInstantSpellByName(damage.runeSpellName); if (spell && conjuringSpell && conjuringSpell != spell && normal_random(0, 100) <= 25) { uint32_t castResult = conjuringSpell->canCast(player) ? 20 : 10; magicLevelSkill += magicLevelSkill * castResult / 100; @@ -1577,7 +1577,7 @@ void ValueCallback::getMinMaxValues(const std::shared_ptr &player, Comba case COMBAT_FORMULA_SKILL: { // onGetPlayerMinMaxValues(player, attackSkill, attackValue, attackFactor) - std::shared_ptr tool = player->getWeapon(); + const auto &tool = player->getWeapon(); const auto &weapon = g_weapons().getWeapon(tool); int32_t attackSkill = 0; float attackFactor = 0; @@ -1831,7 +1831,7 @@ AreaCombat::AreaCombat(const AreaCombat &rhs) { } void AreaCombat::getList(const Position ¢erPos, const Position &targetPos, std::vector> &list) const { - const std::unique_ptr &area = getArea(centerPos, targetPos); + const auto &area = getArea(centerPos, targetPos); if (!area) { return; } @@ -2101,7 +2101,7 @@ void MagicField::onStepInField(const std::shared_ptr &creature) { const ItemType &it = items[getID()]; if (it.conditionDamage) { - auto conditionCopy = it.conditionDamage->clone(); + const auto &conditionCopy = it.conditionDamage->clone(); auto ownerId = getOwnerId(); if (ownerId) { bool harmfulField = true; @@ -2119,9 +2119,9 @@ void MagicField::onStepInField(const std::shared_ptr &creature) { } } - std::shared_ptr targetPlayer = creature->getPlayer(); + const auto &targetPlayer = creature->getPlayer(); if (targetPlayer) { - const std::shared_ptr attackerPlayer = g_game().getPlayerByID(ownerId); + const auto &attackerPlayer = g_game().getPlayerByID(ownerId); if (attackerPlayer) { if (Combat::isProtected(attackerPlayer, targetPlayer)) { harmfulField = false; @@ -2149,15 +2149,15 @@ void Combat::applyExtensions(const std::shared_ptr &caster, const std: // Critical hit uint16_t chance = 0; int32_t bonus = 50; - auto player = caster->getPlayer(); - auto monster = caster->getMonster(); + const auto &player = caster->getPlayer(); + const auto &monster = caster->getMonster(); if (player) { chance = player->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); bonus = player->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE); if (target && target->getMonster()) { uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_LOW, false, 0); if (playerCharmRaceid != 0) { - const auto mType = g_monsters().getMonsterType(target->getName()); + const auto &mType = g_monsters().getMonsterType(target->getName()); if (mType && playerCharmRaceid == mType->info.raceid) { const auto charm = g_iobestiary().getBestiaryCharm(CHARM_LOW); if (charm) { @@ -2183,7 +2183,7 @@ void Combat::applyExtensions(const std::shared_ptr &caster, const std: if (player) { // Fatal hit (onslaught) - if (auto playerWeapon = player->getInventoryItem(CONST_SLOT_LEFT); + if (const auto &playerWeapon = player->getInventoryItem(CONST_SLOT_LEFT); playerWeapon != nullptr && playerWeapon->getTier() > 0) { double_t fatalChance = playerWeapon->getFatalChance(); double_t randomChance = uniform_random(0, 10000) / 100; diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 8cd4a3f9c4d..1c2564da04c 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -180,7 +180,7 @@ void Condition::setTicks(int32_t newTicks) { endTime = ticks + OTSYS_TIME(); } -bool Condition::executeCondition(std::shared_ptr creature, int32_t interval) { +bool Condition::executeCondition(const std::shared_ptr &creature, int32_t interval) { if (ticks == -1) { return true; } @@ -361,7 +361,7 @@ std::unordered_set Condition::getIcons() const { return icons; } -bool Condition::updateCondition(const std::shared_ptr addCondition) { +bool Condition::updateCondition(const std::shared_ptr &addCondition) { if (conditionType != addCondition->getType()) { return false; } @@ -385,7 +385,7 @@ bool ConditionGeneric::startCondition(std::shared_ptr creature) { return Condition::startCondition(creature); } -bool ConditionGeneric::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionGeneric::executeCondition(const std::shared_ptr &creature, int32_t interval) { return Condition::executeCondition(creature, interval); } @@ -466,7 +466,7 @@ void ConditionAttributes::addCondition(std::shared_ptr creature, const updateCharmChanceModifier(creature); disableDefense = conditionAttrs->disableDefense; - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -570,7 +570,7 @@ bool ConditionAttributes::startCondition(std::shared_ptr creature) { updatePercentIncreases(creature); updateIncreases(creature); updateCharmChanceModifier(creature); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { updatePercentSkills(player); updateSkills(player); updatePercentStats(player); @@ -718,12 +718,12 @@ void ConditionAttributes::updateBuffs(const std::shared_ptr &creature) } } -bool ConditionAttributes::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionAttributes::executeCondition(const std::shared_ptr &creature, int32_t interval) { return ConditionGeneric::executeCondition(creature, interval); } void ConditionAttributes::endCondition(std::shared_ptr creature) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { bool needUpdate = false; @@ -1146,7 +1146,7 @@ void ConditionRegeneration::addCondition(std::shared_ptr creature, con if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const std::shared_ptr &conditionRegen = addCondition->static_self_cast(); + const auto &conditionRegen = addCondition->static_self_cast(); healthTicks = conditionRegen->healthTicks; manaTicks = conditionRegen->manaTicks; @@ -1155,7 +1155,7 @@ void ConditionRegeneration::addCondition(std::shared_ptr creature, con manaGain = conditionRegen->manaGain; } - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } } @@ -1189,10 +1189,10 @@ void ConditionRegeneration::serialize(PropWriteStream &propWriteStream) { propWriteStream.write(manaGain); } -bool ConditionRegeneration::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionRegeneration::executeCondition(const std::shared_ptr &creature, int32_t interval) { internalHealthTicks += interval; internalManaTicks += interval; - auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); int32_t dailyStreak = 0; if (player) { dailyStreak = static_cast(player->kv()->scoped("daily-reward")->get("streak")->getNumber()); @@ -1273,7 +1273,7 @@ bool ConditionRegeneration::setParam(ConditionParam_t param, int32_t value) { } uint32_t ConditionRegeneration::getHealthTicks(const std::shared_ptr &creature) const { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player != nullptr && isBuff) { return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); @@ -1283,7 +1283,7 @@ uint32_t ConditionRegeneration::getHealthTicks(const std::shared_ptr & } uint32_t ConditionRegeneration::getManaTicks(const std::shared_ptr &creature) const { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player != nullptr && isBuff) { return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); @@ -1304,7 +1304,7 @@ bool ConditionManaShield::startCondition(std::shared_ptr creature) { creature->setManaShield(manaShield); creature->setMaxManaShield(manaShield); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } @@ -1314,7 +1314,7 @@ bool ConditionManaShield::startCondition(std::shared_ptr creature) { void ConditionManaShield::endCondition(std::shared_ptr creature) { creature->setManaShield(0); creature->setMaxManaShield(0); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } } @@ -1329,7 +1329,7 @@ void ConditionManaShield::addCondition(std::shared_ptr creature, const creature->setManaShield(manaShield); creature->setMaxManaShield(manaShield); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } } @@ -1378,7 +1378,7 @@ void ConditionSoul::addCondition(std::shared_ptr, const std::shared_pt if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const std::shared_ptr &conditionSoul = addCondition->static_self_cast(); + const auto &conditionSoul = addCondition->static_self_cast(); soulTicks = conditionSoul->soulTicks; soulGain = conditionSoul->soulGain; @@ -1404,10 +1404,10 @@ void ConditionSoul::serialize(PropWriteStream &propWriteStream) { propWriteStream.write(soulTicks); } -bool ConditionSoul::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionSoul::executeCondition(const std::shared_ptr &creature, int32_t interval) { internalSoulTicks += interval; - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (player->getZoneType() != ZONE_PROTECTION) { if (internalSoulTicks >= soulTicks) { internalSoulTicks = 0; @@ -1529,8 +1529,8 @@ void ConditionDamage::serialize(PropWriteStream &propWriteStream) { } } -bool ConditionDamage::updateCondition(const std::shared_ptr addCondition) { - const std::shared_ptr &conditionDamage = addCondition->static_self_cast(); +bool ConditionDamage::updateCondition(const std::shared_ptr &addCondition) { + const auto &conditionDamage = addCondition->static_self_cast(); if (conditionDamage->doForceUpdate()) { return true; } @@ -1617,7 +1617,7 @@ bool ConditionDamage::startCondition(std::shared_ptr creature) { return true; } -bool ConditionDamage::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionDamage::executeCondition(const std::shared_ptr &creature, int32_t interval) { if (periodDamage != 0) { periodDamageTick += interval; @@ -1672,7 +1672,7 @@ bool ConditionDamage::getNextDamage(int32_t &damage) { } bool ConditionDamage::doDamage(const std::shared_ptr &creature, int32_t healthChange) { - auto attacker = g_game().getPlayerByGUID(owner) ? g_game().getPlayerByGUID(owner)->getCreature() : g_game().getCreatureByID(owner); + const auto &attacker = g_game().getPlayerByGUID(owner) ? g_game().getPlayerByGUID(owner)->getCreature() : g_game().getCreatureByID(owner); bool isPlayer = attacker && attacker->getPlayer(); if (creature->isSuppress(getType(), isPlayer)) { return true; @@ -1868,7 +1868,7 @@ bool ConditionFeared::canWalkTo(const std::shared_ptr &creature, Posit auto tile = g_game().map.getTile(pos); if (tile && tile->getTopVisibleCreature(creature) == nullptr && tile->queryAdd(0, creature, 1, FLAG_PATHFINDING) == RETURNVALUE_NOERROR) { - std::shared_ptr field = tile->getFieldItem(); + const auto &field = tile->getFieldItem(); if (field && !field->isBlocking() && field->getDamage() != 0) { return false; } @@ -2055,7 +2055,7 @@ bool ConditionFeared::startCondition(std::shared_ptr creature) { return Condition::startCondition(creature); } -bool ConditionFeared::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionFeared::executeCondition(const std::shared_ptr &creature, int32_t interval) { Position currentPos = creature->getPosition(); std::vector listDir; @@ -2190,7 +2190,7 @@ bool ConditionSpeed::startCondition(std::shared_ptr creature) { return true; } -bool ConditionSpeed::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionSpeed::executeCondition(const std::shared_ptr &creature, int32_t interval) { return Condition::executeCondition(creature, interval); } @@ -2304,7 +2304,7 @@ bool ConditionOutfit::startCondition(std::shared_ptr creature) { } if ((outfit.lookType == 0 && outfit.lookTypeEx == 0) && !monsterName.empty()) { - const auto monsterType = g_monsters().getMonsterType(monsterName); + const auto &monsterType = g_monsters().getMonsterType(monsterName); if (monsterType) { setOutfit(monsterType->info.outfit); } else { @@ -2321,7 +2321,7 @@ bool ConditionOutfit::startCondition(std::shared_ptr creature) { return true; } -bool ConditionOutfit::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionOutfit::executeCondition(const std::shared_ptr &creature, int32_t interval) { return Condition::executeCondition(creature, interval); } @@ -2338,9 +2338,9 @@ void ConditionOutfit::addCondition(std::shared_ptr creature, const std if (updateCondition(addCondition)) { setTicks(addCondition->getTicks()); - const std::shared_ptr &conditionOutfit = addCondition->static_self_cast(); + const auto &conditionOutfit = addCondition->static_self_cast(); if (!conditionOutfit->monsterName.empty() && conditionOutfit->monsterName != monsterName) { - const auto monsterType = g_monsters().getMonsterType(conditionOutfit->monsterName); + const auto &monsterType = g_monsters().getMonsterType(conditionOutfit->monsterName); if (monsterType) { setOutfit(monsterType->info.outfit); } else { @@ -2371,7 +2371,7 @@ bool ConditionLight::startCondition(std::shared_ptr creature) { return true; } -bool ConditionLight::executeCondition(std::shared_ptr creature, int32_t interval) { +bool ConditionLight::executeCondition(const std::shared_ptr &creature, int32_t interval) { internalLightTicks += interval; if (internalLightTicks >= lightChangeInterval) { @@ -2397,7 +2397,7 @@ void ConditionLight::addCondition(std::shared_ptr creature, const std: if (updateCondition(condition)) { setTicks(condition->getTicks()); - const std::shared_ptr &conditionLight = condition->static_self_cast(); + const auto &conditionLight = condition->static_self_cast(); lightInfo.level = conditionLight->lightInfo.level; lightInfo.color = conditionLight->lightInfo.color; lightChangeInterval = ticks / lightInfo.level; @@ -2480,7 +2480,7 @@ void ConditionSpellCooldown::addCondition(std::shared_ptr creature, co setTicks(addCondition->getTicks()); if (subId != 0 && ticks > 0) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendSpellCooldown(subId, ticks); } @@ -2494,7 +2494,7 @@ bool ConditionSpellCooldown::startCondition(std::shared_ptr creature) } if (subId != 0 && ticks > 0) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendSpellCooldown(subId, ticks); } @@ -2511,7 +2511,7 @@ void ConditionSpellGroupCooldown::addCondition(std::shared_ptr creatur setTicks(addCondition->getTicks()); if (subId != 0 && ticks > 0) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } @@ -2525,7 +2525,7 @@ bool ConditionSpellGroupCooldown::startCondition(std::shared_ptr creat } if (subId != 0 && ticks > 0) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendSpellGroupCooldown(static_cast(subId), ticks); } diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index f4777f0ef5d..dead14304d3 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -27,7 +27,7 @@ class Condition : public SharedObject { ~Condition() override = default; virtual bool startCondition(std::shared_ptr creature); - virtual bool executeCondition(std::shared_ptr creature, int32_t interval); + virtual bool executeCondition(const std::shared_ptr &creature, int32_t interval); virtual void endCondition(std::shared_ptr creature) = 0; virtual void addCondition(std::shared_ptr creature, std::shared_ptr condition) = 0; virtual std::unordered_set getIcons() const; @@ -75,7 +75,7 @@ class Condition : public SharedObject { bool isBuff {}; bool m_isPersistent {}; - virtual bool updateCondition(std::shared_ptr addCondition); + virtual bool updateCondition(const std::shared_ptr &addCondition); private: SoundEffect_t tickSound = SoundEffect_t::SILENCE; @@ -91,7 +91,7 @@ class ConditionGeneric : public Condition { Condition(initId, initType, initTicks, initBuff, initSubId, isPersistent) { } bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::unordered_set getIcons() const override; @@ -107,7 +107,7 @@ class ConditionAttributes final : public ConditionGeneric { ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(std::shared_ptr creature) final; - bool executeCondition(std::shared_ptr creature, int32_t interval) final; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) final; void endCondition(std::shared_ptr creature) final; void addCondition(std::shared_ptr creature, std::shared_ptr condition) final; @@ -176,7 +176,7 @@ class ConditionRegeneration final : public ConditionGeneric { bool startCondition(std::shared_ptr creature) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; @@ -231,7 +231,7 @@ class ConditionSoul final : public ConditionGeneric { ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) { } void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; @@ -271,7 +271,7 @@ class ConditionDamage final : public Condition { static void generateDamageList(int32_t amount, int32_t start, std::list &list); bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::unordered_set getIcons() const override; @@ -312,7 +312,7 @@ class ConditionDamage final : public Condition { bool getNextDamage(int32_t &damage); bool doDamage(const std::shared_ptr &creature, int32_t healthChange); - bool updateCondition(std::shared_ptr addCondition) override; + bool updateCondition(const std::shared_ptr &addCondition) override; }; class ConditionFeared final : public Condition { @@ -322,7 +322,7 @@ class ConditionFeared final : public Condition { Condition(intiId, initType, initTicks, initBuff, initSubId) { } bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::unordered_set getIcons() const override; @@ -361,7 +361,7 @@ class ConditionSpeed final : public Condition { Condition(initId, initType, initTicks, initBuff, initSubId), speedDelta(initChangeSpeed) { } bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::unordered_set getIcons() const override; @@ -396,7 +396,7 @@ class ConditionOutfit final : public Condition { Condition(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; @@ -422,7 +422,7 @@ class ConditionLight final : public Condition { Condition(initId, initType, initTicks, initBuff, initSubId), lightInfo(initLightlevel, initLightcolor) { } bool startCondition(std::shared_ptr creature) override; - bool executeCondition(std::shared_ptr creature, int32_t interval) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index bf52b7dcef1..102b3b27c7a 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -26,7 +26,7 @@ Spells::~Spells() = default; TalkActionResult_t Spells::playerSaySpell(const std::shared_ptr &player, std::string &words) { auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); - auto tile = player->getTile(); + const auto &tile = player->getTile(); if (maxOnline > 1 && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE)) { auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT, __FUNCTION__); auto accountPlayers = g_game().getPlayersByAccount(player->getAccount()); @@ -54,7 +54,7 @@ TalkActionResult_t Spells::playerSaySpell(const std::shared_ptr &player, // strip trailing spaces trimString(str_words); - const std::shared_ptr instantSpell = getInstantSpell(str_words); + const auto &instantSpell = getInstantSpell(str_words); if (!instantSpell) { return TALKACTION_CONTINUE; } @@ -185,7 +185,7 @@ std::shared_ptr Spells::getSpellByName(const std::string &name) { std::shared_ptr Spells::getRuneSpell(uint16_t id) { auto it = runes.find(id); if (it == runes.end()) { - for (auto &rune : runes) { + for (const auto &rune : runes) { if (rune.second->getRuneItemId() == id) { return rune.second; } @@ -196,7 +196,7 @@ std::shared_ptr Spells::getRuneSpell(uint16_t id) { } std::shared_ptr Spells::getRuneSpellByName(const std::string &name) { - for (auto &it : runes) { + for (const auto &it : runes) { if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { return it.second; } @@ -207,7 +207,7 @@ std::shared_ptr Spells::getRuneSpellByName(const std::string &name) { std::shared_ptr Spells::getInstantSpell(const std::string &words) { std::shared_ptr result = nullptr; - for (auto &it : instants) { + for (const auto &it : instants) { const std::string &instantSpellWords = it.second->getWords(); size_t spellLen = instantSpellWords.length(); if (strncasecmp(instantSpellWords.c_str(), words.c_str(), spellLen) == 0) { @@ -239,7 +239,7 @@ std::shared_ptr Spells::getInstantSpell(const std::string &words) } std::shared_ptr Spells::getInstantSpellById(uint16_t spellId) { - for (auto &it : instants) { + for (const auto &it : instants) { if (it.second->getSpellId() == spellId) { return it.second; } @@ -248,7 +248,7 @@ std::shared_ptr Spells::getInstantSpellById(uint16_t spellId) { } std::shared_ptr Spells::getInstantSpellByName(const std::string &name) { - for (auto &it : instants) { + for (const auto &it : instants) { if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { return it.second; } @@ -273,7 +273,7 @@ bool CombatSpell::loadScriptCombat() { return m_combat != nullptr; } -bool CombatSpell::castSpell(std::shared_ptr creature) { +bool CombatSpell::castSpell(const std::shared_ptr &creature) { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_POSITION; @@ -311,7 +311,7 @@ bool CombatSpell::castSpell(std::shared_ptr creature) { return true; } -bool CombatSpell::castSpell(std::shared_ptr creature, std::shared_ptr target) { +bool CombatSpell::castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) { auto combat = getCombat(); if (!combat) { return false; @@ -501,7 +501,7 @@ bool Spell::playerInstantSpellCheck(const std::shared_ptr &player, const return false; } - const auto tile = g_game().map.getOrCreateTile(toPos); + const auto &tile = g_game().map.getOrCreateTile(toPos); ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); if (ret != RETURNVALUE_NOERROR) { @@ -545,7 +545,7 @@ bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Po return false; } - std::shared_ptr tile = g_game().map.getTile(toPos); + const auto &tile = g_game().map.getTile(toPos); if (!tile) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -565,12 +565,8 @@ bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Po return false; } - const std::shared_ptr topVisibleCreature = tile->getBottomVisibleCreature(player); - if (blockingCreature && topVisibleCreature) { - player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); - g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); - return false; - } else if (blockingSolid && tile->hasFlag(TILESTATE_BLOCKSOLID) && !topVisibleCreature) { + const auto &topVisibleCreature = tile->getBottomVisibleCreature(player); + if ((blockingCreature && topVisibleCreature) || (blockingSolid && tile->hasFlag(TILESTATE_BLOCKSOLID) && !topVisibleCreature)) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHROOM); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); return false; @@ -583,7 +579,7 @@ bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Po } if (aggressive && needTarget && topVisibleCreature && player->hasSecureMode()) { - const std::shared_ptr targetPlayer = topVisibleCreature->getPlayer(); + const auto &targetPlayer = topVisibleCreature->getPlayer(); if (targetPlayer && targetPlayer != player && player->getSkullClient(targetPlayer) == SKULL_NONE && !Combat::isInPvpZone(player, targetPlayer)) { player->sendCancelMessage(RETURNVALUE_TURNSECUREMODETOATTACKUNMARKEDPLAYERS); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -686,7 +682,7 @@ void Spell::applyCooldownConditions(const std::shared_ptr &player) const spellCooldown -= player->wheel()->getSpellBonus(name, WheelSpellBoost_t::COOLDOWN); spellCooldown -= augmentCooldownReduction; if (spellCooldown > 0) { - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, spellCooldown / rateCooldown, 0, false, m_spellId); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLCOOLDOWN, spellCooldown / rateCooldown, 0, false, m_spellId); player->addCondition(condition); } } @@ -708,7 +704,7 @@ void Spell::applyCooldownConditions(const std::shared_ptr &player) const spellSecondaryGroupCooldown -= getWheelOfDestinyBoost(WheelSpellBoost_t::SECONDARY_GROUP_COOLDOWN, spellGrade); } if (spellSecondaryGroupCooldown > 0) { - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, spellSecondaryGroupCooldown / rateCooldown, 0, false, secondaryGroup); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, spellSecondaryGroupCooldown / rateCooldown, 0, false, secondaryGroup); player->addCondition(condition); } } @@ -906,12 +902,12 @@ bool InstantSpell::canThrowSpell(const std::shared_ptr &creature, cons return true; } -bool InstantSpell::castSpell(std::shared_ptr creature) { +bool InstantSpell::castSpell(const std::shared_ptr &creature) { LuaVariant var; var.instantName = getName(); if (casterTargetOrDirection) { - std::shared_ptr target = creature->getAttackedCreature(); + const auto &target = creature->getAttackedCreature(); if (target && target->getHealth() > 0) { if (!canThrowSpell(creature, target)) { return false; @@ -935,7 +931,7 @@ bool InstantSpell::castSpell(std::shared_ptr creature) { return executeCastSpell(creature, var); } -bool InstantSpell::castSpell(std::shared_ptr creature, std::shared_ptr target) { +bool InstantSpell::castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) { if (needTarget) { LuaVariant var; var.type = VARIANT_NUMBER; @@ -1030,9 +1026,9 @@ bool RuneSpell::executeUse(const std::shared_ptr &player, const std::sha var.type = VARIANT_NUMBER; if (target == nullptr) { - std::shared_ptr toTile = g_game().map.getTile(toPosition); + const auto &toTile = g_game().map.getTile(toPosition); if (toTile) { - std::shared_ptr visibleCreature = toTile->getBottomVisibleCreature(player); + const auto &visibleCreature = toTile->getBottomVisibleCreature(player); if (visibleCreature) { var.number = visibleCreature->getID(); } @@ -1065,7 +1061,7 @@ bool RuneSpell::executeUse(const std::shared_ptr &player, const std::sha return true; } -bool RuneSpell::castSpell(std::shared_ptr creature) { +bool RuneSpell::castSpell(const std::shared_ptr &creature) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = creature->getID(); @@ -1073,7 +1069,7 @@ bool RuneSpell::castSpell(std::shared_ptr creature) { return internalCastSpell(creature, var, false); } -bool RuneSpell::castSpell(std::shared_ptr creature, std::shared_ptr target) { +bool RuneSpell::castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) { LuaVariant var; var.type = VARIANT_NUMBER; var.number = target->getID(); diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index 4e97db0356d..b86354707b6 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -75,15 +75,15 @@ class Spells final : public Scripts { constexpr auto g_spells = Spells::getInstance; -using RuneSpellFunction = std::function spell, const auto player, const Position &posTo)>; +using RuneSpellFunction [[maybe_unused]] = std::function &spell, const std::shared_ptr &player, const Position &posTo)>; class BaseSpell { public: constexpr BaseSpell() = default; virtual ~BaseSpell() = default; - virtual bool castSpell(std::shared_ptr creature) = 0; - virtual bool castSpell(std::shared_ptr creature, std::shared_ptr target) = 0; + virtual bool castSpell(const std::shared_ptr &creature) = 0; + virtual bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) = 0; SoundEffect_t soundImpactEffect = SoundEffect_t::SILENCE; SoundEffect_t soundCastEffect = SoundEffect_t::SPELL_OR_RUNE; @@ -98,8 +98,8 @@ class CombatSpell final : public Script, public BaseSpell, public std::enable_sh CombatSpell(const CombatSpell &) = delete; CombatSpell &operator=(const CombatSpell &) = delete; - bool castSpell(std::shared_ptr creature) override; - bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; + bool castSpell(const std::shared_ptr &creature) override; + bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) override; // Scripting spell bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const; @@ -401,8 +401,8 @@ class InstantSpell final : public Script, public Spell { virtual bool playerCastInstant(std::shared_ptr player, std::string ¶m); - bool castSpell(std::shared_ptr creature) override; - bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; + bool castSpell(const std::shared_ptr &creature) override; + bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) override; // Scripting spell bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const; @@ -469,8 +469,8 @@ class RuneSpell final : public Action, public Spell { bool executeUse(const std::shared_ptr &player, const std::shared_ptr &item, const Position &fromPosition, const std::shared_ptr &target, const Position &toPosition, bool isHotkey) override; - bool castSpell(std::shared_ptr creature) override; - bool castSpell(std::shared_ptr creature, std::shared_ptr target) override; + bool castSpell(const std::shared_ptr &creature) override; + bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) override; // Scripting spell bool executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) const; diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 8d0a92dc389..5742294538e 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -261,7 +261,8 @@ void Creature::addEventWalk(bool firstStep) { static_cast(ticks), [creatureId = self->getID()] { g_game().checkCreatureWalk(creatureId); }, "Game::checkCreatureWalk" ); - }); + }, + __FUNCTION__); } void Creature::stopEventWalk() { @@ -1061,7 +1062,7 @@ void Creature::goToFollowCreature_async(std::function &&onComplete) { }); if (onComplete) { - g_dispatcher().context().addEvent(std::move(onComplete)); + g_dispatcher().context().addEvent(std::move(onComplete), __FUNCTION__); } } diff --git a/src/game/scheduling/dispatcher.cpp b/src/game/scheduling/dispatcher.cpp index ff6cf86b98a..e9abefc08a3 100644 --- a/src/game/scheduling/dispatcher.cpp +++ b/src/game/scheduling/dispatcher.cpp @@ -236,17 +236,17 @@ void Dispatcher::stopEvent(uint64_t eventId) { } } -void DispatcherContext::addEvent(std::function &&f) const { - g_dispatcher().addEvent(std::move(f), taskName); +void DispatcherContext::addEvent(std::function &&f, std::string_view context) const { + g_dispatcher().addEvent(std::move(f), context); } -void DispatcherContext::tryAddEvent(std::function &&f) const { +void DispatcherContext::tryAddEvent(std::function &&f, std::string_view context) const { if (!f) { return; } if (isAsync()) { - g_dispatcher().addEvent(std::move(f), taskName); + g_dispatcher().addEvent(std::move(f), context); } else { f(); } diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 19f8104c3bd..6dbc20b06ff 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -56,10 +56,10 @@ struct DispatcherContext { } // postpone the event - void addEvent(std::function &&f) const; + void addEvent(std::function &&f, std::string_view context) const; // if the context is async, the event will be postponed, if not, it will be executed immediately. - void tryAddEvent(std::function &&f) const; + void tryAddEvent(std::function &&f, std::string_view context) const; private: void reset() { @@ -128,7 +128,7 @@ class Dispatcher { void stopEvent(uint64_t eventId); - static const auto &context() { + const auto &context() { return dispacherContext; } diff --git a/src/game/scheduling/task.cpp b/src/game/scheduling/task.cpp index 59fcff86715..743fb239b81 100644 --- a/src/game/scheduling/task.cpp +++ b/src/game/scheduling/task.cpp @@ -16,8 +16,7 @@ std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0; -Task::Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, - const std::source_location& location) : +Task::Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, const std::source_location &location) : func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME()), expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { if (this->context.empty()) { @@ -28,8 +27,7 @@ Task::Task(uint32_t expiresAfterMs, std::function &&f, std::string_v assert(!this->context.empty() && "Context cannot be empty!"); } -Task::Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle /* = false*/, bool log /*= true*/, - const std::source_location& location) : +Task::Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle /* = false*/, bool log /*= true*/, const std::source_location &location) : func(std::move(f)), context(context), functionName(location.function_name()), utime(OTSYS_TIME() + delay), delay(delay), cycle(cycle), log(log) { if (this->context.empty()) { diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index 419298b4196..26d48801ef1 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -14,11 +14,9 @@ class Task { public: - Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, - const std::source_location& location = std::source_location::current()); + Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context, const std::source_location &location = std::source_location::current()); - Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true, - const std::source_location& location = std::source_location::current()); + Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true, const std::source_location &location = std::source_location::current()); ~Task() = default; @@ -32,31 +30,31 @@ class Task { return id; } - uint32_t getDelay() const { + [[nodiscard]] uint32_t getDelay() const { return delay; } - std::string_view getContext() const { + [[nodiscard]] std::string_view getContext() const { return context; } - std::string_view getFunctionName() const { + [[nodiscard]] std::string_view getFunctionName() const { return functionName; } - auto getTime() const { + [[nodiscard]] auto getTime() const { return utime; } - bool hasExpired() const { + [[nodiscard]] bool hasExpired() const { return expiration != 0 && expiration < OTSYS_TIME(); } - bool isCycle() const { + [[nodiscard]] bool isCycle() const { return cycle; } - bool isCanceled() const { + [[nodiscard]] bool isCanceled() const { return func == nullptr; } @@ -64,7 +62,7 @@ class Task { func = nullptr; } - bool execute() const; + [[nodiscard]] bool execute() const; private: static std::atomic_uint_fast64_t LAST_EVENT_ID; @@ -73,7 +71,7 @@ class Task { utime = OTSYS_TIME() + delay; } - bool hasTraceableContext() const { + [[nodiscard]] bool hasTraceableContext() const { const static auto tasksContext = std::unordered_set({ "Decay::checkDecay", "Dispatcher::asyncEvent", "Game::checkCreatureAttack", diff --git a/src/map/mapcache.cpp b/src/map/mapcache.cpp index 3d39fa8943f..6d05b68a76b 100644 --- a/src/map/mapcache.cpp +++ b/src/map/mapcache.cpp @@ -142,7 +142,8 @@ std::shared_ptr MapCache::getOrCreateTileFromCache(const std::unique_ptraddZone(zone); } - }); + }, + __FUNCTION__); floor->setTile(x, y, tile); From 03e390f7a8cc5f5fc41384c406ef26a2aa3a245a Mon Sep 17 00:00:00 2001 From: Beats Date: Thu, 1 Aug 2024 23:26:02 -0300 Subject: [PATCH 05/34] fix crash --- src/items/tile.cpp | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 5b1cb1a1835..028df494bff 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -993,32 +993,36 @@ void Tile::addThing(std::shared_ptr thing) { void Tile::addThing(int32_t, std::shared_ptr thing) { if (!thing) { - return /*RETURNVALUE_NOTPOSSIBLE*/; + return; // RETURNVALUE_NOTPOSSIBLE } + // Verify if the thing is a creature std::shared_ptr creature = thing->getCreature(); if (creature) { Spectators::clearCache(); creature->setParent(static_self_cast()); + // Safely add creature to the list CreatureVector* creatures = makeCreatures(); - creatures->insert(creatures->begin(), creature); + if (creatures) { + creatures->insert(creatures->begin(), creature); + } } else { - const auto item = thing->getItem(); - if (item == nullptr) { - return /*RETURNVALUE_NOTPOSSIBLE*/; + const auto &item = thing->getItem(); + if (!item) { + return; // RETURNVALUE_NOTPOSSIBLE } TileItemVector* items = getItemList(); if (items && items->size() >= 0xFFFF) { - return /*RETURNVALUE_NOTPOSSIBLE*/; + return; // RETURNVALUE_NOTPOSSIBLE } item->setParent(static_self_cast()); const ItemType &itemType = Item::items[item->getID()]; if (itemType.isGroundTile()) { - if (ground == nullptr) { + if (!ground) { ground = item; onAddTileItem(item); } else { @@ -1034,9 +1038,9 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { } } else if (item->isAlwaysOnTop()) { if (itemType.isSplash() && items) { - // remove old splash if exists - for (ItemVector::const_iterator it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - const std::shared_ptr &oldSplash = *it; + // Remove old splash if it exists + for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { + const auto oldSplash = *it; if (!Item::items[oldSplash->getID()].isSplash()) { continue; } @@ -1052,7 +1056,7 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { if (items) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - // Note: this is different from internalAddThing + // Check if the current item should be placed before the current item if (itemType.alwaysOnTopOrder <= Item::items[(*it)->getID()].alwaysOnTopOrder) { items->insert(it, item); isInserted = true; @@ -1063,16 +1067,16 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { items = makeItemList(); } - if (!isInserted) { + if (!isInserted && items) { items->push_back(item); } onAddTileItem(item); } else { if (itemType.isMagicField()) { - // remove old field item if exists + // Remove old field item if it exists if (items) { - for (ItemVector::const_iterator it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { + for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { std::shared_ptr oldField = (*it)->getMagicField(); if (oldField) { if (oldField->isReplaceable()) { @@ -1091,9 +1095,11 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { } } - items = makeItemList(); - items->insert(items->getBeginDownItem(), item); - items->increaseDownItemCount(); + if (items) { + items = makeItemList(); + items->insert(items->getBeginDownItem(), item); + items->increaseDownItemCount(); + } onAddTileItem(item); } } From f7309d2fceb8046d3e4b81eb69cd85782a1cf5b9 Mon Sep 17 00:00:00 2001 From: Beats Date: Sun, 4 Aug 2024 12:33:03 -0300 Subject: [PATCH 06/34] up --- src/creatures/creature.cpp | 16 ++--- src/creatures/creature.hpp | 22 +++--- src/creatures/interactions/chat.cpp | 28 ++++---- src/creatures/monsters/monster.cpp | 72 +++++++++---------- src/creatures/monsters/monster.hpp | 20 +++--- src/creatures/monsters/monsters.cpp | 16 ++--- .../monsters/spawns/spawn_monster.cpp | 7 +- src/creatures/npcs/npc.cpp | 22 +++--- src/creatures/npcs/npc.hpp | 6 +- src/creatures/npcs/spawns/spawn_npc.cpp | 4 +- .../achievement/player_achievement.cpp | 6 +- .../players/cyclopedia/player_badge.cpp | 2 +- .../players/cyclopedia/player_badge.hpp | 4 +- .../players/cyclopedia/player_cyclopedia.hpp | 3 - .../players/cyclopedia/player_title.hpp | 4 -- src/creatures/players/grouping/familiars.cpp | 6 +- src/creatures/players/grouping/familiars.hpp | 3 - src/creatures/players/grouping/groups.cpp | 8 +-- src/creatures/players/grouping/groups.hpp | 2 - src/creatures/players/grouping/guild.cpp | 6 +- src/creatures/players/grouping/party.cpp | 60 ++++++++-------- .../players/imbuements/imbuements.cpp | 4 +- .../players/imbuements/imbuements.hpp | 1 - src/creatures/players/player.cpp | 16 ++--- src/creatures/players/player.hpp | 16 ++--- src/creatures/players/storages/storages.cpp | 12 ++-- src/creatures/players/storages/storages.hpp | 6 +- src/creatures/players/vip/player_vip.cpp | 8 +-- src/creatures/players/vocations/vocation.cpp | 10 ++- src/creatures/players/vocations/vocation.hpp | 12 ++-- src/creatures/players/wheel/player_wheel.cpp | 22 +++--- src/creatures/players/wheel/player_wheel.hpp | 1 - src/creatures/players/wheel/wheel_gems.cpp | 2 +- src/enums/player_cyclopedia.hpp | 2 +- src/game/game.cpp | 4 +- src/lua/creature/events.cpp | 2 +- src/lua/creature/events.hpp | 2 +- src/lua/global/globalevent.cpp | 12 ++-- src/lua/modules/modules.cpp | 4 +- src/lua/modules/modules.hpp | 1 - 40 files changed, 219 insertions(+), 235 deletions(-) diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 5742294538e..7873c883f83 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -361,7 +361,7 @@ void Creature::onRemoveTileItem(std::shared_ptr updateTile, const Position } } -void Creature::onCreatureAppear(std::shared_ptr creature, bool isLogin) { +void Creature::onCreatureAppear(const std::shared_ptr &creature, bool isLogin) { metrics::method_latency measure(__METHOD_NAME__); if (creature == getCreature()) { if (useCacheMap()) { @@ -379,7 +379,7 @@ void Creature::onCreatureAppear(std::shared_ptr creature, bool isLogin } } -void Creature::onRemoveCreature(std::shared_ptr creature, bool) { +void Creature::onRemoveCreature(const std::shared_ptr &creature, bool) { metrics::method_latency measure(__METHOD_NAME__); onCreatureDisappear(creature, true); if (creature != getCreature() && isMapLoaded) { @@ -853,7 +853,7 @@ bool Creature::hasBeenAttacked(uint32_t attackerId) { return (OTSYS_TIME() - it->second.ticks) <= g_configManager().getNumber(PZ_LOCKED, __FUNCTION__); } -std::shared_ptr Creature::getCorpse(std::shared_ptr, std::shared_ptr) { +std::shared_ptr Creature::getCorpse(const std::shared_ptr &, const std::shared_ptr &) { if (getLookCorpse() != 0) { return Item::CreateItem(getLookCorpse()); } @@ -892,7 +892,7 @@ void Creature::gainHealth(const std::shared_ptr &healer, int32_t healt } } -void Creature::drainHealth(std::shared_ptr attacker, int32_t damage) { +void Creature::drainHealth(const std::shared_ptr &attacker, int32_t damage) { changeHealth(-damage, false); if (attacker) { @@ -943,7 +943,7 @@ void Creature::applyAbsorbDamageModifications(const std::shared_ptr &a } } -BlockType_t Creature::blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */) { +BlockType_t Creature::blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense /* = false */, bool checkArmor /* = false */, bool /* field = false */) { BlockType_t blockType = BLOCK_NONE; // Apply skills 12.72 absorbs damage @@ -1201,7 +1201,7 @@ void Creature::addDamagePoints(const std::shared_ptr &attacker, int32_ lastHitCreatureId = attackerId; } -void Creature::onAddCondition(ConditionType_t type) { +void Creature::onAddCondition(const ConditionType_t &type) { if (type == CONDITION_PARALYZE && hasCondition(CONDITION_HASTE)) { removeCondition(CONDITION_HASTE); } else if (type == CONDITION_HASTE && hasCondition(CONDITION_PARALYZE)) { @@ -1209,11 +1209,11 @@ void Creature::onAddCondition(ConditionType_t type) { } } -void Creature::onAddCombatCondition(ConditionType_t) { +void Creature::onAddCombatCondition(const ConditionType_t &) { // } -void Creature::onEndCondition(ConditionType_t) { +void Creature::onEndCondition(const ConditionType_t &) { // } diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index 697d50089bc..7811d833f46 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -342,7 +342,7 @@ class Creature : virtual public Thing, public SharedObject { * @param damage Reference to the amount of damage inflicted, which will be reduced by the creature's mitigation factor. */ void mitigateDamage(const CombatType_t &combatType, BlockType_t &blockType, int32_t &damage) const; - virtual BlockType_t blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false); + virtual BlockType_t blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false); void applyAbsorbDamageModifications(const std::shared_ptr &attacker, int32_t &damage, CombatType_t combatType) const; @@ -425,10 +425,10 @@ class Creature : virtual public Thing, public SharedObject { virtual void changeMana(int32_t manaChange); void gainHealth(const std::shared_ptr &attacker, int32_t healthGain); - virtual void drainHealth(std::shared_ptr attacker, int32_t damage); + virtual void drainHealth(const std::shared_ptr &attacker, int32_t damage); virtual void drainMana(std::shared_ptr attacker, int32_t manaLoss); - virtual bool challengeCreature(std::shared_ptr, [[maybe_unused]] int targetChangeCooldown) { + virtual bool challengeCreature(const std::shared_ptr &, [[maybe_unused]] int targetChangeCooldown) { return false; } @@ -438,9 +438,9 @@ class Creature : virtual public Thing, public SharedObject { bool hasBeenAttacked(uint32_t attackerId); // combat event functions - virtual void onAddCondition(ConditionType_t type); - virtual void onAddCombatCondition(ConditionType_t type); - virtual void onEndCondition(ConditionType_t type); + virtual void onAddCondition(const ConditionType_t &type); + virtual void onAddCombatCondition(const ConditionType_t &type); + virtual void onEndCondition(const ConditionType_t &type); void onTickCondition(ConditionType_t type, bool &bRemove); virtual void onCombatRemoveCondition(std::shared_ptr condition); virtual void onAttackedCreature(std::shared_ptr) { } @@ -481,8 +481,8 @@ class Creature : virtual public Thing, public SharedObject { virtual void onUpdateTileItem(std::shared_ptr tile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType); virtual void onRemoveTileItem(std::shared_ptr tile, const Position &pos, const ItemType &iType, std::shared_ptr item); - virtual void onCreatureAppear(std::shared_ptr creature, bool isLogin); - virtual void onRemoveCreature(std::shared_ptr creature, bool isLogout); + virtual void onCreatureAppear(const std::shared_ptr &creature, bool isLogin); + virtual void onRemoveCreature(const std::shared_ptr &creature, bool isLogout); /** * @brief Check if the summon can move/spawn and if the familiar can teleport to the master @@ -498,7 +498,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void onAttackedCreatureDisappear(bool) { } virtual void onFollowCreatureDisappear(bool) { } - virtual void onCreatureSay(std::shared_ptr, SpeakClasses, const std::string &) { } + virtual void onCreatureSay(const std::shared_ptr &, SpeakClasses, const std::string &) { } virtual void onPlacedCreature() { } @@ -815,14 +815,14 @@ class Creature : virtual public Thing, public SharedObject { virtual uint64_t getLostExperience() const { return 0; } - virtual void dropLoot(std::shared_ptr, std::shared_ptr) { } + virtual void dropLoot(const std::shared_ptr &, std::shared_ptr) { } virtual uint16_t getLookCorpse() const { return 0; } virtual void getPathSearchParams(const std::shared_ptr &, FindPathParams &fpp); virtual void death(std::shared_ptr) { } virtual bool dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); - virtual std::shared_ptr getCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature); + virtual std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature); friend class Game; friend class Map; diff --git a/src/creatures/interactions/chat.cpp b/src/creatures/interactions/chat.cpp index 70b46c34246..b32cf170132 100644 --- a/src/creatures/interactions/chat.cpp +++ b/src/creatures/interactions/chat.cpp @@ -79,7 +79,7 @@ bool ChatChannel::addUser(const std::shared_ptr &player) { // TODO: Move to script when guild channels can be scripted if (id == CHANNEL_GUILD) { - const auto guild = player->getGuild(); + const auto &guild = player->getGuild(); if (guild && !guild->getMotd().empty()) { g_dispatcher().scheduleEvent( 150, [playerId = player->getID()] { g_game().sendGuildMotd(playerId); }, "Game::sendGuildMotd" @@ -278,7 +278,7 @@ bool Chat::load() { return false; } - for (auto channelNode : doc.child("channels").children()) { + for (const auto &channelNode : doc.child("channels").children()) { auto channelId = pugi::cast(channelNode.attribute("id").value()); std::string channelName = channelNode.attribute("name").as_string(); bool isPublic = channelNode.attribute("public").as_bool(); @@ -334,7 +334,7 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & switch (channelId) { case CHANNEL_GUILD: { - const auto guild = player->getGuild(); + const auto &guild = player->getGuild(); if (guild != nullptr) { auto ret = guildChannels.emplace(std::make_pair(guild->getId(), std::make_shared(channelId, guild->getName()))); return ret.first->second; @@ -343,7 +343,7 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & } case CHANNEL_PARTY: { - auto party = player->getParty(); + const auto &party = player->getParty(); if (party != nullptr) { auto ret = partyChannels.emplace(std::make_pair(party, std::make_shared(channelId, "Party"))); return ret.first->second; @@ -378,7 +378,7 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & bool Chat::deleteChannel(const std::shared_ptr &player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { - const auto guild = player->getGuild(); + const auto &guild = player->getGuild(); if (guild == nullptr) { return false; } @@ -393,7 +393,7 @@ bool Chat::deleteChannel(const std::shared_ptr &player, uint16_t channel } case CHANNEL_PARTY: { - auto party = player->getParty(); + const auto &party = player->getParty(); if (party == nullptr) { return false; } @@ -443,15 +443,15 @@ bool Chat::removeUserFromChannel(const std::shared_ptr &player, uint16_t } void Chat::removeUserFromAllChannels(const std::shared_ptr &player) { - for (auto &it : normalChannels) { + for (const auto &it : normalChannels) { it.second->removeUser(player); } - for (auto &it : partyChannels) { + for (const auto &it : partyChannels) { it.second->removeUser(player); } - for (auto &it : guildChannels) { + for (const auto &it : guildChannels) { it.second->removeUser(player); } @@ -476,7 +476,7 @@ bool Chat::talkToChannel(const std::shared_ptr &player, SpeakClasses typ } if (channelId == CHANNEL_GUILD) { - GuildRank_ptr rank = player->getGuildRank(); + const auto &rank = player->getGuildRank(); if (rank && rank->level > 1) { type = TALKTYPE_CHANNEL_O; } else if (type != TALKTYPE_CHANNEL_Y) { @@ -527,7 +527,7 @@ ChannelList Chat::getChannelList(const std::shared_ptr &player) { } bool hasPrivate = false; - for (auto &it : privateChannels) { + for (const auto &it : privateChannels) { if (const auto &channel = it.second) { uint32_t guid = player->getGUID(); if (channel->isInvited(guid)) { @@ -549,7 +549,7 @@ ChannelList Chat::getChannelList(const std::shared_ptr &player) { std::shared_ptr Chat::getChannel(const std::shared_ptr &player, uint16_t channelId) { switch (channelId) { case CHANNEL_GUILD: { - const auto guild = player->getGuild(); + const auto &guild = player->getGuild(); if (guild != nullptr) { auto it = guildChannels.find(guild->getId()); if (it != guildChannels.end()) { @@ -560,7 +560,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla } case CHANNEL_PARTY: { - auto party = player->getParty(); + const auto &party = player->getParty(); if (party != nullptr) { auto it = partyChannels.find(party); if (it != partyChannels.end()) { @@ -607,7 +607,7 @@ std::shared_ptr Chat::getChannelById(uint16_t channelId) { } std::shared_ptr Chat::getPrivateChannel(const std::shared_ptr &player) { - for (auto &it : privateChannels) { + for (const auto &it : privateChannels) { if (it.second->getOwner() == player->getGUID()) { return it.second; } diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index 98a08e33c5a..971fca5f81c 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -24,7 +24,7 @@ int32_t Monster::despawnRadius; uint32_t Monster::monsterAutoID = 0x50000001; std::shared_ptr Monster::createMonster(const std::string &name) { - const auto mType = g_monsters().getMonsterType(name); + const auto &mType = g_monsters().getMonsterType(name); if (!mType) { return nullptr; } @@ -130,20 +130,20 @@ void Monster::onAttackedCreatureDisappear(bool) { extraMeleeAttack = true; } -void Monster::onCreatureAppear(std::shared_ptr creature, bool isLogin) { +void Monster::onCreatureAppear(const std::shared_ptr &creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); if (mType->info.creatureAppearEvent != -1) { // onCreatureAppear(self, creature) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Monster::onCreatureAppear - Monster {} creature {}] " "Call stack overflow. Too many lua script calls being nested.", getName(), creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(mType->info.creatureAppearEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -168,20 +168,20 @@ void Monster::onCreatureAppear(std::shared_ptr creature, bool isLogin) } } -void Monster::onRemoveCreature(std::shared_ptr creature, bool isLogout) { +void Monster::onRemoveCreature(const std::shared_ptr &creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); if (mType->info.creatureDisappearEvent != -1) { // onCreatureDisappear(self, creature) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Monster::onCreatureDisappear - Monster {} creature {}] " "Call stack overflow. Too many lua script calls being nested.", getName(), creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(mType->info.creatureDisappearEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -215,14 +215,14 @@ void Monster::onCreatureMove(const std::shared_ptr &creature, const st if (mType->info.creatureMoveEvent != -1) { // onCreatureMove(self, creature, oldPosition, newPosition) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[Monster::onCreatureMove - Monster {} creature {}] " "Call stack overflow. Too many lua script calls being nested.", getName(), creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(mType->info.creatureMoveEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -283,20 +283,20 @@ void Monster::onCreatureMove(const std::shared_ptr &creature, const st } } -void Monster::onCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text) { +void Monster::onCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text) { Creature::onCreatureSay(creature, type, text); if (mType->info.creatureSayEvent != -1) { // onCreatureSay(self, creature, type, message) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Monster {} creature {}] Call stack overflow. Too many lua " "script calls being nested.", getName(), creature->getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(mType->info.creatureSayEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -636,7 +636,7 @@ float Monster::getMitigation() const { return std::min(mitigation, 30.f); } -BlockType_t Monster::blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool /* field = false */) { +BlockType_t Monster::blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool /* field = false */) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor); if (damage != 0) { @@ -748,7 +748,7 @@ bool Monster::isInSpawnLocation() const { return position == masterPos || masterPos == Position(); } -void Monster::onAddCondition(ConditionType_t type) { +void Monster::onAddCondition(const ConditionType_t &type) { onConditionStatusChange(type); } @@ -759,7 +759,7 @@ void Monster::onConditionStatusChange(const ConditionType_t &type) { updateIdleStatus(); } -void Monster::onEndCondition(ConditionType_t type) { +void Monster::onEndCondition(const ConditionType_t &type) { onConditionStatusChange(type); } @@ -769,14 +769,14 @@ void Monster::onThink(uint32_t interval) { if (mType->info.thinkEvent != -1) { // onThink(self, interval) LuaScriptInterface* scriptInterface = mType->info.scriptInterface; - if (!scriptInterface->reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Monster {} Call stack overflow. Too many lua script calls " "being nested.", getName()); return; } - ScriptEnvironment* env = scriptInterface->getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(mType->info.thinkEvent, scriptInterface); lua_State* L = scriptInterface->getLuaState(); @@ -854,7 +854,7 @@ void Monster::onThink(uint32_t interval) { } void Monster::doAttacking(uint32_t interval) { - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature || (isSummon() && attackedCreature.get() == this)) { return; } @@ -1058,7 +1058,7 @@ void Monster::onThinkDefense(uint32_t interval) { continue; } - std::shared_ptr summon = Monster::createMonster(summonBlock.name); + const auto &summon = Monster::createMonster(summonBlock.name); if (summon) { if (g_game().placeCreature(summon, getPosition(), false, summonBlock.force)) { summon->setMaster(static_self_cast(), true); @@ -1129,7 +1129,7 @@ void Monster::pushItems(const std::shared_ptr &tile, const Direction &next // We can not use iterators here since we can push the item to another tile // which will invalidate the iterator. // start from the end to minimize the amount of traffic - if (const auto items = tile->getItemList()) { + if (const auto &items = tile->getItemList()) { uint32_t moveCount = 0; uint32_t removeCount = 0; int32_t downItemSize = tile->getDownItemCount(); @@ -1157,7 +1157,7 @@ bool Monster::pushCreature(const std::shared_ptr &creature) { }; std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); - for (Direction dir : dirList) { + for (const Direction &dir : dirList) { const Position &tryPos = Spells::getCasterPosition(creature, dir); const auto toTile = g_game().map.getTile(tryPos); if (toTile && !toTile->hasFlag(TILESTATE_BLOCKPATH) && g_game().internalMoveCreature(creature, dir) == RETURNVALUE_NOERROR) { @@ -1175,7 +1175,7 @@ void Monster::pushCreatures(const std::shared_ptr &tile) { std::shared_ptr lastPushedMonster = nullptr; for (size_t i = 0; i < creatures->size();) { - std::shared_ptr monster = creatures->at(i)->getMonster(); + const auto &monster = creatures->at(i)->getMonster(); if (monster && monster->isPushable()) { if (monster != lastPushedMonster && Monster::pushCreature(monster)) { lastPushedMonster = monster; @@ -1273,8 +1273,8 @@ void Monster::doFollowCreature(uint32_t &flags, Direction &nextDirection, bool & updateMapCache(); } // target dancing - auto attackedCreature = getAttackedCreature(); - auto followCreature = getFollowCreature(); + const auto &attackedCreature = getAttackedCreature(); + const auto &followCreature = getFollowCreature(); if (attackedCreature && attackedCreature == followCreature) { if (isFleeing()) { result = getDanceStep(getPosition(), nextDirection, false, false); @@ -1293,7 +1293,7 @@ bool Monster::getRandomStep(const Position &creaturePos, Direction &moveDirectio }; std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); - for (Direction dir : dirList) { + for (const Direction &dir : dirList) { if (canWalkTo(creaturePos, dir)) { moveDirection = dir; return true; @@ -1303,7 +1303,7 @@ bool Monster::getRandomStep(const Position &creaturePos, Direction &moveDirectio } bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection, bool keepAttack /*= true*/, bool keepDistance /*= true*/) { - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature) { return false; } @@ -1891,7 +1891,7 @@ bool Monster::canWalkTo(Position pos, Direction moveDirection) { return false; } - const auto tile = g_game().map.getTile(pos); + const auto &tile = g_game().map.getTile(pos); if (tile && tile->getTopVisibleCreature(getMonster()) == nullptr && tile->queryAdd(0, getMonster(), 1, FLAG_PATHFINDING | FLAG_IGNOREFIELDDAMAGE) == RETURNVALUE_NOERROR) { return true; } @@ -1923,14 +1923,14 @@ void Monster::death(std::shared_ptr) { } } -std::shared_ptr Monster::getCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature) { - std::shared_ptr corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); +std::shared_ptr Monster::getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) { + const auto &corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse) { if (mostDamageCreature) { if (mostDamageCreature->getPlayer()) { corpse->setAttribute(ItemAttribute_t::CORPSEOWNER, mostDamageCreature->getID()); } else { - std::shared_ptr mostDamageCreatureMaster = mostDamageCreature->getMaster(); + const auto &mostDamageCreatureMaster = mostDamageCreature->getMaster(); if (mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer()) { corpse->setAttribute(ItemAttribute_t::CORPSEOWNER, mostDamageCreatureMaster->getID()); } @@ -1976,7 +1976,7 @@ bool Monster::getCombatValues(int32_t &min, int32_t &max) { void Monster::updateLookDirection() { Direction newDir = getDirection(); - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature) { return; } @@ -2033,7 +2033,7 @@ void Monster::updateLookDirection() { g_game().internalCreatureTurn(getMonster(), newDir); } -void Monster::dropLoot(std::shared_ptr corpse, std::shared_ptr) { +void Monster::dropLoot(const std::shared_ptr &corpse, std::shared_ptr) { if (corpse && lootDrop) { // Only fiendish drops sliver if (ForgeClassifications_t classification = getMonsterForgeClassification(); @@ -2044,7 +2044,7 @@ void Monster::dropLoot(std::shared_ptr corpse, std::shared_ptr(uniform_random(minSlivers, maxSlivers)); - std::shared_ptr sliver = Item::CreateItem(ITEM_FORGE_SLIVER, sliverCount); + const auto &sliver = Item::CreateItem(ITEM_FORGE_SLIVER, sliverCount); if (g_game().internalAddItem(corpse, sliver) != RETURNVALUE_NOERROR) { corpse->internalAddThing(sliver); } @@ -2060,7 +2060,7 @@ void Monster::setNormalCreatureLight() { internalLight = mType->info.light; } -void Monster::drainHealth(std::shared_ptr attacker, int32_t damage) { +void Monster::drainHealth(const std::shared_ptr &attacker, int32_t damage) { Creature::drainHealth(attacker, damage); if (damage > 0 && randomStepping) { @@ -2084,7 +2084,7 @@ void Monster::changeHealth(int32_t healthChange, bool sendHealthChange /* = true Creature::changeHealth(healthChange, sendHealthChange); } -bool Monster::challengeCreature(std::shared_ptr creature, int targetChangeCooldown) { +bool Monster::challengeCreature(const std::shared_ptr &creature, int targetChangeCooldown) { if (isSummon()) { return false; } @@ -2094,7 +2094,7 @@ bool Monster::challengeCreature(std::shared_ptr creature, int targetCh challengeFocusDuration = targetChangeCooldown; targetChangeTicks = 0; // Wheel of destiny - const auto player = creature ? creature->getPlayer() : nullptr; + const auto &player = creature ? creature->getPlayer() : nullptr; if (player && !player->isRemoved()) { player->wheel()->healIfBattleHealingActive(); } diff --git a/src/creatures/monsters/monster.hpp b/src/creatures/monsters/monster.hpp index 9a43bc614ad..be457c8804d 100644 --- a/src/creatures/monsters/monster.hpp +++ b/src/creatures/monsters/monster.hpp @@ -140,19 +140,19 @@ class Monster final : public Creature { bool canWalkOnFieldType(CombatType_t combatType) const; void onAttackedCreatureDisappear(bool isLogout) override; - void onCreatureAppear(std::shared_ptr creature, bool isLogin) override; - void onRemoveCreature(std::shared_ptr creature, bool isLogout) override; + void onCreatureAppear(const std::shared_ptr &creature, bool isLogin) override; + void onRemoveCreature(const std::shared_ptr &creature, bool isLogout) override; void onCreatureMove(const std::shared_ptr &creature, const std::shared_ptr &newTile, const Position &newPos, const std::shared_ptr &oldTile, const Position &oldPos, bool teleport) override; - void onCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text) override; + void onCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text) override; - void drainHealth(std::shared_ptr attacker, int32_t damage) override; + void drainHealth(const std::shared_ptr &attacker, int32_t damage) override; void changeHealth(int32_t healthChange, bool sendHealthChange = true) override; bool getNextStep(Direction &direction, uint32_t &flags) override; void onFollowCreatureComplete(const std::shared_ptr &creature) override; void onThink(uint32_t interval) override; - bool challengeCreature(std::shared_ptr creature, int targetChangeCooldown) override; + bool challengeCreature(const std::shared_ptr &creature, int targetChangeCooldown) override; bool changeTargetDistance(int32_t distance, uint32_t duration = 12000); bool isChallenged() const { @@ -282,7 +282,7 @@ class Monster final : public Creature { void clearTargetList(); void clearFriendList(); - BlockType_t blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; + BlockType_t blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; static uint32_t monsterAutoID; @@ -414,7 +414,7 @@ class Monster final : public Creature { bool removeTarget(const std::shared_ptr &creature); void death(std::shared_ptr lastHitCreature) override; - std::shared_ptr getCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature) override; + std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) override; void setIdle(bool idle); void updateIdleStatus(); @@ -422,8 +422,8 @@ class Monster final : public Creature { return isIdle; } - void onAddCondition(ConditionType_t type) override; - void onEndCondition(ConditionType_t type) override; + void onAddCondition(const ConditionType_t &type) override; + void onEndCondition(const ConditionType_t &type) override; bool canUseAttack(const Position &pos, const std::shared_ptr &target) const; bool canUseSpell(const Position &pos, const Position &targetPos, const spellBlock_t &sb, uint32_t interval, bool &inRange, bool &resetTicks); @@ -452,7 +452,7 @@ class Monster final : public Creature { uint16_t getLookCorpse() const override { return mType->info.lookcorpse; } - void dropLoot(std::shared_ptr corpse, std::shared_ptr lastHitCreature) override; + void dropLoot(const std::shared_ptr &corpse, std::shared_ptr lastHitCreature) override; void getPathSearchParams(const std::shared_ptr &creature, FindPathParams &fpp) override; bool useCacheMap() const override { // return !randomStepping; diff --git a/src/creatures/monsters/monsters.cpp b/src/creatures/monsters/monsters.cpp index c0d36694363..eddde3ff749 100644 --- a/src/creatures/monsters/monsters.cpp +++ b/src/creatures/monsters/monsters.cpp @@ -43,7 +43,7 @@ bool MonsterType::canSpawn(const Position &pos) const { } std::shared_ptr Monsters::getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) { - std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, 0, 0)->static_self_cast(); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, 0, 0)->static_self_cast(); condition->setParam(CONDITION_PARAM_TICKINTERVAL, tickInterval); condition->setParam(CONDITION_PARAM_MINVALUE, minDamage); condition->setParam(CONDITION_PARAM_MAXVALUE, maxDamage); @@ -143,7 +143,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel conditionType = CONDITION_PARALYZE; } - std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, duration, 0)->static_self_cast(); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, duration, 0)->static_self_cast(); float multiplier = 1.0f + static_cast(speedChange) / 1000.0f; condition->setFormulaVars(multiplier / 2, 40, multiplier, 40); combatPtr->addCondition(condition); @@ -154,7 +154,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel duration = spell->duration; } - std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)->static_self_cast(); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)->static_self_cast(); if (!spell->outfitMonster.empty()) { condition->setLazyMonsterOutfit(spell->outfitMonster); @@ -178,7 +178,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel duration = spell->duration; } - std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_INVISIBLE, duration, 0); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_INVISIBLE, duration, 0); combatPtr->setParam(COMBAT_PARAM_AGGRESSIVE, 0); combatPtr->addCondition(condition); } else if (spellName == "drunk") { @@ -188,7 +188,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel duration = spell->duration; } - std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_DRUNK, duration, 0); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_DRUNK, duration, 0); combatPtr->addCondition(condition); } else if (spellName == "soulwars fear" || spellName == "fear") { int32_t duration = 6000; @@ -197,7 +197,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel duration = spell->duration; } - const auto condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_FEARED, duration, 0); + const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_FEARED, duration, 0); combatPtr->addCondition(condition); } else if (spellName == "firefield") { combatPtr->setParam(COMBAT_PARAM_CREATEITEM, ITEM_FIREFIELD_PVP_FULL); @@ -248,7 +248,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel maxDamage = minDamage; } - std::shared_ptr condition = getDamageCondition(spell->conditionType, maxDamage, minDamage, startDamage, tickInterval); + const auto &condition = getDamageCondition(spell->conditionType, maxDamage, minDamage, startDamage, tickInterval); combatPtr->addCondition(condition); } @@ -307,7 +307,7 @@ std::shared_ptr Monsters::getMonsterType(const std::string &name, b } std::shared_ptr Monsters::getMonsterTypeByRaceId(uint16_t raceId, bool isBoss /* = false*/) const { - auto bossType = g_ioBosstiary().getMonsterTypeByBossRaceId(raceId); + const auto &bossType = g_ioBosstiary().getMonsterTypeByBossRaceId(raceId); if (isBoss && bossType) { return bossType; } diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index 960cb98acf2..46a2f56a8e0 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -41,7 +41,8 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { std::string boostedNameGet = g_game().getBoostedMonsterName(); - for (auto spawnMonsterNode : doc.child("monsters").children()) { + spawnMonsterList.reserve(10000); + for (const auto &spawnMonsterNode : doc.child("monsters").children()) { Position centerPos( pugi::cast(spawnMonsterNode.attribute("centerx").value()), pugi::cast(spawnMonsterNode.attribute("centery").value()), @@ -63,7 +64,7 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { SpawnMonster &spawnMonster = spawnMonsterList.emplace_back(centerPos, radius); - for (auto childMonsterNode : spawnMonsterNode.children()) { + for (const auto &childMonsterNode : spawnMonsterNode.children()) { if (strcasecmp(childMonsterNode.name(), "monster") == 0) { pugi::xml_attribute nameAttribute = childMonsterNode.attribute("name"); if (!nameAttribute) { @@ -303,7 +304,7 @@ bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Dire break; } } - const auto monsterType = g_monsters().getMonsterType(variant + name); + const auto &monsterType = g_monsters().getMonsterType(variant + name); if (!monsterType) { g_logger().error("Can not find {}", name); return false; diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 39be8029dce..3acd12e672f 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -67,7 +67,7 @@ bool Npc::canInteract(const Position &pos, uint32_t range /* = 4 */) { return Creature::canSee(getPosition(), pos, range, range); } -void Npc::onCreatureAppear(std::shared_ptr creature, bool isLogin) { +void Npc::onCreatureAppear(const std::shared_ptr &creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); if (auto player = creature->getPlayer()) { @@ -86,7 +86,7 @@ void Npc::onCreatureAppear(std::shared_ptr creature, bool isLogin) { } } -void Npc::onRemoveCreature(std::shared_ptr creature, bool isLogout) { +void Npc::onRemoveCreature(const std::shared_ptr &creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); // onCreatureDisappear(self, creature) @@ -100,7 +100,7 @@ void Npc::onRemoveCreature(std::shared_ptr creature, bool isLogout) { return; } - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { removeShopPlayer(player->getGUID()); onPlayerDisappear(player); } @@ -160,7 +160,7 @@ void Npc::onPlayerDisappear(const std::shared_ptr &player) { } } -void Npc::onCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text) { +void Npc::onCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text) { Creature::onCreatureSay(creature, type, text); if (!creature->getPlayer()) { @@ -308,12 +308,12 @@ void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemI } void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, uint64_t totalPrice) { - const auto player = g_game().getPlayerByID(playerId); + const auto &player = g_game().getPlayerByID(playerId); if (!player) { return; } if (itemId == ITEM_GOLD_POUCH) { - auto container = player->getLootPouch(); + const auto &container = player->getLootPouch(); if (!container) { return; } @@ -325,7 +325,7 @@ void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, u hasMore = true; break; } - auto item = *it; + const auto &item = *it; if (!item) { continue; } @@ -336,7 +336,7 @@ void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, u toSellCount += item->getItemAmount(); } } - for (auto &[m_itemId, amount] : toSell) { + for (const auto &[m_itemId, amount] : toSell) { onPlayerSellItem(player, m_itemId, 0, amount, ignore, totalPrice, container); } auto ss = std::stringstream(); @@ -417,7 +417,7 @@ void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemI } g_metrics().addCounter("balance_increase", totalCost, { { "player", player->getName() }, { "context", "npc_sale" } }); } else { - std::shared_ptr newItem = Item::CreateItem(getCurrency(), totalCost); + const auto &newItem = Item::CreateItem(getCurrency(), totalCost); if (newItem) { g_game().internalPlayerAddItem(player, newItem, true); } @@ -462,7 +462,7 @@ void Npc::onPlayerCheckItem(const std::shared_ptr &player, uint16_t item } void Npc::onPlayerCloseChannel(const std::shared_ptr &creature) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (!player) { return; } @@ -572,7 +572,7 @@ bool Npc::isInSpawnRange(const Position &pos) const { } void Npc::setPlayerInteraction(uint32_t playerId, uint16_t topicId /*= 0*/) { - std::shared_ptr creature = g_game().getCreatureByID(playerId); + const auto &creature = g_game().getCreatureByID(playerId); if (!creature) { return; } diff --git a/src/creatures/npcs/npc.hpp b/src/creatures/npcs/npc.hpp index 7f5fc7d54aa..b6918eec0cd 100644 --- a/src/creatures/npcs/npc.hpp +++ b/src/creatures/npcs/npc.hpp @@ -144,10 +144,10 @@ class Npc final : public Creature { return it->second == topicId; } - void onCreatureAppear(std::shared_ptr creature, bool isLogin) override; - void onRemoveCreature(std::shared_ptr creature, bool isLogout) override; + void onCreatureAppear(const std::shared_ptr &creature, bool isLogin) override; + void onRemoveCreature(const std::shared_ptr &creature, bool isLogout) override; void onCreatureMove(const std::shared_ptr &creature, const std::shared_ptr &newTile, const Position &newPos, const std::shared_ptr &oldTile, const Position &oldPos, bool teleport) override; - void onCreatureSay(std::shared_ptr creature, SpeakClasses type, const std::string &text) override; + void onCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text) override; void onThink(uint32_t interval) override; void onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemid, uint8_t count, uint16_t amount, bool ignore, bool inBackpacks); void onPlayerSellAllLoot(uint32_t playerId, uint16_t itemid, bool ignore, uint64_t totalPrice); diff --git a/src/creatures/npcs/spawns/spawn_npc.cpp b/src/creatures/npcs/spawns/spawn_npc.cpp index 8f7d32aff98..b2fc33e2cae 100644 --- a/src/creatures/npcs/spawns/spawn_npc.cpp +++ b/src/creatures/npcs/spawns/spawn_npc.cpp @@ -37,7 +37,7 @@ bool SpawnsNpc::loadFromXml(const std::string &fileNpcName) { setFileName(fileNpcName); setLoaded(true); - for (auto spawnNode : doc.child("npcs").children()) { + for (const auto &spawnNode : doc.child("npcs").children()) { Position centerPos( pugi::cast(spawnNode.attribute("centerx").value()), pugi::cast(spawnNode.attribute("centery").value()), @@ -59,7 +59,7 @@ bool SpawnsNpc::loadFromXml(const std::string &fileNpcName) { const auto &spawnNpc = spawnNpcList.emplace_back(std::make_shared(centerPos, radius)); - for (auto childNode : spawnNode.children()) { + for (const auto &childNode : spawnNode.children()) { if (strcasecmp(childNode.name(), "npc") == 0) { pugi::xml_attribute nameAttribute = childNode.attribute("name"); if (!nameAttribute) { diff --git a/src/creatures/players/achievement/player_achievement.cpp b/src/creatures/players/achievement/player_achievement.cpp index cd0735ab54c..cad3c9b2820 100644 --- a/src/creatures/players/achievement/player_achievement.cpp +++ b/src/creatures/players/achievement/player_achievement.cpp @@ -23,7 +23,7 @@ bool PlayerAchievement::add(uint16_t id, bool message /* = true*/, uint32_t time return false; } - const Achievement &achievement = g_game().getAchievementById(id); + const auto &achievement = g_game().getAchievementById(id); if (achievement.id == 0) { return false; } @@ -45,7 +45,7 @@ bool PlayerAchievement::remove(uint16_t id) { return false; } - Achievement achievement = g_game().getAchievementById(id); + auto achievement = g_game().getAchievementById(id); if (achievement.id == 0) { return false; } @@ -118,7 +118,7 @@ void PlayerAchievement::sendUnlockedSecretAchievements() { std::vector> achievementsUnlocked; uint16_t unlockedSecret = 0; for (const auto &[achievId, achievCreatedTime] : getUnlockedAchievements()) { - Achievement achievement = g_game().getAchievementById(achievId); + const auto &achievement = g_game().getAchievementById(achievId); if (achievement.id == 0) { continue; } diff --git a/src/creatures/players/cyclopedia/player_badge.cpp b/src/creatures/players/cyclopedia/player_badge.cpp index 639640b2ffe..ba557317921 100644 --- a/src/creatures/players/cyclopedia/player_badge.cpp +++ b/src/creatures/players/cyclopedia/player_badge.cpp @@ -10,7 +10,7 @@ #include "pch.hpp" #include "player_badge.hpp" - +#include "enums/player_cyclopedia.hpp" #include "creatures/players/player.hpp" #include "game/game.hpp" #include "kv/kv.hpp" diff --git a/src/creatures/players/cyclopedia/player_badge.hpp b/src/creatures/players/cyclopedia/player_badge.hpp index ed37a69faa8..b0973e10b67 100644 --- a/src/creatures/players/cyclopedia/player_badge.hpp +++ b/src/creatures/players/cyclopedia/player_badge.hpp @@ -9,11 +9,11 @@ #pragma once -#include "enums/player_cyclopedia.hpp" - class Player; class KV; +enum class CyclopediaBadge_t : uint8_t; + struct Badge { uint8_t m_id = 0; CyclopediaBadge_t m_type {}; diff --git a/src/creatures/players/cyclopedia/player_cyclopedia.hpp b/src/creatures/players/cyclopedia/player_cyclopedia.hpp index 32c446cc368..01c7fa7967c 100644 --- a/src/creatures/players/cyclopedia/player_cyclopedia.hpp +++ b/src/creatures/players/cyclopedia/player_cyclopedia.hpp @@ -9,9 +9,6 @@ #pragma once -#include "creatures/creatures_definitions.hpp" -#include "enums/player_cyclopedia.hpp" - class Player; class KV; diff --git a/src/creatures/players/cyclopedia/player_title.hpp b/src/creatures/players/cyclopedia/player_title.hpp index 0530fcc083d..5a18ce94c81 100644 --- a/src/creatures/players/cyclopedia/player_title.hpp +++ b/src/creatures/players/cyclopedia/player_title.hpp @@ -9,11 +9,7 @@ #pragma once -#include - -#include "creatures/creatures_definitions.hpp" #include "enums/player_cyclopedia.hpp" -#include "enums/account_group_type.hpp" class Player; class KV; diff --git a/src/creatures/players/grouping/familiars.cpp b/src/creatures/players/grouping/familiars.cpp index 6312aaa285d..47780dcf07d 100644 --- a/src/creatures/players/grouping/familiars.cpp +++ b/src/creatures/players/grouping/familiars.cpp @@ -12,8 +12,6 @@ #include "creatures/players/grouping/familiars.hpp" #include "lib/di/container.hpp" #include "config/configmanager.hpp" -#include "utils/pugicast.hpp" -#include "utils/tools.hpp" Familiars &Familiars::getInstance() { return inject(); @@ -36,7 +34,7 @@ bool Familiars::loadFromXml() { return false; } - for (auto familiarsNode : doc.child("familiars").children()) { + for (const auto &familiarsNode : doc.child("familiars").children()) { pugi::xml_attribute attr; if ((attr = familiarsNode.attribute("enabled")) && !attr.as_bool()) { continue; @@ -74,7 +72,7 @@ bool Familiars::loadFromXml() { } std::shared_ptr Familiars::getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const { - if (auto it = std::find_if(familiars[vocation].begin(), familiars[vocation].end(), [lookType](auto familiar_it) { + if (auto it = std::find_if(familiars[vocation].begin(), familiars[vocation].end(), [lookType](const auto &familiar_it) { return familiar_it->lookType == lookType; }); it != familiars[vocation].end()) { diff --git a/src/creatures/players/grouping/familiars.hpp b/src/creatures/players/grouping/familiars.hpp index 9eda7d95ba2..f567bdafc4d 100644 --- a/src/creatures/players/grouping/familiars.hpp +++ b/src/creatures/players/grouping/familiars.hpp @@ -9,9 +9,6 @@ #pragma once -#include "declarations.hpp" -#include "lib/di/container.hpp" - struct FamiliarEntry { constexpr explicit FamiliarEntry(uint16_t initLookType) : lookType(initLookType) { } diff --git a/src/creatures/players/grouping/groups.cpp b/src/creatures/players/grouping/groups.cpp index c4dab4a9039..13ee3e2e17d 100644 --- a/src/creatures/players/grouping/groups.cpp +++ b/src/creatures/players/grouping/groups.cpp @@ -12,15 +12,13 @@ #include "config/configmanager.hpp" #include "game/game.hpp" #include "creatures/players/grouping/groups.hpp" -#include "utils/pugicast.hpp" -#include "utils/tools.hpp" namespace ParsePlayerFlagMap { // Initialize the map with all the values from the PlayerFlags_t enumeration phmap::flat_hash_map initParsePlayerFlagMap() { phmap::flat_hash_map map; // Iterate through all values of the PlayerFlags_t enumeration - for (auto value : magic_enum::enum_values()) { + for (const auto &value : magic_enum::enum_values()) { // Get the string representation of the current enumeration value std::string name(magic_enum::enum_name(value).data()); // Convert the string to lowercase @@ -51,7 +49,7 @@ bool Groups::reload() { void parseGroupFlags(Group &group, const pugi::xml_node &groupNode) { if (pugi::xml_node node = groupNode.child("flags")) { - for (auto flagNode : node.children()) { + for (const auto &flagNode : node.children()) { pugi::xml_attribute attr = flagNode.first_attribute(); if (!attr || !attr.as_bool()) { continue; @@ -76,7 +74,7 @@ bool Groups::load() { return false; } - for (auto groupNode : doc.child("groups").children()) { + for (const auto &groupNode : doc.child("groups").children()) { Group group; group.id = pugi::cast(groupNode.attribute("id").value()); group.name = groupNode.attribute("name").as_string(); diff --git a/src/creatures/players/grouping/groups.hpp b/src/creatures/players/grouping/groups.hpp index af319e95772..a0ac5674b5e 100644 --- a/src/creatures/players/grouping/groups.hpp +++ b/src/creatures/players/grouping/groups.hpp @@ -9,8 +9,6 @@ #pragma once -#include "declarations.hpp" - struct Group { std::string name; std::array flags { false }; diff --git a/src/creatures/players/grouping/guild.cpp b/src/creatures/players/grouping/guild.cpp index bbd662d1a1d..c7fde5979a4 100644 --- a/src/creatures/players/grouping/guild.cpp +++ b/src/creatures/players/grouping/guild.cpp @@ -33,7 +33,7 @@ void Guild::removeMember(const std::shared_ptr &player) { } GuildRank_ptr Guild::getRankById(uint32_t rankId) { - for (auto rank : ranks) { + for (const auto &rank : ranks) { if (rank->id == rankId) { return rank; } @@ -42,7 +42,7 @@ GuildRank_ptr Guild::getRankById(uint32_t rankId) { } GuildRank_ptr Guild::getRankByName(const std::string &guildName) const { - for (auto rank : ranks) { + for (const auto &rank : ranks) { if (rank->name == guildName) { return rank; } @@ -51,7 +51,7 @@ GuildRank_ptr Guild::getRankByName(const std::string &guildName) const { } GuildRank_ptr Guild::getRankByLevel(uint8_t level) const { - for (auto rank : ranks) { + for (const auto &rank : ranks) { if (rank->level == level) { return rank; } diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index 3cf7936e69d..242fff7d1ae 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -7,8 +7,6 @@ * Website: https://docs.opentibiabr.com/ */ -#include - #include "pch.hpp" #include "creatures/players/grouping/party.hpp" @@ -164,7 +162,7 @@ bool Party::leaveParty(const std::shared_ptr &player) { } bool Party::passPartyLeadership(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader || !player || leader == player || player->getParty().get() != this) { return false; } @@ -205,7 +203,7 @@ bool Party::passPartyLeadership(const std::shared_ptr &player) { } bool Party::joinParty(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return false; } @@ -262,7 +260,7 @@ bool Party::joinParty(const std::shared_ptr &player) { } bool Party::removeInvite(const std::shared_ptr &player, bool removeFromPlayer /* = true*/) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return false; } @@ -295,7 +293,7 @@ bool Party::removeInvite(const std::shared_ptr &player, bool removeFromP } void Party::revokeInvitation(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -312,7 +310,7 @@ void Party::revokeInvitation(const std::shared_ptr &player) { } bool Party::invitePlayer(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return false; } @@ -356,11 +354,11 @@ bool Party::isPlayerInvited(const std::shared_ptr &player) const { } void Party::updateAllPartyIcons() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } - auto members = getMembers(); + const auto &members = getMembers(); for (const auto &member : members) { for (const auto &otherMember : members) { member->sendPartyCreatureShield(otherMember); @@ -374,7 +372,7 @@ void Party::updateAllPartyIcons() { } void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string &msg, bool sendToInvitations /*= false*/) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -419,7 +417,7 @@ const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) { } bool Party::setSharedExperience(const std::shared_ptr &player, bool newSharedExpActive, bool silent /*= false*/) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!player || leader != player) { return false; } @@ -447,7 +445,7 @@ bool Party::setSharedExperience(const std::shared_ptr &player, bool newS } void Party::shareExperience(uint64_t experience, const std::shared_ptr &target /* = nullptr*/) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -467,7 +465,7 @@ bool Party::canUseSharedExperience(const std::shared_ptr &player) { } SharedExpStatus_t Party::getMemberSharedExperienceStatus(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return SHAREDEXP_EMPTYPARTY; } @@ -497,7 +495,7 @@ float Party::shareRangeMultiplier() const { } uint32_t Party::getHighestLevel() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return 0; } @@ -516,7 +514,7 @@ uint32_t Party::getMinLevel() { } uint32_t Party::getLowestLevel() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return 0; } @@ -543,7 +541,7 @@ bool Party::isPlayerActive(const std::shared_ptr &player) { } SharedExpStatus_t Party::getSharedExperienceStatus() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return SHAREDEXP_EMPTYPARTY; } @@ -577,12 +575,12 @@ void Party::clearPlayerPoints(const std::shared_ptr &player) { } bool Party::canOpenCorpse(uint32_t ownerId) const { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return false; } - if (const auto player = g_game().getPlayerByID(ownerId)) { + if (const auto &player = g_game().getPlayerByID(ownerId)) { return leader->getID() == ownerId || player->getParty().get() == this; } return false; @@ -615,7 +613,7 @@ void Party::showPlayerStatus(const std::shared_ptr &player, const std::s } void Party::updatePlayerStatus(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -638,7 +636,7 @@ void Party::updatePlayerStatus(const std::shared_ptr &player) { } void Party::updatePlayerStatus(const std::shared_ptr &player, const Position &oldPos, const Position &newPos) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -666,7 +664,7 @@ void Party::updatePlayerStatus(const std::shared_ptr &player, const Posi } void Party::updatePlayerHealth(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t healthPercent) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -688,7 +686,7 @@ void Party::updatePlayerHealth(const std::shared_ptr &player, const std: } void Party::updatePlayerMana(const std::shared_ptr &player, uint8_t manaPercent) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -707,7 +705,7 @@ void Party::updatePlayerMana(const std::shared_ptr &player, uint8_t mana } void Party::updatePlayerVocation(const std::shared_ptr &player) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -726,7 +724,7 @@ void Party::updatePlayerVocation(const std::shared_ptr &player) { } void Party::updateTrackerAnalyzer() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -739,7 +737,7 @@ void Party::updateTrackerAnalyzer() { } void Party::addPlayerLoot(const std::shared_ptr &player, const std::shared_ptr &item) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -767,12 +765,12 @@ void Party::addPlayerLoot(const std::shared_ptr &player, const std::shar } void Party::addPlayerSupply(const std::shared_ptr &player, const std::shared_ptr &item) { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } - std::shared_ptr playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); + auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared(player->getID(), player->getName()); membersData.push_back(playerAnalyzer); @@ -816,7 +814,7 @@ void Party::addPlayerHealing(const std::shared_ptr &player, uint64_t amo } void Party::switchAnalyzerPriceType() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -833,7 +831,7 @@ void Party::resetAnalyzer() { } void Party::reloadPrices() { - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return; } @@ -846,12 +844,12 @@ void Party::reloadPrices() { } analyzer->lootPrice = 0; - for (const auto it : analyzer->lootMap) { + for (const auto &it : analyzer->lootMap) { analyzer->lootPrice += leader->getItemCustomPrice(it.first) * it.second; } analyzer->supplyPrice = 0; - for (const auto it : analyzer->supplyMap) { + for (const auto &it : analyzer->supplyMap) { analyzer->supplyPrice += leader->getItemCustomPrice(it.first, true) * it.second; } } diff --git a/src/creatures/players/imbuements/imbuements.cpp b/src/creatures/players/imbuements/imbuements.cpp index 261b348aa61..c8073304369 100644 --- a/src/creatures/players/imbuements/imbuements.cpp +++ b/src/creatures/players/imbuements/imbuements.cpp @@ -35,7 +35,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { } loaded = true; - for (auto baseNode : doc.child("imbuements").children()) { + for (const auto &baseNode : doc.child("imbuements").children()) { pugi::xml_attribute attr; // Base for imbue if (strcasecmp(baseNode.name(), "base") == 0) { @@ -139,7 +139,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { } imbuement.name = nameBase.value(); - for (auto childNode : baseNode.children()) { + for (const auto &childNode : baseNode.children()) { if (!(attr = childNode.attribute("key"))) { g_logger().warn("Missing key attribute in imbuement id: {}", runningid); continue; diff --git a/src/creatures/players/imbuements/imbuements.hpp b/src/creatures/players/imbuements/imbuements.hpp index 1aa93eff67c..27868c99cc3 100644 --- a/src/creatures/players/imbuements/imbuements.hpp +++ b/src/creatures/players/imbuements/imbuements.hpp @@ -12,7 +12,6 @@ #include "creatures/players/player.hpp" #include "declarations.hpp" #include "lib/di/container.hpp" -#include "utils/tools.hpp" class Player; class Item; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 33d9ce6f021..3f677ccb48a 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -1700,7 +1700,7 @@ void Player::onRemoveTileItem(std::shared_ptr fromTile, const Position &po checkLootContainers(item->getContainer()); } -void Player::onCreatureAppear(std::shared_ptr creature, bool isLogin) { +void Player::onCreatureAppear(const std::shared_ptr &creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); if (isLogin && creature == getPlayer()) { @@ -1841,7 +1841,7 @@ void Player::onAttackedCreatureChangeZone(ZoneType_t zone) { } } -void Player::onRemoveCreature(std::shared_ptr creature, bool isLogout) { +void Player::onRemoveCreature(const std::shared_ptr &creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); if (auto player = getPlayer(); player == creature) { @@ -2284,7 +2284,7 @@ void Player::removeMessageBuffer() { } } -void Player::drainHealth(std::shared_ptr attacker, int32_t damage) { +void Player::drainHealth(const std::shared_ptr &attacker, int32_t damage) { if (PLAYER_SOUND_HEALTH_CHANGE >= static_cast(uniform_random(1, 100))) { g_game().sendSingleSoundEffect(static_self_cast()->getPosition(), sex == PLAYERSEX_FEMALE ? SoundEffect_t::HUMAN_FEMALE_BARK : SoundEffect_t::HUMAN_MALE_BARK, getPlayer()); } @@ -2633,7 +2633,7 @@ bool Player::hasShield() const { return false; } -BlockType_t Player::blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool field /* = false*/) { +BlockType_t Player::blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense /* = false*/, bool checkArmor /* = false*/, bool field /* = false*/) { BlockType_t blockType = Creature::blockHit(attacker, combatType, damage, checkDefense, checkArmor, field); if (attacker) { sendCreatureSquare(attacker, SQ_COLOR_BLACK); @@ -3015,7 +3015,7 @@ bool Player::dropCorpse(std::shared_ptr lastHitCreature, std::shared_p return false; } -std::shared_ptr Player::getCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature) { +std::shared_ptr Player::getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) { std::shared_ptr corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse && corpse->getContainer()) { std::ostringstream ss; @@ -4523,7 +4523,7 @@ void Player::updateItemsLight(bool internal /*=false*/) { } } -void Player::onAddCondition(ConditionType_t type) { +void Player::onAddCondition(const ConditionType_t &type) { Creature::onAddCondition(type); if (type == CONDITION_OUTFIT && isMounted()) { @@ -4534,7 +4534,7 @@ void Player::onAddCondition(ConditionType_t type) { sendIcons(); } -void Player::onAddCombatCondition(ConditionType_t type) { +void Player::onAddCombatCondition(const ConditionType_t &type) { if (IsConditionSuppressible(type)) { updateLastConditionTime(type); } @@ -4592,7 +4592,7 @@ void Player::onAddCombatCondition(ConditionType_t type) { } } -void Player::onEndCondition(ConditionType_t type) { +void Player::onEndCondition(const ConditionType_t &type) { Creature::onEndCondition(type); if (type == CONDITION_INFIGHT) { diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 13be5603b9a..b7ff5e1d3d2 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -898,7 +898,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isPzLocked() const { return pzLocked; } - BlockType_t blockHit(std::shared_ptr attacker, CombatType_t combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; + BlockType_t blockHit(const std::shared_ptr &attacker, const CombatType_t &combatType, int32_t &damage, bool checkDefense = false, bool checkArmor = false, bool field = false) override; void doAttacking(uint32_t interval) override; bool hasExtraSwing() override { return lastAttack > 0 && !checkLastAttackWithin(getAttackSpeed()); @@ -974,7 +974,7 @@ class Player final : public Creature, public Cylinder, public Bankable { int32_t getWeaponSkill(const std::shared_ptr &item) const; void getShieldAndWeapon(std::shared_ptr &shield, std::shared_ptr &weapon) const; - void drainHealth(std::shared_ptr attacker, int32_t damage) override; + void drainHealth(const std::shared_ptr &attacker, int32_t damage) override; void drainMana(std::shared_ptr attacker, int32_t manaLoss) override; void addManaSpent(uint64_t amount); void addSkillAdvance(skills_t skill, uint64_t count); @@ -990,9 +990,9 @@ class Player final : public Creature, public Cylinder, public Bankable { uint64_t getGainedExperience(std::shared_ptr attacker) const override; // combat event functions - void onAddCondition(ConditionType_t type) override; - void onAddCombatCondition(ConditionType_t type) override; - void onEndCondition(ConditionType_t type) override; + void onAddCondition(const ConditionType_t &type) override; + void onAddCombatCondition(const ConditionType_t &type) override; + void onEndCondition(const ConditionType_t &type) override; void onCombatRemoveCondition(std::shared_ptr condition) override; void onAttackedCreature(std::shared_ptr target) override; void onAttacked() override; @@ -1317,8 +1317,8 @@ class Player final : public Creature, public Cylinder, public Bankable { void onUpdateTileItem(std::shared_ptr tile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType) override; void onRemoveTileItem(std::shared_ptr tile, const Position &pos, const ItemType &iType, std::shared_ptr item) override; - void onCreatureAppear(std::shared_ptr creature, bool isLogin) override; - void onRemoveCreature(std::shared_ptr creature, bool isLogout) override; + void onCreatureAppear(const std::shared_ptr &creature, bool isLogin) override; + void onRemoveCreature(const std::shared_ptr &creature, bool isLogout) override; void onCreatureMove(const std::shared_ptr &creature, const std::shared_ptr &newTile, const Position &newPos, const std::shared_ptr &oldTile, const Position &oldPos, bool teleport) override; void onEquipInventory(); @@ -2690,7 +2690,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool spawn(); void despawn(); bool dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; - std::shared_ptr getCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature) override; + std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) override; // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; diff --git a/src/creatures/players/storages/storages.cpp b/src/creatures/players/storages/storages.cpp index 7fe925ce9e3..2ec4bde5543 100644 --- a/src/creatures/players/storages/storages.cpp +++ b/src/creatures/players/storages/storages.cpp @@ -10,8 +10,12 @@ #include "pch.hpp" #include "creatures/players/storages/storages.hpp" - #include "config/configmanager.hpp" +#include "lib/di/container.hpp" + +Storages &Storages::getInstance() { + return inject(); +} bool Storages::loadFromXML() { pugi::xml_document doc; @@ -27,7 +31,7 @@ bool Storages::loadFromXML() { std::vector> ranges; - for (pugi::xml_node range : doc.child("storages").children("range")) { + for (const auto &range : doc.child("storages").children("range")) { uint32_t start = range.attribute("start").as_uint(); uint32_t end = range.attribute("end").as_uint(); @@ -40,11 +44,11 @@ bool Storages::loadFromXML() { ranges.emplace_back(start, end); - for (pugi::xml_node storage : range.children("storage")) { + for (const auto &storage : range.children("storage")) { std::string name = storage.attribute("name").as_string(); uint32_t key = storage.attribute("key").as_uint(); - for (char c : name) { + for (const char &c : name) { if (std::isupper(c)) { g_logger().warn("[{}] Storage from storages.xml with name: {}, contains uppercase letters. Please use dot notation pattern", __func__, name); break; diff --git a/src/creatures/players/storages/storages.hpp b/src/creatures/players/storages/storages.hpp index afc9fe14f90..70e099988fd 100644 --- a/src/creatures/players/storages/storages.hpp +++ b/src/creatures/players/storages/storages.hpp @@ -9,8 +9,6 @@ #pragma once -#include "lib/di/container.hpp" - class Storages { public: Storages() = default; @@ -19,9 +17,7 @@ class Storages { Storages(const Storages &) = delete; void operator=(const Storages &) = delete; - static Storages &getInstance() { - return inject(); - } + static Storages &getInstance(); bool loadFromXML(); diff --git a/src/creatures/players/vip/player_vip.cpp b/src/creatures/players/vip/player_vip.cpp index 46fe5442a64..25fbfdba0e4 100644 --- a/src/creatures/players/vip/player_vip.cpp +++ b/src/creatures/players/vip/player_vip.cpp @@ -113,7 +113,7 @@ bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t IOLoginData::removeGuidVIPGroupEntry(m_player.account->getID(), vipGuid); - for (const auto groupId : groupsId) { + for (const auto &groupId : groupsId) { const auto &group = getGroupByID(groupId); if (group) { group->vipGroupGuids.insert(vipGuid); @@ -125,7 +125,7 @@ bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t } std::shared_ptr PlayerVIP::getGroupByID(uint8_t groupId) const { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr &vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const auto &vipGroup) { return vipGroup->id == groupId; }); @@ -134,7 +134,7 @@ std::shared_ptr PlayerVIP::getGroupByID(uint8_t groupId) const { std::shared_ptr PlayerVIP::getGroupByName(const std::string &name) const { const auto groupName = name.c_str(); - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupName](const std::shared_ptr &vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupName](const auto &vipGroup) { return strcmp(groupName, vipGroup->name.c_str()) == 0; }); @@ -157,7 +157,7 @@ void PlayerVIP::addGroupInternal(uint8_t groupId, const std::string &name, bool } void PlayerVIP::removeGroup(uint8_t groupId) { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const std::shared_ptr &vipGroup) { + auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const auto &vipGroup) { return vipGroup->id == groupId; }); diff --git a/src/creatures/players/vocations/vocation.cpp b/src/creatures/players/vocations/vocation.cpp index 2a786e36852..42a7154e301 100644 --- a/src/creatures/players/vocations/vocation.cpp +++ b/src/creatures/players/vocations/vocation.cpp @@ -10,10 +10,14 @@ #include "pch.hpp" #include "creatures/players/vocations/vocation.hpp" - +#include "lib/di/container.hpp" #include "utils/pugicast.hpp" #include "utils/tools.hpp" +Vocations &Vocations::getInstance() { + return inject(); +} + bool Vocations::reload() { vocationsMap.clear(); return loadFromXml(); @@ -28,7 +32,7 @@ bool Vocations::loadFromXml() { return false; } - for (auto vocationNode : doc.child("vocations").children()) { + for (const auto &vocationNode : doc.child("vocations").children()) { pugi::xml_attribute attr; if (!(attr = vocationNode.attribute("id"))) { g_logger().warn("[{}] - Missing vocation id", __FUNCTION__); @@ -120,7 +124,7 @@ bool Vocations::loadFromXml() { voc->avatarLookType = pugi::cast(attr.value()); } - for (auto childNode : vocationNode.children()) { + for (const auto &childNode : vocationNode.children()) { if (strcasecmp(childNode.name(), "skill") == 0) { pugi::xml_attribute skillIdAttribute = childNode.attribute("id"); if (skillIdAttribute) { diff --git a/src/creatures/players/vocations/vocation.hpp b/src/creatures/players/vocations/vocation.hpp index 0ad95ac0fc0..4d5fa6014b8 100644 --- a/src/creatures/players/vocations/vocation.hpp +++ b/src/creatures/players/vocations/vocation.hpp @@ -9,10 +9,12 @@ #pragma once -#include "declarations.hpp" +#include "config/configmanager.hpp" +#include "creatures/creatures_definitions.hpp" #include "items/item.hpp" -#include "lib/di/container.hpp" -#include "creatures/players/wheel/wheel_gems.hpp" + +enum class WheelGemSupremeModifier_t : uint8_t; +enum class WheelGemQuality_t : uint8_t; class Vocation { public: @@ -174,9 +176,7 @@ class Vocations { Vocations(const Vocations &) = delete; void operator=(const Vocations &) = delete; - static Vocations &getInstance() { - return inject(); - } + static Vocations &getInstance(); bool loadFromXml(); bool reload(); diff --git a/src/creatures/players/wheel/player_wheel.cpp b/src/creatures/players/wheel/player_wheel.cpp index 6c63158980a..c475ece182c 100644 --- a/src/creatures/players/wheel/player_wheel.cpp +++ b/src/creatures/players/wheel/player_wheel.cpp @@ -794,7 +794,7 @@ std::vector PlayerWheel::getRevealedGems() const { std::vector PlayerWheel::getActiveGems() const { std::vector activeGems; - for (auto affinity : magic_enum::enum_values()) { + for (const auto &affinity : magic_enum::enum_values()) { std::string key(magic_enum::enum_name(affinity)); auto uuidKV = gemsKV()->scoped("active")->get(key); if (!uuidKV.has_value()) { @@ -1028,7 +1028,7 @@ void PlayerWheel::sendOpenWheelWindow(NetworkMessage &msg, uint32_t ownerId) con addPromotionScrolls(msg); addGems(msg); // TODO: read items from inventory - auto voc = m_player.getVocation(); + const auto &voc = m_player.getVocation(); m_player.client->sendResourceBalance(RESOURCE_BANK, m_player.getBankBalance()); m_player.client->sendResourceBalance(RESOURCE_INVENTORY_MONEY, m_player.getMoney()); m_player.client->sendResourceBalance(RESOURCE_LESSER_GEMS, m_player.getItemTypeCount(voc->getWheelGemId(WheelGemQuality_t::Lesser))); @@ -1154,7 +1154,7 @@ void PlayerWheel::saveSlotPointsOnPressSaveButton(NetworkMessage &msg) { } // Gem Vessels - for (auto affinity : magic_enum::enum_values()) { + for (const auto &affinity : magic_enum::enum_values()) { bool hasGem = msg.getByte(); if (!hasGem) { removeActiveGem(affinity); @@ -2017,12 +2017,12 @@ bool PlayerWheel::checkBattleInstinct() { m_player.getPosition().y + offsetY, m_player.getPosition().z ); - std::shared_ptr tile = g_game().map.getTile(playerPositionOffSet); + const auto &tile = g_game().map.getTile(playerPositionOffSet); if (!tile) { continue; } - std::shared_ptr creature = tile->getTopVisibleCreature(m_player.getPlayer()); + const auto &creature = tile->getTopVisibleCreature(m_player.getPlayer()); if (!creature || creature == m_player.getPlayer() || (creature->getMaster() && creature->getMaster()->getPlayer() == m_player.getPlayer())) { continue; } @@ -2065,12 +2065,12 @@ bool PlayerWheel::checkPositionalTatics() { m_player.getPosition().y + offsetY, m_player.getPosition().z ); - std::shared_ptr tile = g_game().map.getTile(playerPositionOffSet); + const auto &tile = g_game().map.getTile(playerPositionOffSet); if (!tile) { continue; } - std::shared_ptr creature = tile->getTopVisibleCreature(m_player.getPlayer()); + const auto &creature = tile->getTopVisibleCreature(m_player.getPlayer()); if (!creature || creature == m_player.getPlayer() || !creature->getMonster() || (creature->getMaster() && creature->getMaster()->getPlayer())) { continue; } @@ -2112,7 +2112,7 @@ bool PlayerWheel::checkBallisticMastery() { uint16_t newHolyBonus = 2; // 2% uint16_t newPhysicalBonus = 2; // 2% - const auto item = m_player.getWeapon(); + const auto &item = m_player.getWeapon(); if (item && item->getAmmoType() == AMMO_BOLT) { if (getMajorStat(WheelMajor_t::CRITICAL_DMG) != newCritical) { setMajorStat(WheelMajor_t::CRITICAL_DMG, newCritical); @@ -2153,7 +2153,7 @@ bool PlayerWheel::checkCombatMastery() { bool updateClient = false; uint8_t stage = getStage(WheelStage_t::COMBAT_MASTERY); - const auto item = m_player.getWeapon(); + const auto &item = m_player.getWeapon(); if (item && item->getSlotPosition() & SLOTP_TWO_HAND) { int32_t criticalSkill = 0; if (stage >= 3) { @@ -2198,12 +2198,12 @@ bool PlayerWheel::checkDivineEmpowerment() { bool updateClient = false; setOnThinkTimer(WheelOnThink_t::DIVINE_EMPOWERMENT, OTSYS_TIME() + 1000); - const auto tile = m_player.getTile(); + const auto &tile = m_player.getTile(); if (!tile) { return updateClient; } - const auto items = tile->getItemList(); + const auto &items = tile->getItemList(); if (!items) { return updateClient; } diff --git a/src/creatures/players/wheel/player_wheel.hpp b/src/creatures/players/wheel/player_wheel.hpp index b0375b6c794..427c5afa496 100644 --- a/src/creatures/players/wheel/player_wheel.hpp +++ b/src/creatures/players/wheel/player_wheel.hpp @@ -10,7 +10,6 @@ #pragma once #include "io/io_wheel.hpp" -#include "utils/utils_definitions.hpp" #include "kv/kv.hpp" #include "wheel_gems.hpp" diff --git a/src/creatures/players/wheel/wheel_gems.cpp b/src/creatures/players/wheel/wheel_gems.cpp index c3653298c12..16bd037a9e0 100644 --- a/src/creatures/players/wheel/wheel_gems.cpp +++ b/src/creatures/players/wheel/wheel_gems.cpp @@ -518,7 +518,7 @@ void WheelModifierContext::addStrategies(WheelGemSupremeModifier_t modifier) { } void WheelModifierContext::executeStrategies() { - for (auto &strategy : m_strategies) { + for (const auto &strategy : m_strategies) { strategy->execute(); } } diff --git a/src/enums/player_cyclopedia.hpp b/src/enums/player_cyclopedia.hpp index 295e573984f..af7ea1701ff 100644 --- a/src/enums/player_cyclopedia.hpp +++ b/src/enums/player_cyclopedia.hpp @@ -13,7 +13,7 @@ #include #endif -enum CyclopediaBadge_t : uint8_t { +enum class CyclopediaBadge_t : uint8_t { ACCOUNT_AGE = 1, LOYALTY, ACCOUNT_ALL_LEVEL, diff --git a/src/game/game.cpp b/src/game/game.cpp index 7b70cbc1b34..b7e7083eda5 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -10175,7 +10175,7 @@ bool Game::removeFiendishMonster(uint32_t id, bool create /* = true*/) { void Game::updateForgeableMonsters() { forgeableMonsters.clear(); for (const auto &[monsterId, monster] : monsters) { - auto monsterTile = monster->getTile(); + const auto &monsterTile = monster->getTile(); if (!monsterTile) { continue; } @@ -10185,7 +10185,7 @@ void Game::updateForgeableMonsters() { } } - for (const auto monsterId : getFiendishMonsters()) { + for (const auto &monsterId : getFiendishMonsters()) { if (!getMonsterByID(monsterId)) { removeFiendishMonster(monsterId); } diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index c8782d1734f..b70ffe6bf78 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -1247,7 +1247,7 @@ void Events::eventPlayerOnRequestQuestLine(const std::shared_ptr &player scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(const auto player, const std::shared_ptr &item, Slots_t slot, bool equip) { +void Events::eventPlayerOnInventoryUpdate(const std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { return; diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index c2f52f1b4e1..27915383a86 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -116,7 +116,7 @@ class Events { void eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId); void eventOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime); void eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage); - void eventPlayerOnInventoryUpdate(const auto player, const std::shared_ptr &item, Slots_t slot, bool equip); + void eventPlayerOnInventoryUpdate(const std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip); // Monster void eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse); diff --git a/src/lua/global/globalevent.cpp b/src/lua/global/globalevent.cpp index a564313b443..4849672f3b2 100644 --- a/src/lua/global/globalevent.cpp +++ b/src/lua/global/globalevent.cpp @@ -212,14 +212,14 @@ std::string GlobalEvent::getScriptTypeName() const { bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightInfo) const { // onPeriodChange(lightState, lightTime) - if (!LuaEnvironment::reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executePeriodChange - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -232,14 +232,14 @@ bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightIn bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { // onRecord(current, old) - if (!LuaEnvironment::reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executeRecord - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); @@ -251,14 +251,14 @@ bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { } bool GlobalEvent::executeEvent() const { - if (!LuaEnvironment::reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executeEvent - {}] " "Call stack overflow. Too many lua script calls being nested.", getName()); return false; } - ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(getScriptId(), getScriptInterface()); lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); diff --git a/src/lua/modules/modules.cpp b/src/lua/modules/modules.cpp index fcbdd99fdc3..70747a7c3bd 100644 --- a/src/lua/modules/modules.cpp +++ b/src/lua/modules/modules.cpp @@ -154,12 +154,12 @@ void Module::clearEvent() { } void Module::executeOnRecvbyte(const std::shared_ptr &player, NetworkMessage &msg) { - if (!LuaEnvironment::reserveScriptEnv()) { + if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Call stack overflow. Too many lua script calls being nested {}", player->getName()); return; } - ScriptEnvironment* env = LuaEnvironment::getScriptEnv(); + ScriptEnvironment* env = LuaScriptInterface::getScriptEnv(); env->setScriptId(scriptId, scriptInterface); lua_State* L = scriptInterface->getLuaState(); diff --git a/src/lua/modules/modules.hpp b/src/lua/modules/modules.hpp index a2994cf6c73..a9211db3317 100644 --- a/src/lua/modules/modules.hpp +++ b/src/lua/modules/modules.hpp @@ -12,7 +12,6 @@ #include "declarations.hpp" #include "lib/di/container.hpp" #include "lua/global/baseevents.hpp" -#include "lua/scripts/luascript.hpp" #include "server/network/message/networkmessage.hpp" class Module; From 47b64d2b7a87b6899cc70168c6f61be7dab7a4ac Mon Sep 17 00:00:00 2001 From: Beats Date: Thu, 15 Aug 2024 20:47:22 -0300 Subject: [PATCH 07/34] ? --- src/items/thing.cpp | 2 +- src/items/tile.cpp | 159 +++++++++++++++++++++----------------------- 2 files changed, 76 insertions(+), 85 deletions(-) diff --git a/src/items/thing.cpp b/src/items/thing.cpp index 6eec7994df8..26d5fa625f0 100644 --- a/src/items/thing.cpp +++ b/src/items/thing.cpp @@ -13,7 +13,7 @@ #include "items/tile.hpp" const Position &Thing::getPosition() { - std::shared_ptr tile = getTile(); + const auto &tile = getTile(); if (!tile) { return Tile::nullptr_tile->getPosition(); } diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 028df494bff..f0fc757cd77 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -299,7 +299,7 @@ std::shared_ptr Tile::getBottomVisibleCreature(const std::shared_ptrisInvisible()) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (!player || !player->isInGhostMode()) { return creature; } @@ -996,113 +996,104 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { return; // RETURNVALUE_NOTPOSSIBLE } - // Verify if the thing is a creature - std::shared_ptr creature = thing->getCreature(); + const auto &creature = thing->getCreature(); if (creature) { Spectators::clearCache(); creature->setParent(static_self_cast()); - // Safely add creature to the list CreatureVector* creatures = makeCreatures(); if (creatures) { creatures->insert(creatures->begin(), creature); } - } else { - const auto &item = thing->getItem(); - if (!item) { - return; // RETURNVALUE_NOTPOSSIBLE - } + return; + } - TileItemVector* items = getItemList(); - if (items && items->size() >= 0xFFFF) { - return; // RETURNVALUE_NOTPOSSIBLE - } + const auto &item = thing->getItem(); + if (!item) { + return; // RETURNVALUE_NOTPOSSIBLE + } - item->setParent(static_self_cast()); + TileItemVector* items = getItemList(); + if (items && items->size() >= 0xFFFF) { + return; // RETURNVALUE_NOTPOSSIBLE + } - const ItemType &itemType = Item::items[item->getID()]; - if (itemType.isGroundTile()) { - if (!ground) { - ground = item; - onAddTileItem(item); - } else { - const ItemType &oldType = Item::items[ground->getID()]; + item->setParent(static_self_cast()); - std::shared_ptr oldGround = ground; - ground->resetParent(); - ground = item; - resetTileFlags(oldGround); - setTileFlags(item); - onUpdateTileItem(oldGround, oldType, item, itemType); - postRemoveNotification(oldGround, nullptr, 0); - } - } else if (item->isAlwaysOnTop()) { - if (itemType.isSplash() && items) { - // Remove old splash if it exists - for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - const auto oldSplash = *it; - if (!Item::items[oldSplash->getID()].isSplash()) { - continue; - } + const ItemType &itemType = Item::items[item->getID()]; + + if (itemType.isGroundTile()) { + if (!ground) { + ground = item; + onAddTileItem(item); + } else { + const ItemType &oldType = Item::items[ground->getID()]; + const auto &oldGround = ground; + ground->resetParent(); + ground = item; + resetTileFlags(oldGround); + setTileFlags(item); + onUpdateTileItem(oldGround, oldType, item, itemType); + postRemoveNotification(oldGround, nullptr, 0); + } + return; + } + if (item->isAlwaysOnTop()) { + if (itemType.isSplash() && items) { + for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { + const auto &oldSplash = *it; + if (Item::items[oldSplash->getID()].isSplash()) { removeThing(oldSplash, 1); oldSplash->resetParent(); postRemoveNotification(oldSplash, nullptr, 0); break; } } + } - bool isInserted = false; - - if (items) { - for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { - // Check if the current item should be placed before the current item - if (itemType.alwaysOnTopOrder <= Item::items[(*it)->getID()].alwaysOnTopOrder) { - items->insert(it, item); - isInserted = true; - break; - } - } - } else { - items = makeItemList(); - } + if (!items) { + items = makeItemList(); + } - if (!isInserted && items) { - items->push_back(item); - } + const auto &it = std::find_if(items->getBeginTopItem(), items->getEndTopItem(), [&](const auto &i) { + return itemType.alwaysOnTopOrder <= Item::items[i->getID()].alwaysOnTopOrder; + }); - onAddTileItem(item); + if (it != items->getEndTopItem()) { + items->insert(it, item); } else { - if (itemType.isMagicField()) { - // Remove old field item if it exists - if (items) { - for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { - std::shared_ptr oldField = (*it)->getMagicField(); - if (oldField) { - if (oldField->isReplaceable()) { - removeThing(oldField, 1); - - oldField->resetParent(); - postRemoveNotification(oldField, nullptr, 0); - break; - } else { - // This magic field cannot be replaced. - item->resetParent(); - return; - } - } - } + items->push_back(item); + } + + onAddTileItem(item); + return; + } + + if (itemType.isMagicField() && items) { + for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { + std::shared_ptr oldField = (*it)->getMagicField(); + if (oldField) { + if (oldField->isReplaceable()) { + removeThing(oldField, 1); + oldField->resetParent(); + postRemoveNotification(oldField, nullptr, 0); + break; } - } - if (items) { - items = makeItemList(); - items->insert(items->getBeginDownItem(), item); - items->increaseDownItemCount(); + item->resetParent(); + return; } - onAddTileItem(item); } } + + if (!items) { + items = makeItemList(); + } + + items->insert(items->getBeginDownItem(), item); + items->increaseDownItemCount(); + onAddTileItem(item); } void Tile::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) { @@ -1201,7 +1192,7 @@ void Tile::removeThing(std::shared_ptr thing, uint32_t count) { if (creature) { CreatureVector* creatures = getCreatures(); if (creatures) { - auto it = std::find(creatures->begin(), creatures->end(), thing); + auto it = std::ranges::find(*creatures, thing); if (it != creatures->end()) { Spectators::clearCache(); creatures->erase(it); @@ -1266,9 +1257,9 @@ void Tile::removeThing(std::shared_ptr thing, uint32_t count) { } else { std::vector oldStackPosVector; - auto spectators = Spectators().find(getPosition(), true); + const auto spectators = Spectators().find(getPosition(), true); for (const auto &spectator : spectators) { - if (const auto &tmpPlayer = spectator->getPlayer()) { + if (spectator->getPlayer()) { oldStackPosVector.push_back(getStackposOfItem(spectator->getPlayer(), item)); } } @@ -1554,7 +1545,7 @@ void Tile::postRemoveNotification(std::shared_ptr thing, std::shared_ptr< if (creature) { g_moveEvents().onCreatureMove(creature, static_self_cast(), MOVE_EVENT_STEP_OUT); } else { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item) { g_moveEvents().onItemMove(item, static_self_cast(), false); } From 6a04a4abcdd5cd7ca28e6616a70159f08de9d1a1 Mon Sep 17 00:00:00 2001 From: Beats Date: Fri, 16 Aug 2024 01:50:13 -0300 Subject: [PATCH 08/34] fix warnig and ative SIMD --- cmake/modules/CheckSIMDSupport.cmake | 78 +++++++++++++++++++ src/CMakeLists.txt | 1 + .../monsters/spawns/spawn_monster.hpp | 11 ++- src/io/functions/iologindata_load_player.cpp | 8 +- src/items/tile.hpp | 2 +- src/map/utils/astarnodes.cpp | 6 +- src/map/utils/astarnodes.hpp | 2 +- 7 files changed, 93 insertions(+), 15 deletions(-) create mode 100644 cmake/modules/CheckSIMDSupport.cmake diff --git a/cmake/modules/CheckSIMDSupport.cmake b/cmake/modules/CheckSIMDSupport.cmake new file mode 100644 index 00000000000..bff5f47a1d2 --- /dev/null +++ b/cmake/modules/CheckSIMDSupport.cmake @@ -0,0 +1,78 @@ +include(CheckCXXCompilerFlag) + +if(MSVC) + check_cxx_compiler_flag("/arch:AVX512" COMPILER_SUPPORTS_AVX512) + if(COMPILER_SUPPORTS_AVX512) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX512") + add_definitions(-D__AVX512F__ -D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("AVX512: Advanced Vector Extensions 512 supported and enabled.") + elseif(COMPILER_SUPPORTS_AVX2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX2") + add_definitions(-D__AVX2__ -D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("AVX2: Advanced Vector Extensions 2 supported and enabled.") + elseif(COMPILER_SUPPORTS_AVX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX") + add_definitions(-D__AVX__ -D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("AVX: Advanced Vector Extensions supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE42) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE4.2") + add_definitions(-D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("SSE4.2: Streaming SIMD Extensions 4.2 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE41) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE4.1") + add_definitions(-D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("SSE4.1: Streaming SIMD Extensions 4.1 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE3) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE3") + add_definitions(-D__SSE3__ -D__SSE2__ -D__SSE__) + log_option_enabled("SSE3: Streaming SIMD Extensions 3 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE2") + add_definitions(-D__SSE2__ -D__SSE__) + log_option_enabled("SSE2: Streaming SIMD Extensions 2 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:SSE") + add_definitions(-D__SSE__) + log_option_enabled("SSE: Streaming SIMD Extensions supported and enabled.") + else() + message(STATUS "No advanced SIMD support found. Proceeding with the default instruction set.") + endif() +else() + include(CheckCXXCompilerFlag) + check_cxx_compiler_flag("-mavx512f" COMPILER_SUPPORTS_AVX512) + if(COMPILER_SUPPORTS_AVX512) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx512f") + add_definitions(-D__AVX512F__) + log_option_enabled("AVX512: Advanced Vector Extensions 512 supported and enabled.") + elseif(COMPILER_SUPPORTS_AVX2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx2") + add_definitions(-D__AVX2__) + log_option_enabled("AVX2: Advanced Vector Extensions 2 supported and enabled.") + elseif(COMPILER_SUPPORTS_AVX) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx") + add_definitions(-D__AVX__) + log_option_enabled("AVX: Advanced Vector Extensions supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE42) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.2") + add_definitions(-D__SSE4_2__) + log_option_enabled("SSE4.2: Streaming SIMD Extensions 4.2 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE41) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse4.1") + add_definitions(-D__SSE4_1__) + log_option_enabled("SSE4.1: Streaming SIMD Extensions 4.1 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE3) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse3") + add_definitions(-D__SSE3__) + log_option_enabled("SSE3: Streaming SIMD Extensions 3 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE2) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse2") + add_definitions(-D__SSE2__) + log_option_enabled("SSE2: Streaming SIMD Extensions 2 supported and enabled.") + elseif(COMPILER_SUPPORTS_SSE) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -msse") + add_definitions(-D__SSE__) + log_option_enabled("SSE: Streaming SIMD Extensions supported and enabled.") + else() + message(STATUS "No advanced SIMD support found. Proceeding with the default instruction set.") + endif() +endif() diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 2abd46f06c2..a6b1e83bccc 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -2,6 +2,7 @@ cmake_minimum_required(VERSION 3.22 FATAL_ERROR) # Base configurations and settings for the project include(BaseConfig) +include(CheckSIMDSupport) include(GNUInstallDirs) # Import configurations, source definitions, and linker settings diff --git a/src/creatures/monsters/spawns/spawn_monster.hpp b/src/creatures/monsters/spawns/spawn_monster.hpp index ef2ef23efcd..c1f4243a5b6 100644 --- a/src/creatures/monsters/spawns/spawn_monster.hpp +++ b/src/creatures/monsters/spawns/spawn_monster.hpp @@ -9,7 +9,6 @@ #pragma once -#include "items/tile.hpp" #include "game/movement/position.hpp" class Monster; @@ -17,9 +16,9 @@ class MonsterType; struct spawnBlock_t { Position pos; - std::unordered_map, uint32_t> monsterTypes; - int64_t lastSpawn; - uint32_t interval; + std::unordered_map, uint32_t> monsterTypes {}; + int64_t lastSpawn {}; + uint32_t interval {}; Direction direction; std::shared_ptr getMonsterType() const; @@ -38,9 +37,9 @@ class SpawnMonster { // moveable SpawnMonster(SpawnMonster &&rhs) noexcept : - spawnMonsterMap(std::move(rhs.spawnMonsterMap)), spawnedMonsterMap(std::move(rhs.spawnedMonsterMap)), - checkSpawnMonsterEvent(rhs.checkSpawnMonsterEvent), centerPos(rhs.centerPos), radius(rhs.radius), interval(rhs.interval) { } + spawnMonsterMap(std::move(rhs.spawnMonsterMap)), + centerPos(rhs.centerPos), radius(rhs.radius), interval(rhs.interval), checkSpawnMonsterEvent(rhs.checkSpawnMonsterEvent) { } SpawnMonster &operator=(SpawnMonster &&rhs) noexcept { if (this != &rhs) { diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index 9bce6c0015d..75053e57372 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -720,7 +720,7 @@ void IOLoginDataLoad::loadPlayerPreyClass(const std::shared_ptr &player, Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `player_prey` WHERE `player_id` = " << player->getGUID(); - if (result = db.storeQuery(query.str())) { + if ((result = db.storeQuery(query.str()))) { do { auto slot = std::make_unique(static_cast(result->getNumber("slot"))); auto state = static_cast(result->getNumber("state")); @@ -767,7 +767,7 @@ void IOLoginDataLoad::loadPlayerTaskHuntingClass(const std::shared_ptr & Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); - if (result = db.storeQuery(query.str())) { + if ((result = db.storeQuery(query.str()))) { do { auto slot = std::make_unique(static_cast(result->getNumber("slot"))); auto state = static_cast(result->getNumber("state")); @@ -815,7 +815,7 @@ void IOLoginDataLoad::loadPlayerForgeHistory(const std::shared_ptr &play std::ostringstream query; query << "SELECT * FROM `forge_history` WHERE `player_id` = " << player->getGUID(); - if (result = Database::getInstance().storeQuery(query.str())) { + if ((result = Database::getInstance().storeQuery(query.str()))) { do { auto actionEnum = magic_enum::enum_value(result->getNumber("action_type")); ForgeHistory history; @@ -836,7 +836,7 @@ void IOLoginDataLoad::loadPlayerBosstiary(const std::shared_ptr &player, std::ostringstream query; query << "SELECT * FROM `player_bosstiary` WHERE `player_id` = " << player->getGUID(); - if (result = Database::getInstance().storeQuery(query.str())) { + if ((result = Database::getInstance().storeQuery(query.str()))) { do { player->setSlotBossId(1, result->getNumber("bossIdSlotOne")); player->setSlotBossId(2, result->getNumber("bossIdSlotTwo")); diff --git a/src/items/tile.hpp b/src/items/tile.hpp index f414677eced..777a846d783 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -256,7 +256,7 @@ class Tile : public Cylinder, public SharedObject { resetTileFlags(ground); } - if (ground = item) { + if ((ground = item)) { setTileFlags(item); } } diff --git a/src/map/utils/astarnodes.cpp b/src/map/utils/astarnodes.cpp index 5c739272a61..e8df3ce9c32 100644 --- a/src/map/utils/astarnodes.cpp +++ b/src/map/utils/astarnodes.cpp @@ -14,7 +14,7 @@ #include "creatures/combat/combat.hpp" AStarNodes::AStarNodes(uint32_t x, uint32_t y, int_fast32_t extraCost) : - openNodes(), nodes() { + nodes(), openNodes() { #if defined(__AVX2__) __m256i defaultCost = _mm256_set1_epi32(std::numeric_limits::max()); for (int32_t i = 0; i < MAX_NODES; i += 32) { @@ -100,7 +100,7 @@ AStarNode* AStarNodes::getBestNode() { best_node = (total_cost < best_node_f ? indices_array[i] : best_node); best_node_f = (total_cost < best_node_f ? total_cost : best_node_f); } - return (openNodes[best_node] ? &nodes[best_node] : NULL); + return (openNodes[best_node] ? &nodes[best_node] : nullptr); #elif defined(__AVX2__) const __m256i increment = _mm256_set1_epi32(8); __m256i indices = _mm256_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7); @@ -257,7 +257,7 @@ AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) { #endif } -int_fast32_t AStarNodes::getMapWalkCost(AStarNode* node, const Position &neighborPos) { +int_fast32_t AStarNodes::getMapWalkCost(const AStarNode* node, const Position &neighborPos) { // diagonal movement extra cost return (((std::abs(node->x - neighborPos.x) + std::abs(node->y - neighborPos.y)) - 1) * MAP_DIAGONALWALKCOST) + MAP_NORMALWALKCOST; } diff --git a/src/map/utils/astarnodes.hpp b/src/map/utils/astarnodes.hpp index dcd74f7039d..6e4411855bb 100644 --- a/src/map/utils/astarnodes.hpp +++ b/src/map/utils/astarnodes.hpp @@ -30,7 +30,7 @@ class AStarNodes { int32_t getClosedNodes() const; AStarNode* getNodeByPosition(uint32_t x, uint32_t y); - static int_fast32_t getMapWalkCost(AStarNode* node, const Position &neighborPos); + static int_fast32_t getMapWalkCost(const AStarNode* node, const Position &neighborPos); static int_fast32_t getTileWalkCost(const std::shared_ptr &creature, const std::shared_ptr &tile); private: From 6a427af96bc0c29acee788daafa191b19728f4c1 Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 17 Aug 2024 02:29:25 -0300 Subject: [PATCH 09/34] fix crash --- cmake/modules/CheckSIMDSupport.cmake | 16 ++++------------ 1 file changed, 4 insertions(+), 12 deletions(-) diff --git a/cmake/modules/CheckSIMDSupport.cmake b/cmake/modules/CheckSIMDSupport.cmake index bff5f47a1d2..e6638584090 100644 --- a/cmake/modules/CheckSIMDSupport.cmake +++ b/cmake/modules/CheckSIMDSupport.cmake @@ -1,12 +1,8 @@ include(CheckCXXCompilerFlag) if(MSVC) - check_cxx_compiler_flag("/arch:AVX512" COMPILER_SUPPORTS_AVX512) - if(COMPILER_SUPPORTS_AVX512) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX512") - add_definitions(-D__AVX512F__ -D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) - log_option_enabled("AVX512: Advanced Vector Extensions 512 supported and enabled.") - elseif(COMPILER_SUPPORTS_AVX2) + check_cxx_compiler_flag("/arch:AVX2" COMPILER_SUPPORTS_AVX2) + if(COMPILER_SUPPORTS_AVX2) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /arch:AVX2") add_definitions(-D__AVX2__ -D__SSE4_2__ -D__SSE4_1__ -D__SSE3__ -D__SSE2__ -D__SSE__) log_option_enabled("AVX2: Advanced Vector Extensions 2 supported and enabled.") @@ -39,12 +35,8 @@ if(MSVC) endif() else() include(CheckCXXCompilerFlag) - check_cxx_compiler_flag("-mavx512f" COMPILER_SUPPORTS_AVX512) - if(COMPILER_SUPPORTS_AVX512) - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx512f") - add_definitions(-D__AVX512F__) - log_option_enabled("AVX512: Advanced Vector Extensions 512 supported and enabled.") - elseif(COMPILER_SUPPORTS_AVX2) + check_cxx_compiler_flag("-mavx2" COMPILER_SUPPORTS_AVX2) + if(COMPILER_SUPPORTS_AVX2) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -mavx2") add_definitions(-D__AVX2__) log_option_enabled("AVX2: Advanced Vector Extensions 2 supported and enabled.") From c37c149d4e4cab09a4ad9e6d946ac52d68ee0636 Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 17 Aug 2024 05:26:45 -0300 Subject: [PATCH 10/34] test --- src/creatures/creature.cpp | 16 +- src/io/fileloader.cpp | 11 + src/io/fileloader.hpp | 204 +++++++++++++++++- src/io/filestream.cpp | 83 ++++++- src/server/network/message/networkmessage.cpp | 153 ++++++++++++- src/server/network/message/networkmessage.hpp | 104 ++++++++- src/server/network/message/outputmessage.hpp | 130 ++++++++++- src/server/server.hpp | 1 + 8 files changed, 682 insertions(+), 20 deletions(-) diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 7873c883f83..265131a5427 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -511,7 +511,14 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s if (oldPos.y > newPos.y) { // north // shift y south for (int32_t y = mapWalkHeight - 1; --y >= 0;) { +// Copiando linhas usando SIMD +#if defined(__AVX2__) + _mm256_storeu_si256(reinterpret_cast<__m256i*>(localMapCache[y + 1]), _mm256_loadu_si256(reinterpret_cast(localMapCache[y]))); +#elif defined(__SSE2__) + _mm_storeu_si128(reinterpret_cast<__m128i*>(localMapCache[y + 1]), _mm_loadu_si128(reinterpret_cast(localMapCache[y]))); +#else memcpy(localMapCache[y + 1], localMapCache[y], sizeof(localMapCache[y])); +#endif } // update 0 @@ -522,7 +529,14 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s } else if (oldPos.y < newPos.y) { // south // shift y north for (int32_t y = 0; y <= mapWalkHeight - 2; ++y) { +// Copiando linhas usando SIMD +#if defined(__AVX2__) + _mm256_storeu_si256(reinterpret_cast<__m256i*>(localMapCache[y]), _mm256_loadu_si256(reinterpret_cast(localMapCache[y + 1]))); +#elif defined(__SSE2__) + _mm_storeu_si128(reinterpret_cast<__m128i*>(localMapCache[y]), _mm_loadu_si128(reinterpret_cast(localMapCache[y + 1]))); +#else memcpy(localMapCache[y], localMapCache[y + 1], sizeof(localMapCache[y])); +#endif } // update mapWalkHeight - 1 @@ -615,7 +629,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s onCreatureDisappear(attackedCreature, false); } else { if (hasExtraSwing()) { - // our target is moving lets see if we can get in hit + // our target is moving, let's see if we can get a hit g_dispatcher().addEvent([creatureId = getID()] { g_game().checkCreatureAttack(creatureId); }, "Game::checkCreatureAttack"); } diff --git a/src/io/fileloader.cpp b/src/io/fileloader.cpp index 38bf2be19e3..e590965fa11 100644 --- a/src/io/fileloader.cpp +++ b/src/io/fileloader.cpp @@ -22,7 +22,18 @@ namespace OTB { } Identifier fileIdentifier; + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez (caso aplicável) + _mm256_storeu_si256(reinterpret_cast<__m256i*>(fileIdentifier.data()), _mm256_loadu_si256(reinterpret_cast(fileContents.data()))); +#elif defined(__SSE2__) + // Use SSE2 para copiar 16 bytes de cada vez + _mm_storeu_si128(reinterpret_cast<__m128i*>(fileIdentifier.data()), _mm_loadu_si128(reinterpret_cast(fileContents.data()))); +#else + // Fallback para std::copy se nem AVX2 nem SSE2 estiverem disponíveis std::copy(fileContents.begin(), fileContents.begin() + fileIdentifier.size(), fileIdentifier.begin()); +#endif + if (fileIdentifier != acceptedIdentifier && fileIdentifier != wildcard) { throw InvalidOTBFormat {}; } diff --git a/src/io/fileloader.hpp b/src/io/fileloader.hpp index 83cb601e027..6df7e16e554 100644 --- a/src/io/fileloader.hpp +++ b/src/io/fileloader.hpp @@ -71,7 +71,55 @@ class PropStream { return false; } - memcpy(&ret, p, sizeof(T)); + const char* src = p; + char* dst = reinterpret_cast(&ret); + size_t remaining = sizeof(T); + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback para memcpy se nem AVX2 nem SSE2 estiverem disponíveis + memcpy(dst, src, remaining); +#endif + p += sizeof(T); return true; } @@ -87,8 +135,56 @@ class PropStream { } char* str = new char[strLen + 1]; - memcpy(str, p, strLen); - str[strLen] = 0; + const char* src = p; + char* dst = str; + size_t remaining = strLen; + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback para memcpy se nem AVX2 nem SSE2 estiverem disponíveis + memcpy(dst, src, remaining); +#endif + + str[strLen] = 0; // Null-terminate the string ret.assign(str, strLen); delete[] str; p += strLen; @@ -129,7 +225,55 @@ class PropWriteStream { template void write(T add) { char* addr = reinterpret_cast(&add); - std::copy(addr, addr + sizeof(T), std::back_inserter(buffer)); + size_t remaining = sizeof(T); + size_t pos = buffer.size(); + buffer.resize(pos + remaining); + + char* dst = buffer.data() + pos; + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(addr))); + addr += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(addr))); + addr += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(addr))); + addr += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(addr); + addr += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(addr); + addr += 2; + dst += 2; + remaining -= 2; + } + if (remaining == 1) { + *dst = *addr; + } +#else + // Fallback para std::copy se nem AVX2 nem SSE2 estiverem disponíveis + std::copy(addr, addr + remaining, std::back_inserter(buffer)); +#endif } void writeString(const std::string &str) { @@ -140,7 +284,57 @@ class PropWriteStream { } write(static_cast(strLength)); - std::copy(str.begin(), str.end(), std::back_inserter(buffer)); + + const char* src = str.data(); + size_t remaining = strLength; + size_t pos = buffer.size(); + buffer.resize(pos + remaining); + + char* dst = buffer.data() + pos; + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + if (remaining == 1) { + *dst = *src; + } +#else + // Fallback para std::copy se nem AVX2 nem SSE2 estiverem disponíveis + std::copy(src, src + remaining, std::back_inserter(buffer)); +#endif } private: diff --git a/src/io/filestream.cpp b/src/io/filestream.cpp index fc8ae6116fc..a68ae8e165c 100644 --- a/src/io/filestream.cpp +++ b/src/io/filestream.cpp @@ -45,18 +45,97 @@ bool FileStream::read(T &ret, bool escape) { throw std::ios_base::failure("Read failed"); } - std::array array; if (escape) { - for (int_fast8_t i = -1; ++i < size;) { + std::array array; + size_t i = 0; + while (i < size) { if (m_data[m_pos] == OTB::Node::ESCAPE) { ++m_pos; } array[i] = m_data[m_pos]; ++m_pos; + ++i; } + uint8_t* dst = reinterpret_cast(&ret); + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + for (i = 0; i + 32 <= size; i += 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst + i), _mm256_loadu_si256(reinterpret_cast(array.data() + i))); + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar 16 bytes de cada vez + for (i = 0; i + 16 <= size; i += 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst + i), _mm_loadu_si128(reinterpret_cast(array.data() + i))); + } + + for (; i + 8 <= size; i += 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst + i), _mm_loadl_epi64(reinterpret_cast(array.data() + i))); + } + for (; i + 4 <= size; i += 4) { + *reinterpret_cast(dst + i) = *reinterpret_cast(array.data() + i); + } + for (; i + 2 <= size; i += 2) { + *reinterpret_cast(dst + i) = *reinterpret_cast(array.data() + i); + } + if (i < size) { + dst[i] = array[i]; + } +#elif memcpy(&ret, array.data(), size); +#endif } else { + uint8_t* dst = reinterpret_cast(&ret); + const uint8_t* src = &m_data[m_pos]; + size_t remaining = size; + +#if defined(__AVX2__) + // Use AVX2 para copiar 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + dst += 32; + src += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para copiar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + dst += 16; + src += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + dst += 8; + src += 8; + remaining -= 8; + } + + // Copie os bytes restantes usando operações padrão + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + dst += 4; + src += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + dst += 2; + src += 2; + remaining -= 2; + } + if (remaining == 1) { + *dst = *src; + } +#elif memcpy(&ret, &m_data[m_pos], size); +#endif + m_pos += size; } diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index 38acc0b484c..ed67d0a869d 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -50,12 +50,61 @@ void NetworkMessage::addString(const std::string &value, const std::string &func return; } if (stringLen > NETWORKMESSAGE_MAXSIZE) { - g_logger().error("[NetworkMessage::addString] - Exceded NetworkMessage max size: {}, actually size: {}, function '{}'", NETWORKMESSAGE_MAXSIZE, stringLen, function); + g_logger().error("[NetworkMessage::addString] - Exceeded NetworkMessage max size: {}, actual size: {}, function '{}'", NETWORKMESSAGE_MAXSIZE, stringLen, function); return; } add(stringLen); - memcpy(buffer + info.position, value.c_str(), stringLen); + + unsigned char* dst = buffer + info.position; + const auto* src = reinterpret_cast(value.c_str()); + size_t remaining = stringLen; + +#if defined(__AVX2__) + // Use AVX2 to copy 32 bytes at a time + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 to copy remaining bytes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available + memcpy(dst, src, remaining); +#endif + info.position += stringLen; info.length += stringLen; } @@ -75,11 +124,59 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) { return; } if (size > NETWORKMESSAGE_MAXSIZE) { - g_logger().error("[NetworkMessage::addBytes] - Exceded NetworkMessage max size: {}, actually size: {}", NETWORKMESSAGE_MAXSIZE, size); + g_logger().error("[NetworkMessage::addBytes] - Exceeded NetworkMessage max size: {}, actually size: {}", NETWORKMESSAGE_MAXSIZE, size); return; } - memcpy(buffer + info.position, bytes, size); + unsigned char* dst = buffer + info.position; + const auto* src = reinterpret_cast(bytes); + size_t remaining = size; + +#if defined(__AVX2__) + // Use AVX2 to copy 32 bytes at a time + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 to copy remaining bytes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available + memcpy(dst, src, remaining); +#endif + info.position += size; info.length += size; } @@ -91,7 +188,53 @@ void NetworkMessage::addPaddingBytes(size_t n) { } #undef canAdd - memset(buffer + info.position, 0x33, n); + unsigned char* dst = buffer + info.position; + size_t remaining = n; + +#if defined(__AVX2__) + const __m256i padding_avx2 = _mm256_set1_epi8(0x33); // AVX2: 32 bytes de valor de preenchimento + + // Use AVX2 para preencher 32 bytes de cada vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), padding_avx2); + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + const __m128i padding_sse2 = _mm_set1_epi8(0x33); // SSE2: 16 bytes de valor de preenchimento + + // Use SSE2 para preencher os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), padding_sse2); + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(&padding_sse2))); + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = 0x33333333; // Preencher 4 bytes com 0x33 + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = 0x3333; // Preencher 2 bytes com 0x33 + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = 0x33; // Preencher 1 byte com 0x33 + remaining -= 1; + } +#else + // Fallback para o método original usando memset se nem AVX2 nem SSE2 estiverem disponíveis + memset(dst, 0x33, remaining); +#endif + info.length += n; } diff --git a/src/server/network/message/networkmessage.hpp b/src/server/network/message/networkmessage.hpp index 02e19253146..c54501c6c3a 100644 --- a/src/server/network/message/networkmessage.hpp +++ b/src/server/network/message/networkmessage.hpp @@ -53,7 +53,57 @@ class NetworkMessage { } T v; + const unsigned char* src = buffer + info.position; + auto* dst = reinterpret_cast(&v); + + size_t remaining = sizeof(T); + +#if defined(__AVX2__) + // Use AVX2 para carregar 32 bytes por vez + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 para carregar os bytes restantes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback para o método original usando memcpy se nem AVX2 nem SSE2 estiverem disponíveis memcpy(&v, buffer + info.position, sizeof(T)); + spdlog::info("[{}]: AVX2/SSE2 not available, used memcpy to load {} bytes.", __FUNCTION__, sizeof(T)); +#endif + info.position += sizeof(T); return v; } @@ -82,7 +132,57 @@ class NetworkMessage { return; } - memcpy(buffer + info.position, &value, sizeof(T)); + unsigned char* dst = buffer + info.position; + const auto* src = reinterpret_cast(&value); + + size_t remaining = sizeof(T); + +#if defined(__AVX2__) + // Use AVX2 to copy 32 bytes at a time + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + src += 32; + dst += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 to copy remaining bytes + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + src += 16; + dst += 16; + remaining -= 16; + } + while (remaining >= 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + src += 8; + dst += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 4; + dst += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + src += 2; + dst += 2; + remaining -= 2; + } + while (remaining == 1) { + *dst = *src; + remaining -= 1; + } +#else + // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available + memcpy(dst, src, remaining); + spdlog::info("[{}]: AVX2/SSE2 not available, used memcpy to copy {} bytes.", __FUNCTION__, remaining); +#endif + info.position += sizeof(T); info.length += sizeof(T); } @@ -169,5 +269,5 @@ class NetworkMessage { }; NetworkMessageInfo info; - uint8_t buffer[NETWORKMESSAGE_MAXSIZE]; + uint8_t buffer[NETWORKMESSAGE_MAXSIZE] {}; }; diff --git a/src/server/network/message/outputmessage.hpp b/src/server/network/message/outputmessage.hpp index 1f590fbd214..6d76bbc8ace 100644 --- a/src/server/network/message/outputmessage.hpp +++ b/src/server/network/message/outputmessage.hpp @@ -11,7 +11,7 @@ #include "server/network/message/networkmessage.hpp" #include "server/network/connection/connection.hpp" -#include "utils/tools.hpp" +#include class Protocol; @@ -40,15 +40,93 @@ class OutputMessage : public NetworkMessage { } void append(const NetworkMessage &msg) { - auto msgLen = msg.getLength(); - memcpy(buffer + info.position, msg.getBuffer() + INITIAL_BUFFER_POSITION, msgLen); + const auto msgLen = msg.getLength(); + const unsigned char* src = msg.getBuffer() + INITIAL_BUFFER_POSITION; + unsigned char* dst = buffer + info.position; + + size_t remaining = msgLen; + +#if defined(__AVX2__) + // Use AVX2 to copy 32 bytes at a time + while (remaining >= 32) { + copy_block<32>(src, dst); + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 to copy remaining bytes + while (remaining >= 16) { + copy_block<16>(src, dst); + remaining -= 16; + } + while (remaining >= 8) { + copy_block<8>(src, dst); + remaining -= 8; + } + while (remaining >= 4) { + copy_block<4>(src, dst); + remaining -= 4; + } + while (remaining >= 2) { + copy_block<2>(src, dst); + remaining -= 2; + } + while (remaining == 1) { + copy_block<1>(src, dst); + remaining -= 1; + } +#else + // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available + memcpy(dst, src, remaining); +#endif + info.length += msgLen; info.position += msgLen; } void append(const OutputMessage_ptr &msg) { - auto msgLen = msg->getLength(); - memcpy(buffer + info.position, msg->getBuffer() + INITIAL_BUFFER_POSITION, msgLen); + const auto msgLen = msg->getLength(); + const unsigned char* src = msg->getBuffer() + INITIAL_BUFFER_POSITION; + unsigned char* dst = buffer + info.position; + + size_t remaining = msgLen; + +#if defined(__AVX2__) + // Use AVX2 to copy 32 bytes at a time + while (remaining >= 32) { + copy_block<32>(src, dst); + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + // Use SSE2 to copy remaining bytes + while (remaining >= 16) { + copy_block<16>(src, dst); + remaining -= 16; + } + while (remaining >= 8) { + copy_block<8>(src, dst); + remaining -= 8; + } + while (remaining >= 4) { + copy_block<4>(src, dst); + remaining -= 4; + } + while (remaining >= 2) { + copy_block<2>(src, dst); + remaining -= 2; + } + while (remaining == 1) { + copy_block<1>(src, dst); + remaining -= 1; + } +#else + // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available + memcpy(dst, src, remaining); +#endif + info.length += msgLen; info.position += msgLen; } @@ -63,12 +141,54 @@ class OutputMessage : public NetworkMessage { assert(outputBufferStart >= sizeof(T)); outputBufferStart -= sizeof(T); + +#if defined(__SSE2__) + if constexpr (sizeof(T) >= 16) { + // Use SSE2 to copy 16 bytes at a time + _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + outputBufferStart), _mm_loadu_si128(reinterpret_cast(&addHeader))); + } else if constexpr (sizeof(T) >= 8) { + // Use SSE2 to copy 8 bytes + _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + outputBufferStart), _mm_loadl_epi64(reinterpret_cast(&addHeader))); + } else if constexpr (sizeof(T) >= 4) { + // Use SSE2 to copy 4 bytes + *reinterpret_cast(buffer + outputBufferStart) = *reinterpret_cast(&addHeader); + } else if constexpr (sizeof(T) >= 2) { + // Use SSE2 to copy 2 bytes + *reinterpret_cast(buffer + outputBufferStart) = *reinterpret_cast(&addHeader); + } else { + // Copy 1 byte + *reinterpret_cast(buffer + outputBufferStart) = *reinterpret_cast(&addHeader); + } +#else + // Fallback to original method using memcpy if SSE2 is not available memcpy(buffer + outputBufferStart, &addHeader, sizeof(T)); +#endif + // added header size to the message size info.length += sizeof(T); } MsgSize_t outputBufferStart = INITIAL_BUFFER_POSITION; + + template + static void copy_block(const unsigned char*&src, unsigned char*&dst) { + if constexpr (N == 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(src))); + } else if constexpr (N == 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(src))); + } else if constexpr (N == 8) { + _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast(src))); + } else if constexpr (N == 4) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + } else if constexpr (N == 2) { + *reinterpret_cast(dst) = *reinterpret_cast(src); + } else if constexpr (N == 1) { + *dst = *src; + } + + src += N; + dst += N; + } }; class OutputMessagePool { diff --git a/src/server/server.hpp b/src/server/server.hpp index 42134f765b0..2fb36fdb01c 100644 --- a/src/server/server.hpp +++ b/src/server/server.hpp @@ -18,6 +18,7 @@ class Protocol; class ServiceBase { public: + virtual ~ServiceBase() = default; virtual bool is_single_socket() const = 0; virtual bool is_checksummed() const = 0; virtual uint8_t get_protocol_identifier() const = 0; From 6d6a3341f931a37d1856e60cf76ac94d36fd04f2 Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 17 Aug 2024 21:50:08 -0300 Subject: [PATCH 11/34] improve --- src/creatures/combat/condition.cpp | 12 ++-- src/creatures/combat/condition.hpp | 48 +++++++++++++ src/game/scheduling/dispatcher.cpp | 20 +++--- src/game/scheduling/dispatcher.hpp | 13 ++-- src/game/scheduling/task.hpp | 59 ++++++++-------- src/io/fileloader.cpp | 3 - src/io/fileloader.hpp | 3 - src/security/rsa.cpp | 6 ++ src/server/network/message/networkmessage.cpp | 3 - src/server/network/message/networkmessage.hpp | 4 -- src/server/network/message/outputmessage.hpp | 3 - src/server/network/protocol/protocol.cpp | 69 +++++++++++++++---- src/server/network/protocol/protocol.hpp | 13 +++- src/utils/tools.cpp | 4 +- 14 files changed, 178 insertions(+), 82 deletions(-) diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 1c2564da04c..3d2518d443d 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -443,12 +443,12 @@ void ConditionAttributes::addCondition(std::shared_ptr creature, const endCondition(creature); // Apply the new one - memcpy(skills, conditionAttrs->skills, sizeof(skills)); - memcpy(skillsPercent, conditionAttrs->skillsPercent, sizeof(skillsPercent)); - memcpy(stats, conditionAttrs->stats, sizeof(stats)); - memcpy(statsPercent, conditionAttrs->statsPercent, sizeof(statsPercent)); - memcpy(buffs, conditionAttrs->buffs, sizeof(buffs)); - memcpy(buffsPercent, conditionAttrs->buffsPercent, sizeof(buffsPercent)); + simd_memcpy(skills, conditionAttrs->skills, std::size(skills)); + simd_memcpy(skillsPercent, conditionAttrs->skillsPercent, std::size(skillsPercent)); + simd_memcpy(stats, conditionAttrs->stats, std::size(stats)); + simd_memcpy(statsPercent, conditionAttrs->statsPercent, std::size(statsPercent)); + simd_memcpy(buffs, conditionAttrs->buffs, std::size(buffs)); + simd_memcpy(buffsPercent, conditionAttrs->buffsPercent, std::size(buffsPercent)); // Using std::array can only increment to the new instead of use memcpy absorbs = conditionAttrs->absorbs; diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index dead14304d3..3fdadc26a77 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -65,6 +65,54 @@ class Condition : public SharedObject { bool isPersistent() const; bool isRemovableOnDeath() const; + template + static void simd_memcpy(T* dest, const T* src, size_t count) { + size_t remaining = count * sizeof(T); + auto* dst = reinterpret_cast(dest); + const auto* source = reinterpret_cast(src); + +#if defined(__AVX2__) + while (remaining >= 32) { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast(source))); + dst += 32; + source += 32; + remaining -= 32; + } +#endif + +#if defined(__SSE2__) + while (remaining >= 16) { + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast(source))); + dst += 16; + source += 16; + remaining -= 16; + } + while (remaining >= 8) { + *reinterpret_cast(dst) = *reinterpret_cast(source); + dst += 8; + source += 8; + remaining -= 8; + } + while (remaining >= 4) { + *reinterpret_cast(dst) = *reinterpret_cast(source); + dst += 4; + source += 4; + remaining -= 4; + } + while (remaining >= 2) { + *reinterpret_cast(dst) = *reinterpret_cast(source); + dst += 2; + source += 2; + remaining -= 2; + } + if (remaining == 1) { + *dst = *source; + } +#else + std::memcpy(dest, src, count * sizeof(T)); +#endif + } + protected: uint8_t drainBodyStage = 0; int64_t endTime {}; diff --git a/src/game/scheduling/dispatcher.cpp b/src/game/scheduling/dispatcher.cpp index e9abefc08a3..059420df278 100644 --- a/src/game/scheduling/dispatcher.cpp +++ b/src/game/scheduling/dispatcher.cpp @@ -135,7 +135,7 @@ void Dispatcher::executeScheduledEvents() { if (task->execute() && task->isCycle()) { task->updateTime(); - threadScheduledTasks.emplace_back(task); + threadScheduledTasks.emplace(task); } else { scheduledTasksRef.erase(task->getId()); } @@ -174,14 +174,16 @@ void Dispatcher::mergeEvents() { constexpr auto serial = static_cast(TaskGroup::Serial); for (const auto &thread : threads) { - std::scoped_lock lock(thread->mutex); - if (!thread->tasks[serial].empty()) { - m_tasks[serial].insert(m_tasks[serial].end(), make_move_iterator(thread->tasks[serial].begin()), make_move_iterator(thread->tasks[serial].end())); - thread->tasks[serial].clear(); + { + std::scoped_lock lock(thread->mutex); + if (!thread->tasks[serial].empty()) { + m_tasks[serial].insert(m_tasks[serial].end(), make_move_iterator(thread->tasks[serial].begin()), make_move_iterator(thread->tasks[serial].end())); + thread->tasks[serial].clear(); + } } if (!thread->scheduledTasks.empty()) { - scheduledTasks.insert(make_move_iterator(thread->scheduledTasks.begin()), make_move_iterator(thread->scheduledTasks.end())); + scheduledTasks.insert(thread->scheduledTasks.begin(), thread->scheduledTasks.end()); thread->scheduledTasks.clear(); } } @@ -211,11 +213,9 @@ void Dispatcher::addEvent(std::function &&f, std::string_view contex uint64_t Dispatcher::scheduleEvent(const std::shared_ptr &task) { const auto &thread = getThreadTask(); - std::scoped_lock lock(thread->mutex); - auto eventId = scheduledTasksRef - .emplace(task->getId(), thread->scheduledTasks.emplace_back(task)) - .first->first; + thread->scheduledTasks.emplace(task); + auto eventId = scheduledTasksRef.emplace(task->getId(), task).first->first; notify(); return eventId; diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 6dbc20b06ff..11f467870cb 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -88,9 +88,10 @@ class Dispatcher { for (uint_fast16_t i = 0; i < threads.capacity(); ++i) { threads.emplace_back(std::make_unique()); } - }; - // Ensures that we don't accidentally copy it + scheduledTasksRef.reserve(2000); + } + Dispatcher(const Dispatcher &) = delete; Dispatcher operator=(const Dispatcher &) = delete; @@ -195,9 +196,8 @@ class Dispatcher { ThreadPool &threadPool; std::condition_variable signalSchedule; std::atomic_bool hasPendingTasks = false; - std::mutex dummyMutex; // This is only used for signaling the condition variable and not as an actual lock. + std::mutex dummyMutex; - // Thread Events struct ThreadTask { ThreadTask() { for (auto &task : tasks) { @@ -207,12 +207,11 @@ class Dispatcher { } std::array, static_cast(TaskGroup::Last)> tasks; - std::vector> scheduledTasks; + phmap::parallel_flat_hash_set_m> scheduledTasks; std::mutex mutex; }; - std::vector> threads; - // Main Events + std::vector> threads; std::array, static_cast(TaskGroup::Last)> m_tasks; phmap::btree_multiset, Task::Compare> scheduledTasks; phmap::parallel_flat_hash_map_m> scheduledTasksRef; diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index 26d48801ef1..81fbb18b138 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -71,50 +71,51 @@ class Task { utime = OTSYS_TIME() + delay; } - [[nodiscard]] bool hasTraceableContext() const { - const static auto tasksContext = std::unordered_set({ "Decay::checkDecay", - "Dispatcher::asyncEvent", - "Game::checkCreatureAttack", - "Game::checkCreatureWalk", - "Game::checkCreatures", - "Game::checkImbuements", - "Game::checkLight", - "Game::createFiendishMonsters", - "Game::createInfluencedMonsters", - "Game::updateCreatureWalk", - "Game::updateForgeableMonsters", - "GlobalEvents::think", - "LuaEnvironment::executeTimerEvent", - "Modules::executeOnRecvbyte", - "OutputMessagePool::sendAll", - "ProtocolGame::addGameTask", - "ProtocolGame::parsePacketFromDispatcher", - "Raids::checkRaids", - "SpawnMonster::checkSpawnMonster", - "SpawnMonster::scheduleSpawn", - "SpawnMonster::startup", - "SpawnNpc::checkSpawnNpc", - "Webhook::run", - "Protocol::sendRecvMessageCallback" }); + bool hasTraceableContext() const { + const static std::unordered_set tasksContext = { + "Decay::checkDecay", + "Dispatcher::asyncEvent", + "Game::checkCreatureAttack", + "Game::checkCreatureWalk", + "Game::checkCreatures", + "Game::checkImbuements", + "Game::checkLight", + "Game::createFiendishMonsters", + "Game::createInfluencedMonsters", + "Game::updateCreatureWalk", + "Game::updateForgeableMonsters", + "GlobalEvents::think", + "LuaEnvironment::executeTimerEvent", + "Modules::executeOnRecvbyte", + "OutputMessagePool::sendAll", + "ProtocolGame::addGameTask", + "ProtocolGame::parsePacketFromDispatcher", + "Raids::checkRaids", + "SpawnMonster::checkSpawnMonster", + "SpawnMonster::scheduleSpawn", + "SpawnMonster::startup", + "SpawnNpc::checkSpawnNpc", + "Webhook::run", + "Protocol::sendRecvMessageCallback" + }; + return tasksContext.contains(context); } struct Compare { bool operator()(const std::shared_ptr &a, const std::shared_ptr &b) const { - return a->utime < b->utime; + return a->getTime() < b->getTime(); } }; - std::function func = nullptr; + std::function func; std::string context; std::string functionName; int64_t utime = 0; int64_t expiration = 0; - uint64_t id = 0; uint32_t delay = 0; - bool cycle = false; bool log = true; diff --git a/src/io/fileloader.cpp b/src/io/fileloader.cpp index e590965fa11..de508ecdca5 100644 --- a/src/io/fileloader.cpp +++ b/src/io/fileloader.cpp @@ -24,13 +24,10 @@ namespace OTB { Identifier fileIdentifier; #if defined(__AVX2__) - // Use AVX2 para copiar 32 bytes de cada vez (caso aplicável) _mm256_storeu_si256(reinterpret_cast<__m256i*>(fileIdentifier.data()), _mm256_loadu_si256(reinterpret_cast(fileContents.data()))); #elif defined(__SSE2__) - // Use SSE2 para copiar 16 bytes de cada vez _mm_storeu_si128(reinterpret_cast<__m128i*>(fileIdentifier.data()), _mm_loadu_si128(reinterpret_cast(fileContents.data()))); #else - // Fallback para std::copy se nem AVX2 nem SSE2 estiverem disponíveis std::copy(fileContents.begin(), fileContents.begin() + fileIdentifier.size(), fileIdentifier.begin()); #endif diff --git a/src/io/fileloader.hpp b/src/io/fileloader.hpp index 6df7e16e554..07a0bd07188 100644 --- a/src/io/fileloader.hpp +++ b/src/io/fileloader.hpp @@ -116,7 +116,6 @@ class PropStream { remaining -= 1; } #else - // Fallback para memcpy se nem AVX2 nem SSE2 estiverem disponíveis memcpy(dst, src, remaining); #endif @@ -180,7 +179,6 @@ class PropStream { remaining -= 1; } #else - // Fallback para memcpy se nem AVX2 nem SSE2 estiverem disponíveis memcpy(dst, src, remaining); #endif @@ -271,7 +269,6 @@ class PropWriteStream { *dst = *addr; } #else - // Fallback para std::copy se nem AVX2 nem SSE2 estiverem disponíveis std::copy(addr, addr + remaining, std::back_inserter(buffer)); #endif } diff --git a/src/security/rsa.cpp b/src/security/rsa.cpp index d0dbc58148c..2b8948afa07 100644 --- a/src/security/rsa.cpp +++ b/src/security/rsa.cpp @@ -181,7 +181,13 @@ uint16_t RSA::decodeLength(char*&pos) const { default: break; } + +#if defined(__SSE2__) + __m128i temp = _mm_loadu_si128(reinterpret_cast(buffer)); + length = _mm_cvtsi128_si32(temp); +#else std::memcpy(&length, buffer, sizeof(length)); +#endif } return length; } diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index ed67d0a869d..6f461004e34 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -101,7 +101,6 @@ void NetworkMessage::addString(const std::string &value, const std::string &func remaining -= 1; } #else - // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available memcpy(dst, src, remaining); #endif @@ -173,7 +172,6 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) { remaining -= 1; } #else - // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available memcpy(dst, src, remaining); #endif @@ -231,7 +229,6 @@ void NetworkMessage::addPaddingBytes(size_t n) { remaining -= 1; } #else - // Fallback para o método original usando memset se nem AVX2 nem SSE2 estiverem disponíveis memset(dst, 0x33, remaining); #endif diff --git a/src/server/network/message/networkmessage.hpp b/src/server/network/message/networkmessage.hpp index c54501c6c3a..7cb69901fba 100644 --- a/src/server/network/message/networkmessage.hpp +++ b/src/server/network/message/networkmessage.hpp @@ -99,9 +99,7 @@ class NetworkMessage { remaining -= 1; } #else - // Fallback para o método original usando memcpy se nem AVX2 nem SSE2 estiverem disponíveis memcpy(&v, buffer + info.position, sizeof(T)); - spdlog::info("[{}]: AVX2/SSE2 not available, used memcpy to load {} bytes.", __FUNCTION__, sizeof(T)); #endif info.position += sizeof(T); @@ -178,9 +176,7 @@ class NetworkMessage { remaining -= 1; } #else - // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available memcpy(dst, src, remaining); - spdlog::info("[{}]: AVX2/SSE2 not available, used memcpy to copy {} bytes.", __FUNCTION__, remaining); #endif info.position += sizeof(T); diff --git a/src/server/network/message/outputmessage.hpp b/src/server/network/message/outputmessage.hpp index 6d76bbc8ace..29a29aa63be 100644 --- a/src/server/network/message/outputmessage.hpp +++ b/src/server/network/message/outputmessage.hpp @@ -77,7 +77,6 @@ class OutputMessage : public NetworkMessage { remaining -= 1; } #else - // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available memcpy(dst, src, remaining); #endif @@ -123,7 +122,6 @@ class OutputMessage : public NetworkMessage { remaining -= 1; } #else - // Fallback to original method using memcpy if neither AVX2 nor SSE2 are available memcpy(dst, src, remaining); #endif @@ -160,7 +158,6 @@ class OutputMessage : public NetworkMessage { *reinterpret_cast(buffer + outputBufferStart) = *reinterpret_cast(&addHeader); } #else - // Fallback to original method using memcpy if SSE2 is not available memcpy(buffer + outputBufferStart, &addHeader, sizeof(T)); #endif diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index e79d00883c0..ecfd21d8cca 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -121,19 +121,41 @@ void Protocol::XTEA_encrypt(OutputMessage &msg) const { // TODO: refactor this for not use c-style uint32_t precachedControlSum[32][2]; uint32_t sum = 0; - for (int32_t i = 0; i < 32; ++i) { - precachedControlSum[i][0] = (sum + newKey[sum & 3]); + + for (auto &i : precachedControlSum) { + i[0] = (sum + newKey[sum & 3]); sum -= delta; - precachedControlSum[i][1] = (sum + newKey[(sum >> 11) & 3]); + i[1] = (sum + newKey[(sum >> 11) & 3]); } while (readPos < messageLength) { std::array vData = {}; + +#if defined(__AVX2__) + __m128i data = _mm_loadu_si128(reinterpret_cast(buffer + readPos)); + _mm_storeu_si128(reinterpret_cast<__m128i*>(vData.data()), data); +#elif defined(__SSE2__) + __m128i data = _mm_loadl_epi64(reinterpret_cast(buffer + readPos)); + _mm_storel_epi64(reinterpret_cast<__m128i*>(vData.data()), data); +#else memcpy(vData.data(), buffer + readPos, 8); - for (int32_t i = 0; i < 32; ++i) { - vData[0] += ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ precachedControlSum[i][0]; - vData[1] += ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ precachedControlSum[i][1]; +#endif + + // XTEA encryption loop + for (auto &i : precachedControlSum) { + vData[0] += ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ i[0]; + vData[1] += ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ i[1]; } + +#if defined(__AVX2__) + data = _mm_loadu_si128(reinterpret_cast(vData.data())); + _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + readPos), data); +#elif defined(__SSE2__) + data = _mm_loadl_epi64(reinterpret_cast(vData.data())); + _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + readPos), data); +#else memcpy(buffer + readPos, vData.data(), 8); +#endif + readPos += 8; } } @@ -153,19 +175,42 @@ bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { // TODO: refactor this for not use c-style uint32_t precachedControlSum[32][2]; uint32_t sum = 0xC6EF3720; - for (int32_t i = 0; i < 32; ++i) { - precachedControlSum[i][0] = (sum + newKey[(sum >> 11) & 3]); + + for (auto &i : precachedControlSum) { + i[0] = (sum + newKey[(sum >> 11) & 3]); sum += delta; - precachedControlSum[i][1] = (sum + newKey[sum & 3]); + i[1] = (sum + newKey[sum & 3]); } while (readPos < messageLength) { std::array vData = {}; + +#if defined(__AVX2__) + __m128i data = _mm_loadu_si128(reinterpret_cast(buffer + readPos)); + _mm_storeu_si128(reinterpret_cast<__m128i*>(vData.data()), data); +#elif defined(__SSE2__) + __m128i data = _mm_loadl_epi64(reinterpret_cast(buffer + readPos)); + _mm_storel_epi64(reinterpret_cast<__m128i*>(vData.data()), data); +#else memcpy(vData.data(), buffer + readPos, 8); - for (int32_t i = 0; i < 32; ++i) { - vData[1] -= ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ precachedControlSum[i][0]; - vData[0] -= ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ precachedControlSum[i][1]; +#endif + + // XTEA decryption loop + for (auto &i : precachedControlSum) { + vData[1] -= ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ i[0]; + vData[0] -= ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ i[1]; } + +#if defined(__AVX2__) + data = _mm_loadu_si128(reinterpret_cast(vData.data())); + _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + readPos), data); + +#elif defined(__SSE2__) + data = _mm_loadl_epi64(reinterpret_cast(vData.data())); + _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + readPos), data); +#else memcpy(buffer + readPos, vData.data(), 8); +#endif + readPos += 8; } diff --git a/src/server/network/protocol/protocol.hpp b/src/server/network/protocol/protocol.hpp index d1b69ab8821..9a69e09e725 100644 --- a/src/server/network/protocol/protocol.hpp +++ b/src/server/network/protocol/protocol.hpp @@ -66,8 +66,19 @@ class Protocol : public std::enable_shared_from_this { encryptionEnabled = true; } void setXTEAKey(const uint32_t* newKey) { - memcpy(this->key.data(), newKey, sizeof(*newKey) * 4); + uint32_t* dst = this->key.data(); + +#if defined(__AVX2__) + __m128i avx_key = _mm_loadu_si128(reinterpret_cast(newKey)); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), avx_key); +#elif defined(__SSE2__) + __m128i sse_key = _mm_loadu_si128(reinterpret_cast(newKey)); + _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), sse_key); +#else + memcpy(dst, newKey, sizeof(uint32_t) * 4); +#endif } + void setChecksumMethod(ChecksumMethods_t method) { checksumMethod = method; } diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index e802b1b65f3..58337e83e86 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -1609,7 +1609,9 @@ NameEval_t validateName(const std::string &name) { for (const std::string &str : toks) { if (str.length() < 2) { return INVALID_TOKEN_LENGTH; - } else if (std::find(prohibitedWords.begin(), prohibitedWords.end(), str) != prohibitedWords.end()) { // searching for prohibited words + } + + if (std::find(prohibitedWords.begin(), prohibitedWords.end(), str) != prohibitedWords.end()) { // searching for prohibited words return INVALID_FORBIDDEN; } } From 6dbfd726b4412a6fddde5cef2322506b5dd45308 Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 17 Aug 2024 02:06:56 -0300 Subject: [PATCH 12/34] init --- src/server/network/message/outputmessage.cpp | 25 +++- src/server/network/message/outputmessage.hpp | 3 +- src/utils/lockfree.hpp | 121 +++++++++++++++++++ 3 files changed, 143 insertions(+), 6 deletions(-) create mode 100644 src/utils/lockfree.hpp diff --git a/src/server/network/message/outputmessage.cpp b/src/server/network/message/outputmessage.cpp index efed7fe8367..68daee2afd9 100644 --- a/src/server/network/message/outputmessage.cpp +++ b/src/server/network/message/outputmessage.cpp @@ -12,8 +12,10 @@ #include "outputmessage.hpp" #include "server/network/protocol/protocol.hpp" #include "game/scheduling/dispatcher.hpp" +#include "utils/lockfree.hpp" -const std::chrono::milliseconds OUTPUTMESSAGE_AUTOSEND_DELAY { 10 }; +constexpr uint16_t OUTPUTMESSAGE_FREE_LIST_CAPACITY = 2048; +constexpr std::chrono::milliseconds OUTPUTMESSAGE_AUTOSEND_DELAY { 10 }; void OutputMessagePool::scheduleSendAll() { g_dispatcher().scheduleEvent( @@ -23,7 +25,7 @@ void OutputMessagePool::scheduleSendAll() { void OutputMessagePool::sendAll() { // dispatcher thread - for (auto &protocol : bufferedProtocols) { + for (const auto &protocol : bufferedProtocols) { auto &msg = protocol->getCurrentBuffer(); if (msg) { protocol->send(std::move(msg)); @@ -35,7 +37,7 @@ void OutputMessagePool::sendAll() { } } -void OutputMessagePool::addProtocolToAutosend(Protocol_ptr protocol) { +void OutputMessagePool::addProtocolToAutosend(const Protocol_ptr &protocol) { // dispatcher thread if (bufferedProtocols.empty()) { scheduleSendAll(); @@ -53,5 +55,20 @@ void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr &protocol) } OutputMessage_ptr OutputMessagePool::getOutputMessage() { - return std::make_shared(); + LockfreePoolingAllocator allocator; + OutputMessage* rawPtr = allocator.allocate(1); + + try { + new (rawPtr) OutputMessage(); + } catch (...) { + allocator.deallocate(rawPtr, 1); + throw; + } + + return { rawPtr, [&allocator](OutputMessage*&ptr) mutable { + if (ptr) { + ptr->~OutputMessage(); + allocator.deallocate(ptr, 1); + } + } }; } diff --git a/src/server/network/message/outputmessage.hpp b/src/server/network/message/outputmessage.hpp index 29a29aa63be..deb61d6e9df 100644 --- a/src/server/network/message/outputmessage.hpp +++ b/src/server/network/message/outputmessage.hpp @@ -11,7 +11,6 @@ #include "server/network/message/networkmessage.hpp" #include "server/network/connection/connection.hpp" -#include class Protocol; @@ -205,7 +204,7 @@ class OutputMessagePool { static OutputMessage_ptr getOutputMessage(); - void addProtocolToAutosend(Protocol_ptr protocol); + void addProtocolToAutosend(const Protocol_ptr &protocol); void removeProtocolFromAutosend(const Protocol_ptr &protocol); private: diff --git a/src/utils/lockfree.hpp b/src/utils/lockfree.hpp new file mode 100644 index 00000000000..cb27890ef58 --- /dev/null +++ b/src/utils/lockfree.hpp @@ -0,0 +1,121 @@ +/** + * Canary - A free and open-source MMORPG server emulator + * Copyright (©) 2019-2024 OpenTibiaBR + * Repository: https://github.com/opentibiabr/canary + * License: https://github.com/opentibiabr/canary/blob/main/LICENSE + * Contributors: https://github.com/opentibiabr/canary/graphs/contributors + * Website: https://docs.opentibiabr.com/ + */ + +#pragma once + +#include +#include +#include +#include +#include + +const int TOTAL_THREADS = static_cast(std::thread::hardware_concurrency()); +const size_t LOCAL_CACHE_LIMIT = std::max(35 / TOTAL_THREADS, 5); +constexpr size_t STATIC_PREALLOCATION_SIZE = 100; + +struct StackNode { + void* data; + StackNode* next; +}; + +template +class LockfreeFreeList { +public: + LockfreeFreeList() : + head(nullptr) { } + + static LockfreeFreeList &get() { + static LockfreeFreeList instance; + return instance; + } + + bool pop(void*&result) { + StackNode* old_head = head.load(std::memory_order_acquire); + while (old_head != nullptr) { + if (head.compare_exchange_weak(old_head, old_head->next, std::memory_order_acquire)) { + result = old_head->data; + delete old_head; + return true; + } + + std::this_thread::yield(); + } + return false; + } + + bool push(void* data) { + auto* new_node = new StackNode { data, nullptr }; + StackNode* old_head = head.load(std::memory_order_relaxed); + do { + new_node->next = old_head; + } while (!head.compare_exchange_weak(old_head, new_node, std::memory_order_release, std::memory_order_relaxed)); + return true; + } + + void preallocate(const size_t numBlocks) { + for (size_t i = 0; i < numBlocks; ++i) { + void* p = operator new(TSize); + push(p); + } + } + +private: + std::atomic head; +}; + +template +class LockfreePoolingAllocator : public std::allocator { +public: + LockfreePoolingAllocator() = default; + + template >> + explicit constexpr LockfreePoolingAllocator(const U &) { } + using value_type = T; + + T* allocate(size_t) const { + ensurePreallocation(); + if (!localCache.empty()) { + void* p = localCache.back(); + localCache.pop_back(); + return static_cast(p); + } + + auto &inst = LockfreeFreeList::get(); + void* p; + if (!inst.pop(p)) { + p = operator new(sizeof(T)); + } + return static_cast(p); + } + + void deallocate(T* p, size_t) const { + if (localCache.size() < LOCAL_CACHE_LIMIT) { + localCache.push_back(p); + } else { + auto &inst = LockfreeFreeList::get(); + inst.push(p); + } + } + +private: + static thread_local std::vector localCache; + static std::once_flag preallocationFlag; + + static void ensurePreallocation() { + std::call_once(preallocationFlag, []() { + LockfreeFreeList::get().preallocate(STATIC_PREALLOCATION_SIZE); + }); + } +}; + +template +thread_local std::vector LockfreePoolingAllocator::localCache; + +template +std::once_flag LockfreePoolingAllocator::preallocationFlag; From 2b3bbca5efebbcd076be9c5adf2d423e003e07db Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 24 Aug 2024 10:43:04 -0300 Subject: [PATCH 13/34] test --- src/creatures/combat/spells.cpp | 2 +- src/creatures/combat/spells.hpp | 2 +- src/game/game.cpp | 8 ++++---- src/game/game.hpp | 4 ++-- src/items/weapons/weapons.cpp | 22 +++++++++++----------- src/items/weapons/weapons.hpp | 26 +++++++++++++------------- src/lua/callbacks/event_callback.cpp | 4 ++-- src/lua/callbacks/event_callback.hpp | 4 ++-- src/lua/creature/actions.hpp | 2 +- src/lua/creature/events.cpp | 2 +- src/lua/creature/events.hpp | 2 +- src/lua/creature/movement.hpp | 2 +- 12 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index 102b3b27c7a..dce79dadda8 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -771,7 +771,7 @@ uint32_t Spell::getManaCost(const std::shared_ptr &player) const { return 0; } -bool InstantSpell::playerCastInstant(std::shared_ptr player, std::string ¶m) { +bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std::string ¶m) { if (!playerSpellCheck(player)) { return false; } diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index b86354707b6..2771331f50f 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -399,7 +399,7 @@ class InstantSpell final : public Script, public Spell { public: using Script::Script; - virtual bool playerCastInstant(std::shared_ptr player, std::string ¶m); + virtual bool playerCastInstant(const std::shared_ptr &player, std::string ¶m); bool castSpell(const std::shared_ptr &creature) override; bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) override; diff --git a/src/game/game.cpp b/src/game/game.cpp index b7e7083eda5..1a1134a350d 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -704,7 +704,7 @@ void Game::loadMap(const std::string &path, const Position &pos) { map.loadMap(path, false, false, false, false, false, pos); } -std::shared_ptr Game::internalGetCylinder(std::shared_ptr player, const Position &pos) { +std::shared_ptr Game::internalGetCylinder(const std::shared_ptr &player, const Position &pos) { if (pos.x != 0xFFFF) { return map.getTile(pos); } @@ -4079,17 +4079,17 @@ void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) { } void Game::playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - std::shared_ptr player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } - std::shared_ptr thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_TOPDOWN_ITEM); + const auto &thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_TOPDOWN_ITEM); if (!thing) { return; } - std::shared_ptr item = thing->getItem(); + const auto &item = thing->getItem(); if (!item || item->getID() != itemId || !item->isRotatable() || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; diff --git a/src/game/game.hpp b/src/game/game.hpp index b6dc3e51c99..481eb80a51d 100644 --- a/src/game/game.hpp +++ b/src/game/game.hpp @@ -150,7 +150,7 @@ class Game { teamFinderMap.erase(leaderGuid); } - std::shared_ptr internalGetCylinder(std::shared_ptr player, const Position &pos); + std::shared_ptr internalGetCylinder(const std::shared_ptr &player, const Position &pos); std::shared_ptr internalGetThing(const std::shared_ptr &player, const Position &pos, int32_t index, uint32_t itemId, StackPosType_t type); static void internalGetPosition(const std::shared_ptr &item, Position &pos, uint8_t &stackpos); @@ -388,7 +388,7 @@ class Game { void playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier); void playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type); void playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position &pos); - void playerMoveThingFromDepotSearch(std::shared_ptr player, uint16_t itemId, uint8_t tier, uint8_t count, const Position &fromPos, const Position &toPos, bool allItems = false); + void playerMoveThingFromDepotSearch(const std::shared_ptr &player, uint16_t itemId, uint8_t tier, uint8_t count, const Position &fromPos, const Position &toPos, bool allItems = false); void playerRequestAddVip(uint32_t playerId, const std::string &name); void playerRequestRemoveVip(uint32_t playerId, uint32_t guid); diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index aaaafa8f179..8e91aa24448 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -133,7 +133,7 @@ int32_t Weapon::playerWeaponCheck(const std::shared_ptr &player, const s return 100; } -bool Weapon::useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const { +bool Weapon::useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; @@ -143,7 +143,7 @@ bool Weapon::useWeapon(std::shared_ptr player, std::shared_ptr ite return true; } -CombatDamage Weapon::getCombatDamage(CombatDamage combat, std::shared_ptr player, std::shared_ptr item, int32_t damageModifier) const { +CombatDamage Weapon::getCombatDamage(CombatDamage combat, const std::shared_ptr &player, const std::shared_ptr &item, int32_t damageModifier) const { // Local variables uint32_t level = player->getLevel(); int16_t elementalAttack = getElementDamageValue(); @@ -447,7 +447,7 @@ void WeaponMelee::configureWeapon(const ItemType &it) { Weapon::configureWeapon(it); } -bool WeaponMelee::useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const { +bool WeaponMelee::useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const { int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; @@ -507,7 +507,7 @@ bool WeaponMelee::useWeapon(std::shared_ptr player, std::shared_ptr player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const { +bool WeaponMelee::getSkillType(const std::shared_ptr &player, const std::shared_ptr &item, skills_t &skill, uint32_t &skillpoint) const { if (player->getAddAttackSkill() && player->getLastAttackBlockType() != BLOCK_IMMUNITY) { skillpoint = 1; } else { @@ -537,7 +537,7 @@ bool WeaponMelee::getSkillType(std::shared_ptr player, std::shared_ptr player, std::shared_ptr, std::shared_ptr item) const { +int32_t WeaponMelee::getElementDamage(const std::shared_ptr &player, std::shared_ptr, std::shared_ptr item) const { if (elementType == COMBAT_NONE) { return 0; } @@ -557,7 +557,7 @@ int16_t WeaponMelee::getElementDamageValue() const { return elementDamage; } -int32_t WeaponMelee::getWeaponDamage(std::shared_ptr player, std::shared_ptr, std::shared_ptr item, bool maxDamage /*= false*/) const { +int32_t WeaponMelee::getWeaponDamage(const std::shared_ptr &player, std::shared_ptr, std::shared_ptr item, bool maxDamage /*= false*/) const { using namespace std; int32_t attackSkill = player->getWeaponSkill(item); int32_t attackValue = std::max(0, item->getAttack()); @@ -597,7 +597,7 @@ void WeaponDistance::configureWeapon(const ItemType &it) { Weapon::configureWeapon(it); } -bool WeaponDistance::useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const { +bool WeaponDistance::useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const { int32_t damageModifier; const ItemType &it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { @@ -773,7 +773,7 @@ bool WeaponDistance::useWeapon(std::shared_ptr player, std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const { +int32_t WeaponDistance::getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const { if (elementType == COMBAT_NONE) { return 0; } @@ -808,7 +808,7 @@ int16_t WeaponDistance::getElementDamageValue() const { return elementDamage; } -int32_t WeaponDistance::getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage /*= false*/) const { +int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); bool hasElement = false; @@ -850,7 +850,7 @@ int32_t WeaponDistance::getWeaponDamage(std::shared_ptr player, std::sha return -normal_random(minValue, (maxValue * static_cast(player->getVocation()->distDamageMultiplier))); } -bool WeaponDistance::getSkillType(std::shared_ptr player, std::shared_ptr, skills_t &skill, uint32_t &skillpoint) const { +bool WeaponDistance::getSkillType(const std::shared_ptr &player, std::shared_ptr, skills_t &skill, uint32_t &skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { @@ -883,7 +883,7 @@ void WeaponWand::configureWeapon(const ItemType &it) { Weapon::configureWeapon(it); } -int32_t WeaponWand::getWeaponDamage(std::shared_ptr player, std::shared_ptr, std::shared_ptr, bool maxDamage /* = false*/) const { +int32_t WeaponWand::getWeaponDamage(const std::shared_ptr &player, std::shared_ptr, std::shared_ptr, bool maxDamage /* = false*/) const { if (!g_configManager().getBoolean(TOGGLE_CHAIN_SYSTEM, __FUNCTION__)) { // Returns maximum damage or a random value between minChange and maxChange return maxDamage ? -maxChange : -normal_random(minChange, maxChange); diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 527c6f61406..9ab450bc5b1 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -64,13 +64,13 @@ class Weapon : public Script { int32_t playerWeaponCheck(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t shootRange) const; static bool useFist(const std::shared_ptr &player, const std::shared_ptr &target); - virtual bool useWeapon(const std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const; + virtual bool useWeapon(const const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const; - virtual int32_t getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const = 0; - virtual int32_t getElementDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const = 0; + virtual int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const = 0; + virtual int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const = 0; virtual CombatType_t getElementType() const = 0; virtual int16_t getElementDamageValue() const = 0; - virtual CombatDamage getCombatDamage(CombatDamage combat, std::shared_ptr player, std::shared_ptr item, int32_t damageModifier) const; + virtual CombatDamage getCombatDamage(CombatDamage combat, const std::shared_ptr &player, std::shared_ptr item, int32_t damageModifier) const; uint16_t getID() const { return id; } @@ -284,17 +284,17 @@ class WeaponMelee final : public Weapon { void configureWeapon(const ItemType &it) override; - bool useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const override; + bool useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const override; - int32_t getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; - int32_t getElementDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const override; + int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; + int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const override; CombatType_t getElementType() const override { return elementType; } virtual int16_t getElementDamageValue() const override; private: - bool getSkillType(std::shared_ptr player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; + bool getSkillType(const std::shared_ptr &player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; uint16_t elementDamage = 0; CombatType_t elementType = COMBAT_NONE; }; @@ -312,17 +312,17 @@ class WeaponDistance final : public Weapon { return true; } - bool useWeapon(std::shared_ptr player, std::shared_ptr item, std::shared_ptr target) const override; + bool useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const override; - int32_t getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; - int32_t getElementDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item) const override; + int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; + int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const override; CombatType_t getElementType() const override { return elementType; } virtual int16_t getElementDamageValue() const override; private: - bool getSkillType(std::shared_ptr player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; + bool getSkillType(const std::shared_ptr &player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; CombatType_t elementType = COMBAT_NONE; uint16_t elementDamage = 0; @@ -338,7 +338,7 @@ class WeaponWand final : public Weapon { void configureWeapon(const ItemType &it) override; - int32_t getWeaponDamage(std::shared_ptr player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; + int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; int32_t getElementDamage(std::shared_ptr, std::shared_ptr, std::shared_ptr) const override { return 0; } diff --git a/src/lua/callbacks/event_callback.cpp b/src/lua/callbacks/event_callback.cpp index fb9161c0633..ea99635d7ab 100644 --- a/src/lua/callbacks/event_callback.cpp +++ b/src/lua/callbacks/event_callback.cpp @@ -940,7 +940,7 @@ void EventCallback::playerOnRequestQuestLine(const std::shared_ptr &play getScriptInterface()->callVoidFunction(2); } -void EventCallback::playerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) const { +void EventCallback::playerOnInventoryUpdate(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[{}] Call stack overflow", __FUNCTION__); return; @@ -964,7 +964,7 @@ void EventCallback::playerOnInventoryUpdate(std::shared_ptr player, cons getScriptInterface()->callVoidFunction(4); } -bool EventCallback::playerOnRotateItem(std::shared_ptr player, const std::shared_ptr &item, const Position &position) const { +bool EventCallback::playerOnRotateItem(const std::shared_ptr &player, const std::shared_ptr &item, const Position &position) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[{}] Call stack overflow", __FUNCTION__); return false; diff --git a/src/lua/callbacks/event_callback.hpp b/src/lua/callbacks/event_callback.hpp index 4d1333169a5..bd45f82902f 100644 --- a/src/lua/callbacks/event_callback.hpp +++ b/src/lua/callbacks/event_callback.hpp @@ -114,8 +114,8 @@ class EventCallback : public Script { void playerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId) const; void playerOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime) const; void playerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage) const; - void playerOnInventoryUpdate(std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) const; - bool playerOnRotateItem(std::shared_ptr player, const std::shared_ptr &item, const Position &position) const; + void playerOnInventoryUpdate(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip) const; + bool playerOnRotateItem(const std::shared_ptr &player, const std::shared_ptr &item, const Position &position) const; void playerOnWalk(const std::shared_ptr &player, Direction &dir) const; // Monster diff --git a/src/lua/creature/actions.hpp b/src/lua/creature/actions.hpp index fae38d5e0d0..f03ee5950b6 100644 --- a/src/lua/creature/actions.hpp +++ b/src/lua/creature/actions.hpp @@ -110,7 +110,7 @@ class Action : public Script { } std::function player, std::shared_ptr item, + const std::shared_ptr &player, std::shared_ptr item, const Position &fromPosition, std::shared_ptr target, const Position &toPosition, bool isHotkey )> diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index b70ffe6bf78..7210ce7e850 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -1247,7 +1247,7 @@ void Events::eventPlayerOnRequestQuestLine(const std::shared_ptr &player scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(const std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip) { +void Events::eventPlayerOnInventoryUpdate(const const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { return; diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index 27915383a86..d195cfa301b 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -116,7 +116,7 @@ class Events { void eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId); void eventOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime); void eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage); - void eventPlayerOnInventoryUpdate(const std::shared_ptr player, const std::shared_ptr &item, Slots_t slot, bool equip); + void eventPlayerOnInventoryUpdate(const const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip); // Monster void eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse); diff --git a/src/lua/creature/movement.hpp b/src/lua/creature/movement.hpp index a3e145d6247..65fef34cb36 100644 --- a/src/lua/creature/movement.hpp +++ b/src/lua/creature/movement.hpp @@ -268,7 +268,7 @@ class MoveEvent final : public Script, public SharedObject { // equipFunction std::function moveEvent, - std::shared_ptr player, + const std::shared_ptr &player, std::shared_ptr item, Slots_t slot, bool boolean From 80e336ace44bf036ffb1b3d218feb9d49cf2225a Mon Sep 17 00:00:00 2001 From: beats-dh Date: Mon, 26 Aug 2024 22:21:24 -0300 Subject: [PATCH 14/34] teste --- src/CMakeLists.txt | 3 +- src/creatures/combat/combat.cpp | 4 +- src/creatures/combat/condition.cpp | 6 +- src/creatures/creature.cpp | 8 +- src/creatures/monsters/monster.cpp | 2 +- src/creatures/npcs/npc.cpp | 2 +- .../players/cyclopedia/player_cyclopedia.cpp | 4 +- src/creatures/players/player.cpp | 8 +- src/game/bank/bank.cpp | 2 +- src/game/game.cpp | 235 +++++++++--------- src/game/game.hpp | 2 + src/io/iomarket.cpp | 4 +- src/items/containers/mailbox/mailbox.cpp | 2 +- src/items/decay/decay.cpp | 2 +- src/items/item.cpp | 4 +- src/items/tile.cpp | 8 +- src/items/weapons/weapons.cpp | 6 +- src/items/weapons/weapons.hpp | 20 +- src/lua/callbacks/creaturecallback.cpp | 2 +- src/lua/creature/actions.cpp | 2 +- src/lua/creature/events.hpp | 2 +- src/lua/creature/movement.cpp | 2 +- .../functions/core/game/bank_functions.cpp | 2 +- .../functions/core/game/game_functions.cpp | 2 +- .../functions/core/game/global_functions.cpp | 10 +- .../network/network_message_functions.cpp | 4 +- .../creatures/creature_functions.cpp | 6 +- .../creatures/player/player_functions.cpp | 10 +- src/map/house/house.cpp | 6 +- src/map/house/housetile.cpp | 4 +- src/server/network/protocol/protocolgame.cpp | 2 + src/utils/counter_pointer.hpp | 47 ++++ 32 files changed, 242 insertions(+), 181 deletions(-) create mode 100644 src/utils/counter_pointer.hpp diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index a6b1e83bccc..586f55a02d7 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -9,7 +9,8 @@ include(GNUInstallDirs) include(CanaryLib) # Define main executable target, set it up and link to main library -add_executable(${PROJECT_NAME} main.cpp) +add_executable(${PROJECT_NAME} main.cpp + utils/counter_pointer.hpp) if(MSVC) # Add executable icon for Windows diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index a2eb8411ce8..2fba90cfa77 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -68,7 +68,7 @@ CombatDamage Combat::getCombatDamage(const std::shared_ptr &creature, int32_t min, max; if (creature->getCombatValues(min, max)) { damage.primary.value = normal_random(min, max); - } else if (const auto player = creature->getPlayer()) { + } else if (const auto &player = creature->getPlayer()) { if (params.valueCallback) { params.valueCallback->getMinMaxValues(player, damage, params.useCharges); } else if (formulaType == COMBAT_FORMULA_LEVELMAGIC) { @@ -271,7 +271,7 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &caster, const s return RETURNVALUE_FIRSTGOUPSTAIRS; } - if (const auto player = caster->getPlayer()) { + if (const auto &player = caster->getPlayer()) { if (player->hasFlag(PlayerFlags_t::IgnoreProtectionZone)) { return RETURNVALUE_NOERROR; } diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 3d2518d443d..a946423577d 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -1130,14 +1130,14 @@ bool ConditionRegeneration::startCondition(std::shared_ptr creature) { return false; } - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } return true; } void ConditionRegeneration::endCondition(std::shared_ptr creature) { - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->sendStats(); } } @@ -2084,7 +2084,7 @@ void ConditionFeared::endCondition(std::shared_ptr creature) { /* * After a player is feared there's a 10 seconds before they can can feared again. */ - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->setImmuneFear(); } diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 265131a5427..056e282ddbd 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -168,7 +168,7 @@ void Creature::onCreatureWalk() { if (getNextStep(dir, flags)) { ReturnValue ret = g_game().internalMoveCreature(static_self_cast(), dir, flags); if (ret != RETURNVALUE_NOERROR) { - if (const auto player = getPlayer()) { + if (const auto &player = getPlayer()) { player->sendCancelMessage(ret); player->sendCancelWalk(); } @@ -491,7 +491,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s handleLostSummon(configTeleportSummons); } - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (player->isExerciseTraining()) { player->setTraining(false); } @@ -709,7 +709,7 @@ void Creature::onDeath() { for (const auto &killer : killers) { if (auto monster = getMonster()) { killer->onKilledMonster(monster); - } else if (auto player = getPlayer(); player && mostDamageCreature != killer) { + } else if (const auto &player = getPlayer(); player && mostDamageCreature != killer) { killer->onKilledPlayer(player, false); } } @@ -814,7 +814,7 @@ bool Creature::dropCorpse(std::shared_ptr lastHitCreature, std::shared dropLoot(corpse->getContainer(), lastHitCreature); corpse->startDecaying(); bool disallowedCorpses = corpse->isRewardCorpse() || (corpse->getID() == ITEM_MALE_CORPSE || corpse->getID() == ITEM_FEMALE_CORPSE); - const auto player = mostDamageCreature ? mostDamageCreature->getPlayer() : nullptr; + const auto &player = mostDamageCreature ? mostDamageCreature->getPlayer() : nullptr; auto corpseContainer = corpse->getContainer(); if (corpseContainer && player && !disallowedCorpses) { auto monster = getMonster(); diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index 971fca5f81c..fb031615f47 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -647,7 +647,7 @@ BlockType_t Monster::blockHit(const std::shared_ptr &attacker, const C } // Wheel of destiny - const auto player = attacker ? attacker->getPlayer() : nullptr; + const auto &player = attacker ? attacker->getPlayer() : nullptr; if (player && player->wheel()->getInstant("Ballistic Mastery")) { elementMod -= player->wheel()->checkElementSensitiveReduction(combatType); } diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 3acd12e672f..958fa475c23 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -70,7 +70,7 @@ bool Npc::canInteract(const Position &pos, uint32_t range /* = 4 */) { void Npc::onCreatureAppear(const std::shared_ptr &creature, bool isLogin) { Creature::onCreatureAppear(creature, isLogin); - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { onPlayerAppear(player); } diff --git a/src/creatures/players/cyclopedia/player_cyclopedia.cpp b/src/creatures/players/cyclopedia/player_cyclopedia.cpp index c74d385f964..6f94b5d46b1 100644 --- a/src/creatures/players/cyclopedia/player_cyclopedia.cpp +++ b/src/creatures/players/cyclopedia/player_cyclopedia.cpp @@ -42,7 +42,7 @@ void PlayerCyclopedia::loadDeathHistory(uint16_t page, uint16_t entriesPerPage) uint32_t playerID = m_player.getID(); std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { - const auto player = g_game().getPlayerByID(playerID); + const auto &player = g_game().getPlayerByID(playerID); if (!player) { return; } @@ -92,7 +92,7 @@ void PlayerCyclopedia::loadRecentKills(uint16_t page, uint16_t entriesPerPage) { uint32_t playerID = m_player.getID(); std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { - const auto player = g_game().getPlayerByID(playerID); + const auto &player = g_game().getPlayerByID(playerID); if (!player) { return; } diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 3f677ccb48a..ce122d0275d 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -968,7 +968,7 @@ bool Player::canWalkthrough(const std::shared_ptr &creature) { return true; } - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); std::shared_ptr monster = creature->getMonster(); std::shared_ptr npc = creature->getNpc(); if (monster) { @@ -1024,7 +1024,7 @@ bool Player::canWalkthroughEx(const std::shared_ptr &creature) { return true; } - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); std::shared_ptr npc = creature->getNpc(); if (player) { std::shared_ptr playerTile = player->getTile(); @@ -1844,7 +1844,7 @@ void Player::onAttackedCreatureChangeZone(ZoneType_t zone) { void Player::onRemoveCreature(const std::shared_ptr &creature, bool isLogout) { Creature::onRemoveCreature(creature, isLogout); - if (auto player = getPlayer(); player == creature) { + if (const auto &player = getPlayer(); player == creature) { if (isLogout) { onDeEquipInventory(); @@ -5125,7 +5125,7 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { return SKULL_NONE; } - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player && player->getSkull() == SKULL_NONE) { if (player.get() == this) { for (const auto &kill : unjustifiedKills) { diff --git a/src/game/bank/bank.cpp b/src/game/bank/bank.cpp index 6798250cced..ff56c5518ba 100644 --- a/src/game/bank/bank.cpp +++ b/src/game/bank/bank.cpp @@ -25,7 +25,7 @@ Bank::~Bank() { if (bankable == nullptr || bankable->isOnline()) { return; } - const auto player = bankable->getPlayer(); + const auto &player = bankable->getPlayer(); if (player && !player->isOnline()) { g_saveManager().savePlayer(player); diff --git a/src/game/game.cpp b/src/game/game.cpp index 1a1134a350d..d2a2c5567ff 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -54,6 +54,7 @@ #include "enums/account_errors.hpp" #include "enums/account_coins.hpp" #include "enums/player_blessings.hpp" +#include "utils/counter_pointer.hpp" #include @@ -532,6 +533,14 @@ void Game::start(ServiceManager* manager) { marketItemsPriceIntervalMS, [this] { loadItemsPrice(); }, "Game::loadItemsPrice" ); } + + g_dispatcher().cycleEvent( + 5000, [this] { teste(); }, "Calling GC" + ); +} + +void Game::teste() const { + g_beats().countAllReferencesAndClean(); } GameState_t Game::getGameState() const { @@ -866,7 +875,7 @@ void Game::internalGetPosition(const std::shared_ptr &item, Position &pos, std::shared_ptr topParent = item->getTopParent(); if (topParent) { - if (const auto player = std::dynamic_pointer_cast(topParent)) { + if (const auto &player = std::dynamic_pointer_cast(topParent)) { pos.x = 0xFFFF; std::shared_ptr container = std::dynamic_pointer_cast(item->getParent()); @@ -1215,7 +1224,7 @@ void Game::executeDeath(uint32_t creatureId) { void Game::playerTeleport(uint32_t playerId, const Position &newPosition) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->hasFlag(PlayerFlags_t::CanMapClickTeleport)) { return; } @@ -1299,7 +1308,7 @@ FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string &file) { void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -1363,7 +1372,7 @@ void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t } void Game::playerMoveCreatureByID(uint32_t playerId, uint32_t movingCreatureId, const Position &movingCreatureOrigPos, const Position &toPos) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -1481,7 +1490,7 @@ ReturnValue Game::internalMoveCreature(const std::shared_ptr &creature creature->setLastPosition(creature->getPosition()); const Position ¤tPos = creature->getPosition(); Position destPos = getNextPosition(direction, currentPos); - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); bool diagonalMovement = (direction & DIRECTION_DIAGONAL_MASK) != 0; if (player && !diagonalMovement) { @@ -1588,7 +1597,7 @@ ReturnValue Game::internalMoveCreature(const std::shared_ptr &creature } void Game::playerMoveItemByPlayerID(uint32_t playerId, const Position &fromPos, uint16_t itemId, uint8_t fromStackPos, const Position &toPos, uint8_t count) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -2361,7 +2370,7 @@ std::tuple Game::addItemBatch(const std::shared } metrics::method_latency measure(__METHOD_NAME__); - const auto player = toCylinder->getPlayer(); + const auto &player = toCylinder->getPlayer(); bool dropping = false; auto setupDestination = [&]() -> std::shared_ptr { if (autoContainerId == 0) { @@ -2601,7 +2610,7 @@ bool Game::removeMoney(const std::shared_ptr &cylinder, uint64_t money } } - const auto player = useBalance ? std::dynamic_pointer_cast(cylinder) : nullptr; + const auto &player = useBalance ? std::dynamic_pointer_cast(cylinder) : nullptr; uint64_t balance = 0; if (useBalance && player) { balance = player->getBankBalance(); @@ -3306,7 +3315,7 @@ Slots_t getSlotType(const ItemType &it) { // Implementation of player invoked events void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = false*/, uint8_t tier /* = 0*/) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3382,7 +3391,7 @@ void Game::playerEquipItem(uint32_t playerId, uint16_t itemId, bool hasTier /* = } void Game::playerMove(uint32_t playerId, Direction direction) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3395,7 +3404,7 @@ void Game::playerMove(uint32_t playerId, Direction direction) { } void Game::forcePlayerMove(uint32_t playerId, Direction direction) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3422,7 +3431,7 @@ bool Game::playerBroadcastMessage(const std::shared_ptr &player, const s } void Game::playerCreatePrivateChannel(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isPremium()) { return; } @@ -3436,7 +3445,7 @@ void Game::playerCreatePrivateChannel(uint32_t playerId) { } void Game::playerChannelInvite(uint32_t playerId, const std::string &name) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3459,7 +3468,7 @@ void Game::playerChannelInvite(uint32_t playerId, const std::string &name) { } void Game::playerChannelExclude(uint32_t playerId, const std::string &name) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3482,7 +3491,7 @@ void Game::playerChannelExclude(uint32_t playerId, const std::string &name) { } void Game::playerRequestChannels(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3491,7 +3500,7 @@ void Game::playerRequestChannels(uint32_t playerId) { } void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3513,7 +3522,7 @@ void Game::playerOpenChannel(uint32_t playerId, uint16_t channelId) { } void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3522,7 +3531,7 @@ void Game::playerCloseChannel(uint32_t playerId, uint16_t channelId) { } void Game::playerOpenPrivateChannel(uint32_t playerId, std::string &receiver) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3552,7 +3561,7 @@ void Game::playerCloseNpcChannel(uint32_t playerId) { } void Game::playerReceivePing(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3561,7 +3570,7 @@ void Game::playerReceivePing(uint32_t playerId) { } void Game::playerReceivePingBack(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3570,7 +3579,7 @@ void Game::playerReceivePingBack(uint32_t playerId) { } void Game::playerAutoWalk(uint32_t playerId, const std::vector &listDir) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3581,7 +3590,7 @@ void Game::playerAutoWalk(uint32_t playerId, const std::vector &listD } void Game::forcePlayerAutoWalk(uint32_t playerId, const std::vector &listDir) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3598,7 +3607,7 @@ void Game::forcePlayerAutoWalk(uint32_t playerId, const std::vector & } void Game::playerStopAutoWalk(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3608,7 +3617,7 @@ void Game::playerStopAutoWalk(uint32_t playerId) { void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint16_t fromItemId, const Position &toPos, uint8_t toStackPos, uint16_t toItemId) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3746,7 +3755,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t f void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPos, uint8_t index, uint16_t itemId) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -3849,7 +3858,7 @@ void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPo void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uint8_t fromStackPos, uint32_t creatureId, uint16_t itemId) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4003,7 +4012,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uin } void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4013,7 +4022,7 @@ void Game::playerCloseContainer(uint32_t playerId, uint8_t cid) { } void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4065,7 +4074,7 @@ void Game::playerMoveUpContainer(uint32_t playerId, uint8_t cid) { } void Game::playerUpdateContainer(uint32_t playerId, uint8_t cid) { - const auto player = getPlayerByGUID(playerId); + const auto &player = getPlayerByGUID(playerId); if (!player) { return; } @@ -4134,7 +4143,7 @@ void Game::playerRotateItem(uint32_t playerId, const Position &pos, uint8_t stac } void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -4190,7 +4199,7 @@ void Game::playerConfigureShowOffSocket(uint32_t playerId, const Position &pos, } void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t podiumVisible, uint8_t direction) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -4320,7 +4329,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Pos } void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4469,7 +4478,7 @@ void Game::unwrapItem(const std::shared_ptr &item, uint16_t unWrapId, cons } void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std::string &text) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4533,7 +4542,7 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: } void Game::playerBrowseField(uint32_t playerId, const Position &pos) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4593,7 +4602,7 @@ void Game::playerBrowseField(uint32_t playerId, const Position &pos) { } void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackpos, uint8_t count, bool allItems) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4634,7 +4643,7 @@ void Game::playerStowItem(uint32_t playerId, const Position &pos, uint16_t itemI } void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t count, uint8_t) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4709,7 +4718,7 @@ void Game::playerStashWithdraw(uint32_t playerId, uint16_t itemId, uint32_t coun } void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_t index, uint8_t containerCategory) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4734,7 +4743,7 @@ void Game::playerSeekInContainer(uint32_t playerId, uint8_t containerId, uint16_ } void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t windowTextId, const std::string &text) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4751,7 +4760,7 @@ void Game::playerUpdateHouseWindow(uint32_t playerId, uint8_t listId, uint32_t w } void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t stackPos, uint32_t tradePlayerId, uint16_t itemId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -4925,7 +4934,7 @@ bool Game::internalStartTrade(const std::shared_ptr &player, const std:: } void Game::playerAcceptTrade(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5058,7 +5067,7 @@ std::string Game::getTradeErrorDescription(ReturnValue ret, const std::shared_pt } void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t index) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5117,7 +5126,7 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t } void Game::playerCloseTrade(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5172,7 +5181,7 @@ void Game::playerBuyItem(uint32_t playerId, uint16_t itemId, uint8_t count, uint return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5228,7 +5237,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5258,7 +5267,7 @@ void Game::playerSellItem(uint32_t playerId, uint16_t itemId, uint8_t count, uin } void Game::playerCloseShop(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5267,7 +5276,7 @@ void Game::playerCloseShop(uint32_t playerId) { } void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5297,7 +5306,7 @@ void Game::playerLookInShop(uint32_t playerId, uint16_t itemId, uint8_t count) { } void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, uint8_t stackPos) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5332,7 +5341,7 @@ void Game::playerLookAt(uint32_t playerId, uint16_t itemId, const Position &pos, } void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5367,7 +5376,7 @@ void Game::playerLookInBattleList(uint32_t playerId, uint32_t creatureId) { } void Game::playerQuickLoot(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, const std::shared_ptr &defaultItem, bool lootAllCorpses, bool autoLoot) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5557,7 +5566,7 @@ void Game::playerLootAllCorpses(const std::shared_ptr &player, const Pos } void Game::playerSetManagedContainer(uint32_t playerId, ObjectCategory_t category, const Position &pos, uint16_t itemId, uint8_t stackPos, bool isLootContainer) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || pos.x != 0xffff) { return; } @@ -5602,7 +5611,7 @@ void Game::playerSetManagedContainer(uint32_t playerId, ObjectCategory_t categor } void Game::playerClearManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5619,7 +5628,7 @@ void Game::playerClearManagedContainer(uint32_t playerId, ObjectCategory_t categ } void Game::playerOpenManagedContainer(uint32_t playerId, ObjectCategory_t category, bool isLootContainer) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5633,7 +5642,7 @@ void Game::playerOpenManagedContainer(uint32_t playerId, ObjectCategory_t catego } void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5642,7 +5651,7 @@ void Game::playerSetQuickLootFallback(uint32_t playerId, bool fallback) { } void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t filter, const std::vector &itemIds) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5655,7 +5664,7 @@ void Game::playerQuickLootBlackWhitelist(uint32_t playerId, QuickLootFilter_t fi * Depot search system ******************************************************************************/ void Game::playerRequestDepotItems(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isDepotSearchAvailable()) { return; } @@ -5670,7 +5679,7 @@ void Game::playerRequestDepotItems(uint32_t playerId) { } void Game::playerRequestCloseDepotSearch(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5680,7 +5689,7 @@ void Game::playerRequestCloseDepotSearch(uint32_t playerId) { } void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint8_t tier) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5695,7 +5704,7 @@ void Game::playerRequestDepotSearchItem(uint32_t playerId, uint16_t itemId, uint } void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, uint8_t tier, uint8_t type) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpenOnItem(itemId)) { return; } @@ -5710,7 +5719,7 @@ void Game::playerRequestDepotSearchRetrieve(uint32_t playerId, uint16_t itemId, } void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Position &pos) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->isDepotSearchOpen()) { return; } @@ -5725,7 +5734,7 @@ void Game::playerRequestOpenContainerFromDepotSearch(uint32_t playerId, const Po } void Game::playerCancelAttackAndFollow(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5736,7 +5745,7 @@ void Game::playerCancelAttackAndFollow(uint32_t playerId) { } void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5767,7 +5776,7 @@ void Game::playerSetAttackedCreature(uint32_t playerId, uint32_t creatureId) { } void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5778,7 +5787,7 @@ void Game::playerFollowCreature(uint32_t playerId, uint32_t creatureId) { } void Game::playerSetFightModes(uint32_t playerId, FightMode_t fightMode, bool chaseMode, bool secureMode) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5793,7 +5802,7 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string &name) { return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5829,7 +5838,7 @@ void Game::playerRequestAddVip(uint32_t playerId, const std::string &name) { } void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5838,7 +5847,7 @@ void Game::playerRequestRemoveVip(uint32_t playerId, uint32_t guid) { } void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::string &description, uint32_t icon, bool notify, std::vector vipGroupsId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5847,7 +5856,7 @@ void Game::playerRequestEditVip(uint32_t playerId, uint32_t guid, const std::str } void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t slot, bool protectionCharm) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5876,7 +5885,7 @@ void Game::playerApplyImbuement(uint32_t playerId, uint16_t imbuementid, uint8_t } void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { - const auto player = getPlayerByID(playerid); + const auto &player = getPlayerByID(playerid); if (!player) { return; } @@ -5894,7 +5903,7 @@ void Game::playerClearImbuement(uint32_t playerid, uint8_t slot) { } void Game::playerCloseImbuementWindow(uint32_t playerid) { - const auto player = getPlayerByID(playerid); + const auto &player = getPlayerByID(playerid); if (!player) { return; } @@ -5903,7 +5912,7 @@ void Game::playerCloseImbuementWindow(uint32_t playerid) { } void Game::playerTurn(uint32_t playerId, Direction dir) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5925,7 +5934,7 @@ void Game::playerRequestOutfit(uint32_t playerId) { return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5934,7 +5943,7 @@ void Game::playerRequestOutfit(uint32_t playerId) { } void Game::playerToggleMount(uint32_t playerId, bool mount) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -5947,7 +5956,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMoun return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -6014,7 +6023,7 @@ void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMoun } void Game::playerShowQuestLog(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -6024,7 +6033,7 @@ void Game::playerShowQuestLog(uint32_t playerId) { } void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -6034,7 +6043,7 @@ void Game::playerShowQuestLine(uint32_t playerId, uint16_t questId) { } void Game::playerSay(uint32_t playerId, uint16_t channelId, SpeakClasses type, const std::string &receiver, const std::string &text) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8152,7 +8161,7 @@ void Game::playerInviteToParty(uint32_t playerId, uint32_t invitedId) { return; } - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8191,7 +8200,7 @@ void Game::updatePlayerHelpers(const std::shared_ptr &player) { } void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8215,7 +8224,7 @@ void Game::playerJoinParty(uint32_t playerId, uint32_t leaderId) { } void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8234,7 +8243,7 @@ void Game::playerRevokePartyInvitation(uint32_t playerId, uint32_t invitedId) { } void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8253,7 +8262,7 @@ void Game::playerPassPartyLeadership(uint32_t playerId, uint32_t newLeaderId) { } void Game::playerLeaveParty(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8268,7 +8277,7 @@ void Game::playerLeaveParty(uint32_t playerId) { } void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpActive) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8283,7 +8292,7 @@ void Game::playerEnableSharedPartyExperience(uint32_t playerId, bool sharedExpAc } void Game::sendGuildMotd(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8295,7 +8304,7 @@ void Game::sendGuildMotd(uint32_t playerId) { } void Game::kickPlayer(uint32_t playerId, bool displayEffect) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8426,7 +8435,7 @@ std::string Game::generateVocationConditionHighscore(uint32_t vocation) { } void Game::processHighscoreResults(const DBResult_ptr &result, uint32_t playerID, uint8_t category, uint32_t vocation, uint8_t entriesPerPage) { - const auto player = g_game().getPlayerByID(playerID); + const auto &player = g_game().getPlayerByID(playerID); if (!player) { return; } @@ -8564,7 +8573,7 @@ std::string Game::getSkillNameById(uint8_t &skill) { } void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string &targetName, uint8_t reportType, uint8_t reportReason, const std::string &comment, const std::string &translation) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8574,7 +8583,7 @@ void Game::playerReportRuleViolationReport(uint32_t playerId, const std::string } void Game::playerReportBug(uint32_t playerId, const std::string &message, const Position &position, uint8_t category) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8584,7 +8593,7 @@ void Game::playerReportBug(uint32_t playerId, const std::string &message, const } void Game::playerDebugAssert(uint32_t playerId, const std::string &assertLine, const std::string &date, const std::string &description, const std::string &comment) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8599,7 +8608,7 @@ void Game::playerDebugAssert(uint32_t playerId, const std::string &assertLine, c } void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uint8_t option, int8_t index, uint16_t raceId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8608,7 +8617,7 @@ void Game::playerPreyAction(uint32_t playerId, uint8_t slot, uint8_t action, uin } void Game::playerTaskHuntingAction(uint32_t playerId, uint8_t slot, uint8_t action, bool upgrade, uint16_t raceId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8653,7 +8662,7 @@ void Game::playerNpcGreet(uint32_t playerId, uint32_t npcId) { } void Game::playerLeaveMarket(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8662,7 +8671,7 @@ void Game::playerLeaveMarket(uint32_t playerId) { } void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8687,7 +8696,7 @@ void Game::playerBrowseMarket(uint32_t playerId, uint16_t itemId, uint8_t tier) } void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8702,7 +8711,7 @@ void Game::playerBrowseMarketOwnOffers(uint32_t playerId) { } void Game::playerBrowseMarketOwnHistory(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -8854,7 +8863,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite // Initialize variables // Before creating the offer we will compare it with the RETURN VALUE ERROR std::ostringstream offerStatus; - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); const ItemType &it = Item::items[itemId]; // Make sure everything is ok before the create market offer starts @@ -8937,7 +8946,7 @@ void Game::playerCreateMarketOffer(uint32_t playerId, uint8_t type, uint16_t ite } void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->getAccount()) { return; } @@ -9020,7 +9029,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16_t counter, uint16_t amount) { std::ostringstream offerStatus; - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || !player->getAccount()) { offerStatus << "Failed to load player"; return; @@ -9292,7 +9301,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 } void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const std::string &buffer) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9322,7 +9331,7 @@ void Game::sendOfflineTrainingDialog(const std::shared_ptr &player) { } void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, uint8_t button, uint8_t choice) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9357,7 +9366,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui void Game::playerForgeFuseItems(uint32_t playerId, ForgeAction_t actionType, uint16_t firstItemId, uint8_t tier, uint16_t secondItemId, bool usedCore, bool reduceTierLoss, bool convergence) { metrics::method_latency measure(__METHOD_NAME__); - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9384,7 +9393,7 @@ void Game::playerForgeFuseItems(uint32_t playerId, ForgeAction_t actionType, uin } void Game::playerForgeTransferItemTier(uint32_t playerId, ForgeAction_t actionType, uint16_t donorItemId, uint8_t tier, uint16_t receiveItemId, bool convergence) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9399,7 +9408,7 @@ void Game::playerForgeTransferItemTier(uint32_t playerId, ForgeAction_t actionTy } void Game::playerForgeResourceConversion(uint32_t playerId, ForgeAction_t actionType) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9414,7 +9423,7 @@ void Game::playerForgeResourceConversion(uint32_t playerId, ForgeAction_t action } void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9429,7 +9438,7 @@ void Game::playerBrowseForgeHistory(uint32_t playerId, uint8_t page) { } void Game::playerBosstiarySlot(uint32_t playerId, uint8_t slotId, uint32_t selectedBossId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9456,7 +9465,7 @@ void Game::playerBosstiarySlot(uint32_t playerId, uint8_t slotId, uint32_t selec } void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, const Position &pos, uint8_t stackPos, const uint16_t itemId, uint8_t direction, const std::pair &podiumAndMonsterVisible) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || pos.x == 0xFFFF) { return; } @@ -9562,7 +9571,7 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con } void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t stackPos, const uint16_t itemId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9651,7 +9660,7 @@ void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t st } void Game::playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpen) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player || player->isRemoved()) { return; } @@ -9683,7 +9692,7 @@ void Game::playerRequestInventoryImbuements(uint32_t playerId, bool isTrackerOpe } void Game::playerOpenWheel(uint32_t playerId, uint32_t ownerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9703,7 +9712,7 @@ void Game::playerOpenWheel(uint32_t playerId, uint32_t ownerId) { } void Game::playerSaveWheel(uint32_t playerId, NetworkMessage &msg) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9718,7 +9727,7 @@ void Game::playerSaveWheel(uint32_t playerId, NetworkMessage &msg) { } void Game::playerWheelGemAction(uint32_t playerId, NetworkMessage &msg) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -9755,7 +9764,7 @@ void Game::playerWheelGemAction(uint32_t playerId, NetworkMessage &msg) { ********************/ void Game::updatePlayerSaleItems(uint32_t playerId) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } @@ -10332,7 +10341,7 @@ void Game::removePlayerUniqueLogin(const std::shared_ptr &player) { } void Game::playerCheckActivity(const std::string &playerName, int interval) { - const auto player = getPlayerUniqueLogin(playerName); + const auto &player = getPlayerUniqueLogin(playerName); if (!player) { return; } @@ -10367,7 +10376,7 @@ void Game::playerCheckActivity(const std::string &playerName, int interval) { } void Game::playerRewardChestCollect(uint32_t playerId, const Position &pos, uint16_t itemId, uint8_t stackPos, uint32_t maxMoveItems /* = 0*/) { - const auto player = getPlayerByID(playerId); + const auto &player = getPlayerByID(playerId); if (!player) { return; } diff --git a/src/game/game.hpp b/src/game/game.hpp index 481eb80a51d..8e0cd662c6e 100644 --- a/src/game/game.hpp +++ b/src/game/game.hpp @@ -971,6 +971,8 @@ class Game { std::string generateHighscoreQueryForOurRank(const std::string &categoryName, uint8_t entriesPerPage, uint32_t playerGUID, uint32_t vocation); std::string generateHighscoreOrGetCachedQueryForEntries(const std::string &categoryName, uint32_t page, uint8_t entriesPerPage, uint32_t vocation); std::string generateHighscoreOrGetCachedQueryForOurRank(const std::string &categoryName, uint8_t entriesPerPage, uint32_t playerGUID, uint32_t vocation); + + void teste() const; }; constexpr auto g_game = Game::getInstance; diff --git a/src/io/iomarket.cpp b/src/io/iomarket.cpp index b074b07cbaf..8d08c54a920 100644 --- a/src/io/iomarket.cpp +++ b/src/io/iomarket.cpp @@ -168,7 +168,7 @@ void IOMarket::processExpiredOffers(const DBResult_ptr &result, bool) { continue; } - const auto player = g_game().getPlayerByGUID(playerId, true); + const auto &player = g_game().getPlayerByGUID(playerId, true); if (!player) { continue; } @@ -216,7 +216,7 @@ void IOMarket::processExpiredOffers(const DBResult_ptr &result, bool) { } else { uint64_t totalPrice = result->getNumber("price") * amount; - const auto player = g_game().getPlayerByGUID(playerId); + const auto &player = g_game().getPlayerByGUID(playerId); if (player) { player->setBankBalance(player->getBankBalance() + totalPrice); } else { diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index 3371ac049ed..b0714b87e7b 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -88,7 +88,7 @@ bool Mailbox::sendItem(const std::shared_ptr &item) const { } } - const auto player = g_game().getPlayerByName(receiver, true); + const auto &player = g_game().getPlayerByName(receiver, true); std::string writer; time_t date = time(nullptr); std::string text; diff --git a/src/items/decay/decay.cpp b/src/items/decay/decay.cpp index 94ca7d00ab3..81ef6bc708c 100644 --- a/src/items/decay/decay.cpp +++ b/src/items/decay/decay.cpp @@ -163,7 +163,7 @@ void Decay::internalDecayItem(const std::shared_ptr &item) { } if (it.decayTo != 0) { - const auto player = item->getHoldingPlayer(); + const auto &player = item->getHoldingPlayer(); if (player) { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { diff --git a/src/items/item.cpp b/src/items/item.cpp index 81a2c2c4d30..9c9857ace98 100644 --- a/src/items/item.cpp +++ b/src/items/item.cpp @@ -100,7 +100,7 @@ void Item::setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { } void Item::addImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { - const auto player = getHoldingPlayer(); + const auto &player = getHoldingPlayer(); if (!player) { return; } @@ -335,7 +335,7 @@ bool Item::isOwner(uint32_t ownerId) const { const auto &player = g_game().getPlayerByID(ownerId); return player && player->getGUID() == getOwnerId(); } - if (auto player = g_game().getPlayerByGUID(ownerId); player) { + if (const auto &player = g_game().getPlayerByGUID(ownerId); player) { return player->getID() == getOwnerId(); } return false; diff --git a/src/items/tile.cpp b/src/items/tile.cpp index f0fc757cd77..b8f7af486fe 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -259,7 +259,7 @@ std::shared_ptr Tile::getBottomCreature() const { std::shared_ptr Tile::getTopVisibleCreature(const std::shared_ptr &creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player && player->isAccessPlayer()) { return getTopCreature(); } @@ -272,7 +272,7 @@ std::shared_ptr Tile::getTopVisibleCreature(const std::shared_ptrisInvisible()) { - const auto player = tileCreature->getPlayer(); + const auto &player = tileCreature->getPlayer(); if (!player || !player->isInGhostMode()) { return tileCreature; } @@ -286,7 +286,7 @@ std::shared_ptr Tile::getTopVisibleCreature(const std::shared_ptr Tile::getBottomVisibleCreature(const std::shared_ptr &creature) const { if (const CreatureVector* creatures = getCreatures()) { if (creature) { - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player && player->isAccessPlayer()) { return getBottomCreature(); } @@ -663,7 +663,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr &thing, uint32_ } const CreatureVector* creatures = getCreatures(); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, tileFlags) && !player->isAccessPlayer()) { for (auto &tileCreature : *creatures) { if (!player->canWalkthrough(tileCreature)) { diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 8e91aa24448..9cf7128648b 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -260,7 +260,7 @@ void Weapon::internalUseWeapon(const std::shared_ptr &player, const std: onUsedWeapon(player, item, target->getTile()); } -void Weapon::internalUseWeapon(const std::shared_ptr &player, const auto item, const std::shared_ptr &tile) const { +void Weapon::internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &tile) const { if (isLoadedCallback()) { LuaVariant var; var.type = VARIANT_TARGETPOSITION; @@ -597,7 +597,7 @@ void WeaponDistance::configureWeapon(const ItemType &it) { Weapon::configureWeapon(it); } -bool WeaponDistance::useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const { +bool WeaponDistance::useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const { int32_t damageModifier; const ItemType &it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { @@ -850,7 +850,7 @@ int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr &player, s return -normal_random(minValue, (maxValue * static_cast(player->getVocation()->distDamageMultiplier))); } -bool WeaponDistance::getSkillType(const std::shared_ptr &player, std::shared_ptr, skills_t &skill, uint32_t &skillpoint) const { +bool WeaponDistance::getSkillType(const std::shared_ptr &player, const std::shared_ptr&, skills_t &skill, uint32_t &skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 9ab450bc5b1..b3822f05dd6 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -64,13 +64,13 @@ class Weapon : public Script { int32_t playerWeaponCheck(const std::shared_ptr &player, const std::shared_ptr &target, uint8_t shootRange) const; static bool useFist(const std::shared_ptr &player, const std::shared_ptr &target); - virtual bool useWeapon(const const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const; + virtual bool useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const; virtual int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const = 0; virtual int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const = 0; virtual CombatType_t getElementType() const = 0; virtual int16_t getElementDamageValue() const = 0; - virtual CombatDamage getCombatDamage(CombatDamage combat, const std::shared_ptr &player, std::shared_ptr item, int32_t damageModifier) const; + virtual CombatDamage getCombatDamage(CombatDamage combat, const std::shared_ptr &player, const std::shared_ptr &item, int32_t damageModifier) const; uint16_t getID() const { return id; } @@ -225,10 +225,10 @@ class Weapon : public Script { protected: void internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target, int32_t damageModifier, int32_t cleavePercent = 0) const; - void internalUseWeapon(const std::shared_ptr &player, const auto item, const std::shared_ptr &tile) const; + void internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &tile) const; private: - virtual bool getSkillType(std::shared_ptr, std::shared_ptr, skills_t &, uint32_t &) const { + virtual bool getSkillType(const std::shared_ptr&, const std::shared_ptr&, skills_t &, uint32_t &) const { return false; } @@ -284,7 +284,7 @@ class WeaponMelee final : public Weapon { void configureWeapon(const ItemType &it) override; - bool useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const override; + bool useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const override; int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const override; @@ -294,7 +294,7 @@ class WeaponMelee final : public Weapon { virtual int16_t getElementDamageValue() const override; private: - bool getSkillType(const std::shared_ptr &player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; + bool getSkillType(const std::shared_ptr &player, const std::shared_ptr &item, skills_t &skill, uint32_t &skillpoint) const override; uint16_t elementDamage = 0; CombatType_t elementType = COMBAT_NONE; }; @@ -312,7 +312,7 @@ class WeaponDistance final : public Weapon { return true; } - bool useWeapon(const std::shared_ptr &player, std::shared_ptr item, std::shared_ptr target) const override; + bool useWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &target) const override; int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; int32_t getElementDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item) const override; @@ -322,7 +322,7 @@ class WeaponDistance final : public Weapon { virtual int16_t getElementDamageValue() const override; private: - bool getSkillType(const std::shared_ptr &player, std::shared_ptr item, skills_t &skill, uint32_t &skillpoint) const override; + bool getSkillType(const std::shared_ptr &player, const std::shared_ptr &item, skills_t &skill, uint32_t &skillpoint) const override; CombatType_t elementType = COMBAT_NONE; uint16_t elementDamage = 0; @@ -339,7 +339,7 @@ class WeaponWand final : public Weapon { void configureWeapon(const ItemType &it) override; int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; - int32_t getElementDamage(std::shared_ptr, std::shared_ptr, std::shared_ptr) const override { + int32_t getElementDamage(const std::shared_ptr&, std::shared_ptr, std::shared_ptr) const override { return 0; } CombatType_t getElementType() const override { @@ -355,7 +355,7 @@ class WeaponWand final : public Weapon { } private: - bool getSkillType(std::shared_ptr, std::shared_ptr, skills_t &, uint32_t &) const override { + bool getSkillType(const std::shared_ptr&, const std::shared_ptr&, skills_t &, uint32_t &) const override { return false; } diff --git a/src/lua/callbacks/creaturecallback.cpp b/src/lua/callbacks/creaturecallback.cpp index c2df33499ad..8461393e45d 100644 --- a/src/lua/callbacks/creaturecallback.cpp +++ b/src/lua/callbacks/creaturecallback.cpp @@ -39,7 +39,7 @@ void CreatureCallback::pushSpecificCreature(const std::shared_ptr &cre LuaScriptInterface::pushUserdata(L, npc); } else if (std::shared_ptr monster = creature->getMonster()) { LuaScriptInterface::pushUserdata(L, monster); - } else if (const auto player = creature->getPlayer()) { + } else if (const auto &player = creature->getPlayer()) { LuaScriptInterface::pushUserdata(L, player); } else { return; diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index 9e6795685ff..f619e4cbe78 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -236,7 +236,7 @@ std::shared_ptr Actions::getAction(const std::shared_ptr &item) { iteratePositions != actionPositionMap.end()) { if (std::shared_ptr tile = item->getTile(); tile) { - if (const auto player = item->getHoldingPlayer(); + if (const auto &player = item->getHoldingPlayer(); player && item->getTopParent() == player) { g_logger().debug("[Actions::getAction] - The position only is valid for use item in the map, player name {}", player->getName()); return nullptr; diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index d195cfa301b..17d2a73384f 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -116,7 +116,7 @@ class Events { void eventPlayerOnRequestQuestLine(const std::shared_ptr &player, uint16_t questId); void eventOnStorageUpdate(const std::shared_ptr &player, uint32_t key, int32_t value, int32_t oldValue, uint64_t currentTime); void eventPlayerOnCombat(const std::shared_ptr &player, const std::shared_ptr &target, const std::shared_ptr &item, CombatDamage &damage); - void eventPlayerOnInventoryUpdate(const const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip); + void eventPlayerOnInventoryUpdate(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip); // Monster void eventMonsterOnDropLoot(std::shared_ptr monster, const std::shared_ptr &corpse); diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index 653a4bf568a..f317a7a6deb 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -688,7 +688,7 @@ bool MoveEvent::executeStep(const std::shared_ptr &creature, const std // Check if the new position is the same as the old one // If it is, log a warning and either teleport the player to their temple position if item type is an teleport auto fromPosition = creature->getLastPosition(); - if (auto player = creature->getPlayer(); item && fromPosition == pos && getEventType() == MOVE_EVENT_STEP_IN) { + if (const auto &player = creature->getPlayer(); item && fromPosition == pos && getEventType() == MOVE_EVENT_STEP_IN) { if (const ItemType &itemType = Item::items[item->getID()]; player && itemType.isTeleport()) { g_logger().warn("[{}] cannot teleport player: {}, to the same position: {} of fromPosition: {}", __FUNCTION__, player->getName(), pos.toString(), fromPosition.toString()); g_game().internalTeleport(player, player->getTemplePosition()); diff --git a/src/lua/functions/core/game/bank_functions.cpp b/src/lua/functions/core/game/bank_functions.cpp index 401ba9dab7c..49aa78e0dcf 100644 --- a/src/lua/functions/core/game/bank_functions.cpp +++ b/src/lua/functions/core/game/bank_functions.cpp @@ -154,7 +154,7 @@ std::shared_ptr BankFunctions::getBank(lua_State* L, int32_t arg, bool isG } return std::make_shared(guild); } - const auto player = getPlayer(L, arg, true); + const auto &player = getPlayer(L, arg, true); if (!player) { return nullptr; } diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index 941ead55c3a..036acc00cd9 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -652,7 +652,7 @@ int GameFunctions::luaGameGetNormalizedPlayerName(lua_State* L) { // Game.getNormalizedPlayerName(name[, isNewName = false]) auto name = getString(L, 1); auto isNewName = getBoolean(L, 2, false); - const auto player = g_game().getPlayerByName(name, true, isNewName); + const auto &player = g_game().getPlayerByName(name, true, isNewName); if (player) { pushString(L, player->getName()); } else { diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 492526022d6..4a7335eada9 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -25,7 +25,7 @@ class Creature; int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { // doPlayerAddItem(cid, itemid, count/subtype, canDropOnMap) // doPlayerAddItem(cid, itemid, count, canDropOnMap, subtype) - const auto player = getPlayer(L, 1); + const auto &player = getPlayer(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -286,7 +286,7 @@ int GlobalFunctions::luaDoAreaCombatHealth(lua_State* L) { damage.instantSpellName = getString(L, 9); damage.runeSpellName = getString(L, 10); if (creature) { - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->wheel()->getCombatDataSpell(damage); } } @@ -330,7 +330,7 @@ int GlobalFunctions::luaDoTargetCombatHealth(lua_State* L) { damage.instantSpellName = getString(L, 9); damage.runeSpellName = getString(L, 10); if (creature) { - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->wheel()->getCombatDataSpell(damage); } } @@ -368,7 +368,7 @@ int GlobalFunctions::luaDoAreaCombatMana(lua_State* L) { damage.instantSpellName = getString(L, 8); damage.runeSpellName = getString(L, 9); if (creature) { - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->wheel()->getCombatDataSpell(damage); } } @@ -413,7 +413,7 @@ int GlobalFunctions::luaDoTargetCombatMana(lua_State* L) { damage.instantSpellName = getString(L, 7); damage.runeSpellName = getString(L, 8); if (creature) { - if (auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { player->wheel()->getCombatDataSpell(damage); } } diff --git a/src/lua/functions/core/network/network_message_functions.cpp b/src/lua/functions/core/network/network_message_functions.cpp index faaf752c267..017d7e74100 100644 --- a/src/lua/functions/core/network/network_message_functions.cpp +++ b/src/lua/functions/core/network/network_message_functions.cpp @@ -239,7 +239,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddItem(lua_State* L) { return 1; } - const auto player = getUserdataShared(L, 3); + const auto &player = getUserdataShared(L, 3); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); lua_pushnil(L); @@ -289,7 +289,7 @@ int NetworkMessageFunctions::luaNetworkMessageSendToPlayer(lua_State* L) { return 1; } - const auto player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index ddca806acb2..85f5897c8ca 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -485,7 +485,7 @@ int CreatureFunctions::luaCreatureSetHealth(lua_State* L) { creature->health = std::min(getNumber(L, 2), creature->healthMax); g_game().addCreatureHealth(creature); - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendStats(); } @@ -537,7 +537,7 @@ int CreatureFunctions::luaCreatureSetMaxHealth(lua_State* L) { creature->health = std::min(creature->health, creature->healthMax); g_game().addCreatureHealth(creature); - const auto player = creature->getPlayer(); + const auto &player = creature->getPlayer(); if (player) { player->sendStats(); } @@ -764,7 +764,7 @@ int CreatureFunctions::luaCreatureRemove(lua_State* L) { } bool forced = getBoolean(L, 2, true); - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (forced) { player->removePlayer(true); } else { diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index f67dd2d88a8..deb4e689576 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -1719,7 +1719,7 @@ int PlayerFunctions::luaPlayerSetBankBalance(lua_State* L) { int PlayerFunctions::luaPlayerGetStorageValue(lua_State* L) { // player:getStorageValue(key) - const auto player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; @@ -3734,7 +3734,7 @@ int PlayerFunctions::luaPlayerSendDoubleSoundEffect(lua_State* L) { int PlayerFunctions::luaPlayerGetName(lua_State* L) { // player:getName() - const auto player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3747,7 +3747,7 @@ int PlayerFunctions::luaPlayerGetName(lua_State* L) { int PlayerFunctions::luaPlayerChangeName(lua_State* L) { // player:changeName(newName) - const auto player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -3819,7 +3819,7 @@ int PlayerFunctions::luaPlayerAddHazardSystemPoints(lua_State* L) { int PlayerFunctions::luaPlayerGetHazardSystemPoints(lua_State* L) { // player:getHazardSystemPoints() - const auto player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { pushBoolean(L, false); reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); @@ -3857,7 +3857,7 @@ int PlayerFunctions::luaPlayerGetLoyaltyBonus(lua_State* L) { int PlayerFunctions::luaPlayerGetLoyaltyPoints(lua_State* L) { // player:getLoyaltyPoints() - const auto player = getUserdataShared(L, 1); + const auto &player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); return 1; diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index 9e7287309a6..aca6f9a656a 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -242,7 +242,7 @@ void House::setAccessList(uint32_t listId, const std::string &textlist) { for (const std::shared_ptr &tile : houseTiles) { if (CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { - const auto player = (*creatures)[i]->getPlayer(); + const auto &player = (*creatures)[i]->getPlayer(); if (player && !isInvited(player)) { kickPlayer(nullptr, player); } @@ -256,7 +256,7 @@ bool House::transferToDepot() const { return false; } - const auto player = g_game().getPlayerByGUID(owner); + const auto &player = g_game().getPlayerByGUID(owner); if (player) { transferToDepot(player); } else { @@ -587,7 +587,7 @@ void AccessList::parseList(const std::string &list) { } void AccessList::addPlayer(const std::string &name) { - const auto player = g_game().getPlayerByName(name); + const auto &player = g_game().getPlayerByName(name); if (player) { playerList.insert(player->getGUID()); } else { diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 572d04128a4..7d580acec27 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -64,7 +64,7 @@ void HouseTile::updateHouse(const std::shared_ptr &item) { ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr actor /* = nullptr*/) { if (std::shared_ptr creature = thing->getCreature()) { - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } @@ -91,7 +91,7 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr &thi std::shared_ptr HouseTile::queryDestination(int32_t &index, const std::shared_ptr &thing, std::shared_ptr* destItem, uint32_t &tileFlags) { if (std::shared_ptr creature = thing->getCreature()) { - if (const auto player = creature->getPlayer()) { + if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { const Position &entryPos = house->getEntryPosition(); std::shared_ptr destTile = g_game().map.getTile(entryPos); diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 0108513d137..5d0456546f1 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -43,6 +43,7 @@ #include "enums/player_blessings.hpp" #include "creatures/players/highscore_category.hpp" +#include "utils/counter_pointer.hpp" /* * NOTE: This namespace is used so that we can add functions without having to declare them in the ".hpp/.hpp" file @@ -488,6 +489,7 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS if (!foundPlayer) { player = std::make_shared(getThis()); player->setName(name); + g_beats().store(name, player); g_game().addPlayerUniqueLogin(player); player->setID(); diff --git a/src/utils/counter_pointer.hpp b/src/utils/counter_pointer.hpp new file mode 100644 index 00000000000..fea4640f4ca --- /dev/null +++ b/src/utils/counter_pointer.hpp @@ -0,0 +1,47 @@ +#pragma once + +#include +#include +#include +#include +#include "lib/di/container.hpp" + +class SharedPtrManager { +public: + SharedPtrManager() = default; + ~SharedPtrManager() = default; + + // Singleton - ensures we don't accidentally copy it. + SharedPtrManager(const SharedPtrManager &) = delete; + SharedPtrManager &operator=(const SharedPtrManager &) = delete; + + static SharedPtrManager &getInstance() { + return inject(); + } + + // Função para armazenar o shared_ptr + template + void store(const std::string &name, const std::shared_ptr &ptr) { + sharedPtrMap[name] = ptr; + } + + // Função para contar as referências de todos os shared_ptr armazenados e limpar os destruídos + void countAllReferencesAndClean() { + for (auto it = sharedPtrMap.begin(); it != sharedPtrMap.end();) { + const auto &sptr = it->second.lock(); + if (sptr) { + std::cout << "Contagem de referências do shared_ptr (" << it->first << "): " + << sptr.use_count() << std::endl; + ++it; + } else { + std::cout << "Objeto " << it->first << " foi destruído e será removido do mapa." << std::endl; + it = sharedPtrMap.erase(it); // Remove o item do mapa e avança o iterador + } + } + } + +private: + std::unordered_map> sharedPtrMap; +}; + +constexpr auto g_beats = SharedPtrManager::getInstance; From b0b828d0b2c6d62e16849d7904021560aaadbda4 Mon Sep 17 00:00:00 2001 From: beats-dh Date: Wed, 28 Aug 2024 23:15:06 -0300 Subject: [PATCH 15/34] Update events.cpp --- src/lua/creature/events.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 7210ce7e850..e07121a9ec5 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -1247,7 +1247,7 @@ void Events::eventPlayerOnRequestQuestLine(const std::shared_ptr &player scriptInterface.callVoidFunction(2); } -void Events::eventPlayerOnInventoryUpdate(const const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip) { +void Events::eventPlayerOnInventoryUpdate(const std::shared_ptr &player, const std::shared_ptr &item, Slots_t slot, bool equip) { // Player:onInventoryUpdate(item, slot, equip) if (info.playerOnInventoryUpdate == -1) { return; From 7ef016882641eee6430db9a70f22182504ba287b Mon Sep 17 00:00:00 2001 From: beats-dh Date: Thu, 29 Aug 2024 21:28:53 -0300 Subject: [PATCH 16/34] remove opemtelemetry lib metrics off --- CMakeLists.txt | 28 ++++++++++++++++------------ vcpkg.json | 17 ++++++++++++----- 2 files changed, 28 insertions(+), 17 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index d5853366d80..4406b8fbb94 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -23,17 +23,6 @@ set(VCPKG_BUILD_TYPE "release") set(CMAKE_EXPORT_COMPILE_COMMANDS ON) - -# ***************************************************************************** -# Project canary -# ***************************************************************************** -if(CMAKE_BUILD_TYPE STREQUAL "Debug") - project(canary-debug) -else() - project(canary) -endif() - - # ***************************************************************************** # Append cmake search path # ***************************************************************************** @@ -51,7 +40,22 @@ include(LoggingHelper) option(OPTIONS_ENABLE_CCACHE "Enable ccache" OFF) option(OPTIONS_ENABLE_SCCACHE "Use sccache to speed up compilation process" OFF) option(OPTIONS_ENABLE_IPO "Check and Enable interprocedural optimization (IPO/LTO)" ON) -option(FEATURE_METRICS "Enable metrics feature" OFF) +option(FEATURE_METRICS "Enable metrics feature" ON) + + +if(FEATURE_METRICS) + list(APPEND VCPKG_MANIFEST_FEATURES "metrics") +endif() + + +# ***************************************************************************** +# Project canary +# ***************************************************************************** +if(CMAKE_BUILD_TYPE STREQUAL "Debug") + project(canary-debug) +else() + project(canary) +endif() # ***************************************************************************** # Options Code diff --git a/vcpkg.json b/vcpkg.json index eed7e776ee0..5e0623857a4 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -18,11 +18,6 @@ "spdlog", "zlib", "bshoshany-thread-pool", - { - "name": "opentelemetry-cpp", - "default-features": true, - "features": ["otlp-http", "prometheus"] - }, { "name": "libmariadb", "features": [ @@ -38,5 +33,17 @@ "platform": "windows" } ], + "features": { + "metrics": { + "description": "Enable OpenTelemetry support", + "dependencies": [ + { + "name": "opentelemetry-cpp", + "default-features": true, + "features": ["otlp-http", "prometheus"] + } + ] + } + }, "builtin-baseline": "095ee06e7f60dceef7d713e3f8b1c2eb10d650d7" } From d5bdb0e4157826375d7fad48cf684fa1ea150543 Mon Sep 17 00:00:00 2001 From: GitHub Actions Date: Sat, 31 Aug 2024 01:01:17 +0000 Subject: [PATCH 17/34] Code format - (Clang-format) --- src/items/weapons/weapons.cpp | 2 +- src/items/weapons/weapons.hpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 9cf7128648b..268ff42c968 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -850,7 +850,7 @@ int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr &player, s return -normal_random(minValue, (maxValue * static_cast(player->getVocation()->distDamageMultiplier))); } -bool WeaponDistance::getSkillType(const std::shared_ptr &player, const std::shared_ptr&, skills_t &skill, uint32_t &skillpoint) const { +bool WeaponDistance::getSkillType(const std::shared_ptr &player, const std::shared_ptr &, skills_t &skill, uint32_t &skillpoint) const { skill = SKILL_DISTANCE; if (player->getAddAttackSkill()) { diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index b3822f05dd6..5eee699cacb 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -228,7 +228,7 @@ class Weapon : public Script { void internalUseWeapon(const std::shared_ptr &player, const std::shared_ptr &item, const std::shared_ptr &tile) const; private: - virtual bool getSkillType(const std::shared_ptr&, const std::shared_ptr&, skills_t &, uint32_t &) const { + virtual bool getSkillType(const std::shared_ptr &, const std::shared_ptr &, skills_t &, uint32_t &) const { return false; } @@ -339,7 +339,7 @@ class WeaponWand final : public Weapon { void configureWeapon(const ItemType &it) override; int32_t getWeaponDamage(const std::shared_ptr &player, std::shared_ptr target, std::shared_ptr item, bool maxDamage = false) const override; - int32_t getElementDamage(const std::shared_ptr&, std::shared_ptr, std::shared_ptr) const override { + int32_t getElementDamage(const std::shared_ptr &, std::shared_ptr, std::shared_ptr) const override { return 0; } CombatType_t getElementType() const override { @@ -355,7 +355,7 @@ class WeaponWand final : public Weapon { } private: - bool getSkillType(const std::shared_ptr&, const std::shared_ptr&, skills_t &, uint32_t &) const override { + bool getSkillType(const std::shared_ptr &, const std::shared_ptr &, skills_t &, uint32_t &) const override { return false; } From 9f8948c977e3303369ccc8859b6b403a1c5cf17f Mon Sep 17 00:00:00 2001 From: beats-dh Date: Sat, 31 Aug 2024 01:15:45 -0300 Subject: [PATCH 18/34] Update qodana.yml --- qodana.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/qodana.yml b/qodana.yml index 1621c979a9d..1697dd7e432 100644 --- a/qodana.yml +++ b/qodana.yml @@ -1,5 +1,7 @@ version: "1.0" +linter: jetbrains/qodana-clang:latest + profile: name: qodana.recommended From aa4e39539afa5e4dd44e5ec42f0687992b7e6bbe Mon Sep 17 00:00:00 2001 From: Beats Date: Sun, 1 Sep 2024 17:09:29 -0400 Subject: [PATCH 19/34] update --- src/account/account.cpp | 18 +- src/account/account.hpp | 2 +- src/account/account_repository.cpp | 3 - src/account/account_repository_db.cpp | 25 +- src/account/account_repository_db.hpp | 2 +- src/canary_server.cpp | 6 +- src/canary_server.hpp | 8 +- src/config/configmanager.cpp | 2 +- src/config/configmanager.hpp | 2 +- src/creatures/appearance/mounts/mounts.cpp | 14 +- src/creatures/appearance/mounts/mounts.hpp | 2 +- src/creatures/appearance/outfit/outfit.cpp | 16 +- src/creatures/appearance/outfit/outfit.hpp | 11 +- src/creatures/combat/combat.cpp | 133 +-- src/creatures/combat/combat.hpp | 18 +- src/creatures/creature.cpp | 22 +- src/creatures/creature.hpp | 26 +- src/creatures/npcs/npcs.cpp | 2 +- src/creatures/players/player.cpp | 983 +++++++++---------- src/creatures/players/player.hpp | 235 +++-- src/creatures/players/storages/storages.cpp | 1 + src/creatures/players/vip/player_vip.hpp | 6 +- src/game/movement/teleport.cpp | 10 +- src/game/movement/teleport.hpp | 10 +- src/items/containers/container.cpp | 20 +- src/items/containers/container.hpp | 16 +- src/items/containers/depot/depotchest.cpp | 4 +- src/items/containers/depot/depotchest.hpp | 4 +- src/items/containers/depot/depotlocker.cpp | 4 +- src/items/containers/depot/depotlocker.hpp | 4 +- src/items/containers/inbox/inbox.cpp | 4 +- src/items/containers/inbox/inbox.hpp | 4 +- src/items/containers/mailbox/mailbox.cpp | 10 +- src/items/containers/mailbox/mailbox.hpp | 10 +- src/items/containers/rewards/reward.cpp | 4 +- src/items/containers/rewards/reward.hpp | 4 +- src/items/containers/rewards/rewardchest.cpp | 4 +- src/items/containers/rewards/rewardchest.hpp | 4 +- src/items/cylinder.cpp | 6 +- src/items/cylinder.hpp | 26 +- src/items/items.hpp | 1 + src/items/tile.cpp | 16 +- src/items/tile.hpp | 20 +- src/items/trashholder.cpp | 10 +- src/items/trashholder.hpp | 10 +- src/map/house/housetile.cpp | 2 +- src/map/house/housetile.hpp | 2 +- 47 files changed, 867 insertions(+), 879 deletions(-) diff --git a/src/account/account.cpp b/src/account/account.cpp index aa2ab0b070c..8b5cc2ff71a 100644 --- a/src/account/account.cpp +++ b/src/account/account.cpp @@ -64,7 +64,7 @@ uint8_t Account::reload() { return load(); } -uint8_t Account::save() { +uint8_t Account::save() const { if (!m_accLoaded) { return enumToValue(AccountErrors_t::NotInitialized); } @@ -183,8 +183,8 @@ std::string Account::getPassword() { } void Account::addPremiumDays(const int32_t &days) { - auto timeLeft = std::max(0, static_cast((m_account.premiumLastDay - getTimeNow()) % 86400)); - setPremiumDays(m_account.premiumRemainingDays + days); + const auto timeLeft = std::max(0, static_cast((m_account.premiumLastDay - getTimeNow()) % 86400)); + setPremiumDays(static_cast(m_account.premiumRemainingDays) + days); m_account.premiumDaysPurchased += days; if (timeLeft > 0) { @@ -220,13 +220,13 @@ uint8_t Account::setAccountType(const uint8_t &accountType) { } void Account::updatePremiumTime() { - time_t lastDay = m_account.premiumLastDay; - uint32_t remainingDays = m_account.premiumRemainingDays; + const time_t lastDay = m_account.premiumLastDay; + const uint32_t remainingDays = m_account.premiumRemainingDays; - time_t currentTime = getTimeNow(); + const time_t currentTime = getTimeNow(); - auto daysLeft = static_cast((lastDay - currentTime) / 86400); - auto timeLeft = static_cast((lastDay - currentTime) % 86400); + const auto daysLeft = static_cast((lastDay - currentTime) / 86400); + const auto timeLeft = static_cast((lastDay - currentTime) % 86400); m_account.premiumRemainingDays = daysLeft > 0 ? daysLeft : 0; @@ -278,7 +278,7 @@ bool Account::authenticateSession() { } bool Account::authenticatePassword(const std::string &password) { - if (Argon2 {}.argon(password, getPassword())) { + if (Argon2().argon(password, getPassword())) { return true; } diff --git a/src/account/account.hpp b/src/account/account.hpp index d968ba8ddfb..411cb2901cb 100644 --- a/src/account/account.hpp +++ b/src/account/account.hpp @@ -62,7 +62,7 @@ class Account { * * @return AccountErrors_t AccountErrors_t::Ok(0) Success, otherwise Fail. */ - uint8_t save(); + uint8_t save() const; /** * @brief Load Account Information. diff --git a/src/account/account_repository.cpp b/src/account/account_repository.cpp index babca847043..c7f4499e968 100644 --- a/src/account/account_repository.cpp +++ b/src/account/account_repository.cpp @@ -7,10 +7,7 @@ * Website: https://docs.opentibiabr.com/ */ -#include "pch.hpp" - #include "account/account_repository.hpp" - #include "lib/di/container.hpp" AccountRepository &AccountRepository::getInstance() { diff --git a/src/account/account_repository_db.cpp b/src/account/account_repository_db.cpp index 2d691020a95..678584208ad 100644 --- a/src/account/account_repository_db.cpp +++ b/src/account/account_repository_db.cpp @@ -15,7 +15,6 @@ #include "lib/logging/logger.hpp" #include "utils/definitions.hpp" #include "utils/tools.hpp" -#include "enums/account_type.hpp" #include "enums/account_coins.hpp" #include "account/account_info.hpp" @@ -23,18 +22,18 @@ AccountRepositoryDB::AccountRepositoryDB() : coinTypeToColumn({ { enumToValue(CoinType::Normal), "coins" }, { enumToValue(CoinType::Tournament), "tournament_coins" }, { enumToValue(CoinType::Transferable), "coins_transferable" } }) { } bool AccountRepositoryDB::loadByID(const uint32_t &id, AccountInfo &acc) { - auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `id` = {}", id); + const auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `id` = {}", id); return load(query, acc); } bool AccountRepositoryDB::loadByEmailOrName(bool oldProtocol, const std::string &emailOrName, AccountInfo &acc) { auto identifier = oldProtocol ? "name" : "email"; - auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `{}` = {}", identifier, g_database().escapeString(emailOrName)); + const auto query = fmt::format("SELECT `id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, 0 AS `expires` FROM `accounts` WHERE `{}` = {}", identifier, g_database().escapeString(emailOrName)); return load(query, acc); } bool AccountRepositoryDB::loadBySession(const std::string &sessionKey, AccountInfo &acc) { - auto query = fmt::format( + const auto query = fmt::format( "SELECT `accounts`.`id`, `type`, `premdays`, `lastday`, `creation`, `premdays_purchased`, `account_sessions`.`expires` " "FROM `accounts` " "INNER JOIN `account_sessions` ON `account_sessions`.`account_id` = `accounts`.`id` " @@ -45,7 +44,7 @@ bool AccountRepositoryDB::loadBySession(const std::string &sessionKey, AccountIn } bool AccountRepositoryDB::save(const AccountInfo &accInfo) { - bool successful = g_database().executeQuery( + const bool successful = g_database().executeQuery( fmt::format( "UPDATE `accounts` SET `type` = {}, `premdays` = {}, `lastday` = {}, `creation` = {}, `premdays_purchased` = {} WHERE `id` = {}", accInfo.accountType, @@ -65,7 +64,7 @@ bool AccountRepositoryDB::save(const AccountInfo &accInfo) { } bool AccountRepositoryDB::getPassword(const uint32_t &id, std::string &password) { - auto result = g_database().storeQuery(fmt::format("SELECT * FROM `accounts` WHERE `id` = {}", id)); + const auto result = g_database().storeQuery(fmt::format("SELECT * FROM `accounts` WHERE `id` = {}", id)); if (!result) { g_logger().error("Failed to get account:[{}] password!", id); return false; @@ -76,12 +75,12 @@ bool AccountRepositoryDB::getPassword(const uint32_t &id, std::string &password) } bool AccountRepositoryDB::getCoins(const uint32_t &id, const uint8_t &type, uint32_t &coins) { - if (coinTypeToColumn.find(type) == coinTypeToColumn.end()) { + if (!coinTypeToColumn.contains(type)) { g_logger().error("[{}]: invalid coin type:[{}]", __FUNCTION__, type); return false; } - auto result = g_database().storeQuery(fmt::format( + const auto result = g_database().storeQuery(fmt::format( "SELECT `{}` FROM `accounts` WHERE `id` = {}", coinTypeToColumn.at(type), id @@ -97,12 +96,12 @@ bool AccountRepositoryDB::getCoins(const uint32_t &id, const uint8_t &type, uint } bool AccountRepositoryDB::setCoins(const uint32_t &id, const uint8_t &type, const uint32_t &amount) { - if (coinTypeToColumn.find(type) == coinTypeToColumn.end()) { + if (!coinTypeToColumn.contains(type)) { g_logger().error("[{}]: invalid coin type:[{}]", __FUNCTION__, type); return false; } - bool successful = g_database().executeQuery(fmt::format( + const bool successful = g_database().executeQuery(fmt::format( "UPDATE `accounts` SET `{}` = {} WHERE `id` = {}", coinTypeToColumn.at(type), amount, @@ -148,8 +147,8 @@ bool AccountRepositoryDB::registerCoinsTransaction( return successful; } -bool AccountRepositoryDB::loadAccountPlayers(AccountInfo &acc) { - auto result = g_database().storeQuery( +bool AccountRepositoryDB::loadAccountPlayers(AccountInfo &acc) const { + const auto result = g_database().storeQuery( fmt::format("SELECT `name`, `deletion` FROM `players` WHERE `account_id` = {} ORDER BY `name` ASC", acc.id) ); @@ -170,7 +169,7 @@ bool AccountRepositoryDB::loadAccountPlayers(AccountInfo &acc) { } bool AccountRepositoryDB::load(const std::string &query, AccountInfo &acc) { - auto result = g_database().storeQuery(query); + const auto result = g_database().storeQuery(query); if (result == nullptr) { return false; diff --git a/src/account/account_repository_db.hpp b/src/account/account_repository_db.hpp index 651600e3bc4..e79440d92eb 100644 --- a/src/account/account_repository_db.hpp +++ b/src/account/account_repository_db.hpp @@ -35,6 +35,6 @@ class AccountRepositoryDB final : public AccountRepository { private: const std::map coinTypeToColumn; bool load(const std::string &query, AccountInfo &acc); - bool loadAccountPlayers(AccountInfo &acc); + bool loadAccountPlayers(AccountInfo &acc) const; void setupLoyaltyInfo(AccountInfo &acc); }; diff --git a/src/canary_server.cpp b/src/canary_server.cpp index cca280b69fa..1460a450f67 100644 --- a/src/canary_server.cpp +++ b/src/canary_server.cpp @@ -195,7 +195,7 @@ void CanaryServer::setupHousesRent() { g_game().map.houses.payHouses(rentPeriod); } -void CanaryServer::logInfos() { +void CanaryServer::logInfos() const { #if defined(GIT_RETRIEVED_STATE) && GIT_RETRIEVED_STATE logger.debug("{} - Version [{}] dated [{}]", ProtocolStatus::SERVER_NAME, SERVER_RELEASE_VERSION, GIT_COMMIT_DATE_ISO8601); #if GIT_IS_DIRTY @@ -300,7 +300,7 @@ void CanaryServer::loadConfigLua() { #endif } -void CanaryServer::initializeDatabase() { +void CanaryServer::initializeDatabase() const { logger.info("Establishing database connection... "); if (!Database::getInstance().connect()) { throw FailedToInitializeCanary("Failed to connect to database!"); @@ -380,7 +380,7 @@ void CanaryServer::loadModules() { g_game().logCyclopediaStats(); } -void CanaryServer::modulesLoadHelper(bool loaded, std::string moduleName) { +void CanaryServer::modulesLoadHelper(bool loaded, std::string moduleName) const { logger.debug("Loading {}", moduleName); if (!loaded) { throw FailedToInitializeCanary(fmt::format("Cannot load: {}", moduleName)); diff --git a/src/canary_server.hpp b/src/canary_server.hpp index 57c931cd133..dbcd7cb2212 100644 --- a/src/canary_server.hpp +++ b/src/canary_server.hpp @@ -14,7 +14,7 @@ class Logger; -class FailedToInitializeCanary : public std::exception { +class FailedToInitializeCanary final : public std::exception { private: std::string message; @@ -52,7 +52,7 @@ class CanaryServer { std::atomic loaderStatus = LoaderStatus::LOADING; - void logInfos(); + void logInfos() const; static void toggleForceCloseButton(); static void badAllocationHandler(); static void shutdown(); @@ -61,10 +61,10 @@ class CanaryServer { static std::string getPlatform(); void loadConfigLua(); - void initializeDatabase(); + void initializeDatabase() const; void loadModules(); void setWorldType(); void loadMaps() const; void setupHousesRent(); - void modulesLoadHelper(bool loaded, std::string moduleName); + void modulesLoadHelper(bool loaded, std::string moduleName) const; }; diff --git a/src/config/configmanager.cpp b/src/config/configmanager.cpp index 6390d0699b3..7288f5b844b 100644 --- a/src/config/configmanager.cpp +++ b/src/config/configmanager.cpp @@ -378,7 +378,7 @@ bool ConfigManager::reload() { return result; } -void ConfigManager::missingConfigWarning(const char* identifier) { +void ConfigManager::missingConfigWarning(const char* identifier) const { g_logger().warn("[{}]: Missing configuration for identifier: {}", __FUNCTION__, identifier); } diff --git a/src/config/configmanager.hpp b/src/config/configmanager.hpp index 2a0c0861955..3bec936170f 100644 --- a/src/config/configmanager.hpp +++ b/src/config/configmanager.hpp @@ -26,7 +26,7 @@ class ConfigManager { bool load(); bool reload(); - void missingConfigWarning(const char* identifier); + void missingConfigWarning(const char* identifier) const; const std::string &setConfigFileLua(const std::string &what) { configFileLua = { what }; diff --git a/src/creatures/appearance/mounts/mounts.cpp b/src/creatures/appearance/mounts/mounts.cpp index 7014d0b026b..ebfe8758aa7 100644 --- a/src/creatures/appearance/mounts/mounts.cpp +++ b/src/creatures/appearance/mounts/mounts.cpp @@ -21,15 +21,15 @@ bool Mounts::reload() { bool Mounts::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/mounts.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/mounts.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; } - for (auto mountNode : doc.child("mounts").children()) { - auto lookType = pugi::cast(mountNode.attribute("clientid").value()); + for (const auto &mountNode : doc.child("mounts").children()) { + const auto lookType = pugi::cast(mountNode.attribute("clientid").value()); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { g_logger().warn("{} - An unregistered creature mount with id '{}' was blocked to prevent client crash.", __FUNCTION__, lookType); continue; @@ -48,7 +48,7 @@ bool Mounts::loadFromXml() { } std::shared_ptr Mounts::getMountByID(uint8_t id) { - auto it = std::find_if(mounts.begin(), mounts.end(), [id](const std::shared_ptr &mount) { + const auto it = std::ranges::find_if(mounts, [id](const auto &mount) { return mount->id == id; // Note the use of -> operator to access the members of the Mount object }); @@ -57,7 +57,7 @@ std::shared_ptr Mounts::getMountByID(uint8_t id) { std::shared_ptr Mounts::getMountByName(const std::string &name) { auto mountName = name.c_str(); - auto it = std::find_if(mounts.begin(), mounts.end(), [mountName](const std::shared_ptr &mount) { + const auto it = std::ranges::find_if(mounts, [mountName](const auto &mount) { return strcasecmp(mountName, mount->name.c_str()) == 0; }); @@ -65,7 +65,7 @@ std::shared_ptr Mounts::getMountByName(const std::string &name) { } std::shared_ptr Mounts::getMountByClientID(uint16_t clientId) { - auto it = std::find_if(mounts.begin(), mounts.end(), [clientId](const std::shared_ptr &mount) { + const auto it = std::ranges::find_if(mounts, [clientId](const auto &mount) { return mount->clientId == clientId; // Note the use of -> operator to access the members of the Mount object }); diff --git a/src/creatures/appearance/mounts/mounts.hpp b/src/creatures/appearance/mounts/mounts.hpp index d5e6c965bd2..78ddc95feb2 100644 --- a/src/creatures/appearance/mounts/mounts.hpp +++ b/src/creatures/appearance/mounts/mounts.hpp @@ -10,7 +10,7 @@ #pragma once struct Mount { - Mount(uint8_t initId, uint16_t initClientId, std::string initName, int32_t initSpeed, bool initPremium, std::string initType) : + Mount(const uint8_t initId, const uint16_t initClientId, std::string initName, const int32_t initSpeed, const bool initPremium, std::string initType) : name(std::move(initName)), speed(initSpeed), clientId(initClientId), id(initId), premium(initPremium), type(std::move(initType)) { } diff --git a/src/creatures/appearance/outfit/outfit.cpp b/src/creatures/appearance/outfit/outfit.cpp index 697ed776c3d..28de5a065c1 100644 --- a/src/creatures/appearance/outfit/outfit.cpp +++ b/src/creatures/appearance/outfit/outfit.cpp @@ -27,8 +27,8 @@ bool Outfits::reload() { bool Outfits::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/outfits.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/outfits.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -36,28 +36,28 @@ bool Outfits::loadFromXml() { for (const auto &outfitNode : doc.child("outfits").children()) { pugi::xml_attribute attr; - if ((attr = outfitNode.attribute("enabled")) && !attr.as_bool()) { + if (((attr = outfitNode.attribute("enabled"))) && !attr.as_bool()) { continue; } - if (!(attr = outfitNode.attribute("type"))) { + if (!((attr = outfitNode.attribute("type")))) { g_logger().warn("[Outfits::loadFromXml] - Missing outfit type"); continue; } - auto type = pugi::cast(attr.value()); + const auto type = pugi::cast(attr.value()); if (type > PLAYERSEX_LAST) { g_logger().warn("[Outfits::loadFromXml] - Invalid outfit type {}", type); continue; } - pugi::xml_attribute lookTypeAttribute = outfitNode.attribute("looktype"); + const pugi::xml_attribute lookTypeAttribute = outfitNode.attribute("looktype"); if (!lookTypeAttribute) { g_logger().warn("[Outfits::loadFromXml] - Missing looktype on outfit"); continue; } - if (auto lookType = pugi::cast(lookTypeAttribute.value()); + if (const auto lookType = pugi::cast(lookTypeAttribute.value()); g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { g_logger().warn("[Outfits::loadFromXml] An unregistered creature looktype type with id '{}' was ignored to prevent client crash.", lookType); @@ -94,7 +94,7 @@ std::shared_ptr Outfits::getOutfitByLookType(const std::shared_ptrlookType == lookType; }); diff --git a/src/creatures/appearance/outfit/outfit.hpp b/src/creatures/appearance/outfit/outfit.hpp index 0d89a2c932d..a0503045db0 100644 --- a/src/creatures/appearance/outfit/outfit.hpp +++ b/src/creatures/appearance/outfit/outfit.hpp @@ -9,13 +9,10 @@ #pragma once -#include "declarations.hpp" -#include "lib/di/container.hpp" - class Player; struct OutfitEntry { - constexpr explicit OutfitEntry(uint16_t initLookType, uint8_t initAddons) : + constexpr explicit OutfitEntry(const uint16_t initLookType, const uint8_t initAddons) : lookType(initLookType), addons(initAddons) { } uint16_t lookType; @@ -23,7 +20,7 @@ struct OutfitEntry { }; struct Outfit { - Outfit(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initFrom) : + Outfit(std::string initName, const uint16_t initLookType, const bool initPremium, const bool initUnlocked, std::string initFrom) : name(std::move(initName)), lookType(initLookType), premium(initPremium), unlocked(initUnlocked), from(std::move(initFrom)) { } std::string name; @@ -34,7 +31,7 @@ struct Outfit { }; struct ProtocolOutfit { - ProtocolOutfit(const std::string &initName, uint16_t initLookType, uint8_t initAddons) : + ProtocolOutfit(const std::string &initName, const uint16_t initLookType, const uint8_t initAddons) : name(initName), lookType(initLookType), addons(initAddons) { } const std::string &name; @@ -50,7 +47,7 @@ class Outfits { bool loadFromXml(); [[nodiscard]] std::shared_ptr getOutfitByLookType(const std::shared_ptr &player, uint16_t lookType, bool isOppositeOutfit = false) const; - [[nodiscard]] const std::vector> &getOutfits(PlayerSex_t sex) const { + [[nodiscard]] const std::vector> &getOutfits(const PlayerSex_t &sex) const { return outfits[sex]; } diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 2fba90cfa77..313a1dd8311 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -36,12 +36,12 @@ int32_t Combat::getLevelFormula(const std::shared_ptr &player, const std if (player->wheel()->getInstant("Runic Mastery") && wheelSpell && damage.instantSpellName.empty() && normal_random(0, 100) <= 25) { const auto conjuringSpell = g_spells().getInstantSpellByName(damage.runeSpellName); if (conjuringSpell && conjuringSpell != wheelSpell) { - uint32_t castResult = conjuringSpell->canCast(player) ? 20 : 10; + const uint32_t castResult = conjuringSpell->canCast(player) ? 20 : 10; magicLevelSkill += magicLevelSkill * castResult / 100; } } - int32_t levelFormula = player->getLevel() * 2 + (player->getMagicLevel() + player->getSpecializedMagicLevel(damage.primary.type, true)) * 3; + const int32_t levelFormula = player->getLevel() * 2 + (player->getMagicLevel() + player->getSpecializedMagicLevel(damage.primary.type, true)) * 3; return levelFormula; } @@ -72,14 +72,14 @@ CombatDamage Combat::getCombatDamage(const std::shared_ptr &creature, if (params.valueCallback) { params.valueCallback->getMinMaxValues(player, damage, params.useCharges); } else if (formulaType == COMBAT_FORMULA_LEVELMAGIC) { - int32_t levelFormula = getLevelFormula(player, wheelSpell, damage); + const int32_t levelFormula = getLevelFormula(player, wheelSpell, damage); damage.primary.value = normal_random( static_cast(levelFormula * mina + minb), static_cast(levelFormula * maxa + maxb) ); } else if (formulaType == COMBAT_FORMULA_SKILL) { - std::shared_ptr tool = player->getWeapon(); - const WeaponShared_ptr weapon = g_weapons().getWeapon(tool); + const auto &tool = player->getWeapon(); + const WeaponShared_ptr &weapon = g_weapons().getWeapon(tool); if (weapon) { damage.primary.value = normal_random( static_cast(minb), @@ -89,7 +89,7 @@ CombatDamage Combat::getCombatDamage(const std::shared_ptr &creature, damage.secondary.type = weapon->getElementType(); damage.secondary.value = weapon->getElementDamage(player, target, tool); if (params.useCharges) { - auto charges = tool->getAttribute(ItemAttribute_t::CHARGES); + const auto charges = tool->getAttribute(ItemAttribute_t::CHARGES); if (charges != 0) { g_game().transformItem(tool, tool->getID(), charges - 1); } @@ -243,7 +243,7 @@ ReturnValue Combat::canTargetCreature(const std::shared_ptr &player, con } } - return Combat::canDoCombat(player, target, true); + return canDoCombat(player, target, true); } ReturnValue Combat::canDoCombat(const std::shared_ptr &caster, const std::shared_ptr &tile, bool aggressive) { @@ -267,7 +267,8 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &caster, const s const Position &tilePosition = tile->getPosition(); if (casterPosition.z < tilePosition.z) { return RETURNVALUE_FIRSTGODOWNSTAIRS; - } else if (casterPosition.z > tilePosition.z) { + } + if (casterPosition.z > tilePosition.z) { return RETURNVALUE_FIRSTGOUPSTAIRS; } @@ -310,14 +311,14 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const return RETURNVALUE_NOERROR; } - auto targetPlayer = target ? target->getPlayer() : nullptr; + const auto targetPlayer = target ? target->getPlayer() : nullptr; if (target) { - std::shared_ptr tile = target->getTile(); + const std::shared_ptr &tile = target->getTile(); if (tile->hasProperty(CONST_PROP_BLOCKPROJECTILE)) { return RETURNVALUE_NOTENOUGHROOM; } if (tile->hasFlag(TILESTATE_PROTECTIONZONE)) { - auto permittedOnPz = targetPlayer ? targetPlayer->hasPermittedConditionInPZ() : false; + const auto permittedOnPz = targetPlayer ? targetPlayer->hasPermittedConditionInPZ() : false; return permittedOnPz ? RETURNVALUE_NOERROR : RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE; } } @@ -341,10 +342,11 @@ ReturnValue Combat::canDoCombat(const std::shared_ptr &attacker, const } // nopvp-zone - auto attackerTile = attackerPlayer->getTile(); + const auto attackerTile = attackerPlayer->getTile(); if (targetPlayerTile && targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; - } else if (attackerTile && attackerTile->hasFlag(TILESTATE_NOPVPZONE) && targetPlayerTile && !targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE | TILESTATE_PROTECTIONZONE)) { + } + if (attackerTile && attackerTile->hasFlag(TILESTATE_NOPVPZONE) && targetPlayerTile && !targetPlayerTile->hasFlag(TILESTATE_NOPVPZONE | TILESTATE_PROTECTIONZONE)) { return RETURNVALUE_ACTIONNOTPERMITTEDINANOPVPZONE; } @@ -501,7 +503,7 @@ bool Combat::setParam(CombatParam_t param, uint32_t value) { return false; } -bool Combat::setCallback(CallBackParam_t key) { +bool Combat::setCallback(const CallBackParam_t &key) { switch (key) { case CALLBACK_PARAM_LEVELMAGICVALUE: { params.valueCallback = std::make_unique(COMBAT_FORMULA_LEVELMAGIC); @@ -668,7 +670,7 @@ CombatDamage Combat::applyImbuementElementalDamage(const std::shared_ptr break; } - float damagePercent = imbuementInfo.imbuement->elementDamage / 100.0; + const float damagePercent = imbuementInfo.imbuement->elementDamage / 100.0; damage.secondary.type = imbuementInfo.imbuement->combatType; damage.secondary.value = damage.primary.value * (damagePercent); @@ -748,7 +750,7 @@ void Combat::CombatConditionFunc(const std::shared_ptr &caster, const player->sendCancelMessage("You are still immune against this spell."); return; } else if (caster && caster->getMonster()) { - uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_CLEANSE, false, 0); + const uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_CLEANSE, false, 0); if (playerCharmRaceid != 0) { const auto &mType = g_monsters().getMonsterType(caster->getName()); if (mType && playerCharmRaceid == mType->info.raceid) { @@ -864,7 +866,7 @@ void Combat::combatTileEffects(const CreatureVector &spectators, const std::shar item->setOwner(caster); } - ReturnValue ret = g_game().internalAddItem(tile, item); + const ReturnValue ret = g_game().internalAddItem(tile, item); if (ret == RETURNVALUE_NOERROR) { item->startDecaying(); } @@ -947,7 +949,7 @@ void Combat::doChainEffect(const Position &origin, const Position &dest, uint8_t fpp.maxSearchDist = 9; Position pos = origin; if (g_game().map.getPathMatching(origin, dirList, FrozenPathingConditionCall(dest), fpp)) { - for (auto dir : dirList) { + for (const auto &dir : dirList) { pos = getNextPosition(dir, pos); g_game().addMagicEffect(pos, effect); } @@ -993,7 +995,7 @@ void Combat::setupChain(const std::shared_ptr &weapon) { weapon->params.chainCallback = std::make_unique(); auto setCommonValues = [this, weapon](double formula, SoundEffect_t impactSound, uint32_t effect) { - double weaponSkillFormula = weapon->getChainSkillValue(); + const double weaponSkillFormula = weapon->getChainSkillValue(); setPlayerCombatValues(COMBAT_FORMULA_SKILL, 0, 0, weaponSkillFormula ? weaponSkillFormula : formula, 0); setParam(COMBAT_PARAM_IMPACTSOUND, impactSound); setParam(COMBAT_PARAM_EFFECT, effect); @@ -1053,9 +1055,9 @@ bool Combat::doCombatChain(const std::shared_ptr &caster, const std::s int i = 0; auto combat = this; for (const auto &[from, toVector] : targets) { - auto delay = i * std::max(50, g_configManager().getNumber(COMBAT_CHAIN_DELAY, __FUNCTION__)); + const auto delay = i * std::max(50, g_configManager().getNumber(COMBAT_CHAIN_DELAY, __FUNCTION__)); ++i; - for (auto to : toVector) { + for (const auto &to : toVector) { auto nextTarget = g_game().getCreatureByID(to); if (!nextTarget) { continue; @@ -1114,7 +1116,7 @@ bool Combat::doCombat(const std::shared_ptr &caster, const Position &p doCombatMana(caster, position, area, damage, params); } } else { - auto origin = caster != nullptr ? caster->getPosition() : Position(); + const auto origin = caster != nullptr ? caster->getPosition() : Position(); CombatFunc(caster, origin, position, area, params, CombatNullFunc, nullptr); } @@ -1257,7 +1259,7 @@ void Combat::doCombatHealth(const std::shared_ptr &caster, const std:: } void Combat::doCombatHealth(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, CombatDamage &damage, const CombatParams ¶ms) { - bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); + const bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster && target) && (caster == target || canCombat) && (params.impactEffect != CONST_ME_NONE)) { @@ -1340,7 +1342,7 @@ void Combat::doCombatCondition(const std::shared_ptr &caster, const Po } void Combat::doCombatCondition(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms) { - bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); + const bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster == target || canCombat) && params.impactEffect != CONST_ME_NONE) { g_game().addMagicEffect(target->getPosition(), params.impactEffect); } @@ -1369,7 +1371,7 @@ void Combat::doCombatDispel(const std::shared_ptr &caster, const Posit } void Combat::doCombatDispel(const std::shared_ptr &caster, const std::shared_ptr &target, const CombatParams ¶ms) { - bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); + const bool canCombat = !params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR); if ((caster && target) && (caster == target || canCombat) && (params.impactEffect != CONST_ME_NONE)) { @@ -1400,7 +1402,7 @@ void Combat::doCombatDispel(const std::shared_ptr &caster, const std:: void Combat::doCombatDefault(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, const CombatParams ¶ms) { if (!params.aggressive || (caster != target && Combat::canDoCombat(caster, target, params.aggressive) == RETURNVALUE_NOERROR)) { - auto spectators = Spectators().find(target->getPosition(), true); + const auto spectators = Spectators().find(target->getPosition(), true); CombatNullFunc(caster, target, params, nullptr); combatTileEffects(spectators.data(), caster, target->getTile(), params); @@ -1472,7 +1474,7 @@ std::vector>> Combat::pickChainTargets continue; } - double distance = Position::getEuclideanDistance(currentTarget->getPosition(), spectator->getPosition()); + const double distance = Position::getEuclideanDistance(currentTarget->getPosition(), spectator->getPosition()); if (distance < closestDistance) { closestDistance = distance; closestSpectator = spectator; @@ -1485,7 +1487,7 @@ std::vector>> Combat::pickChainTargets bool found = false; for (auto &[pos, vec] : resultMap) { if (pos == currentTarget->getPosition()) { - vec.push_back(closestSpectator->getID()); + vec.emplace_back(closestSpectator->getID()); found = true; break; } @@ -1497,7 +1499,8 @@ std::vector>> Combat::pickChainTargets targets.push_back(closestSpectator); visited.insert(closestSpectator->getID()); continue; - } else if (backtracking) { + } + if (backtracking) { g_logger().debug("[{}] backtracking", __METHOD_NAME__); targets.pop_back(); backtrackingAttempts--; @@ -1511,9 +1514,9 @@ std::vector>> Combat::pickChainTargets } bool Combat::isValidChainTarget(const std::shared_ptr &caster, const std::shared_ptr ¤tTarget, const std::shared_ptr &potentialTarget, const CombatParams ¶ms, bool aggressive) { - bool canCombat = canDoCombat(caster, potentialTarget, aggressive) == RETURNVALUE_NOERROR; - bool pick = params.chainPickerCallback ? params.chainPickerCallback->onChainCombat(caster, potentialTarget) : true; - bool hasSight = g_game().isSightClear(currentTarget->getPosition(), potentialTarget->getPosition(), true); + const bool canCombat = canDoCombat(caster, potentialTarget, aggressive) == RETURNVALUE_NOERROR; + const bool pick = params.chainPickerCallback ? params.chainPickerCallback->onChainCombat(caster, potentialTarget) : true; + const bool hasSight = g_game().isSightClear(currentTarget->getPosition(), potentialTarget->getPosition(), true); return canCombat && pick && hasSight; } @@ -1531,7 +1534,7 @@ uint32_t ValueCallback::getMagicLevelSkill(const std::shared_ptr &player // Rune conjuring spell have the same name as the rune item spell. const std::shared_ptr &conjuringSpell = g_spells().getInstantSpellByName(damage.runeSpellName); if (spell && conjuringSpell && conjuringSpell != spell && normal_random(0, 100) <= 25) { - uint32_t castResult = conjuringSpell->canCast(player) ? 20 : 10; + const uint32_t castResult = conjuringSpell->canCast(player) ? 20 : 10; magicLevelSkill += magicLevelSkill * castResult / 100; } } @@ -1603,15 +1606,15 @@ void ValueCallback::getMinMaxValues(const std::shared_ptr &player, Comba if (lua_pcall(L, parameters, 2, 0) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else { - int32_t defaultDmg = normal_random( + const int32_t defaultDmg = normal_random( LuaScriptInterface::getNumber(L, -2), LuaScriptInterface::getNumber(L, -1) ); if (shouldCalculateSecondaryDamage) { - double factor = (double)elementAttack / (double)attackValue; // attack value here is phys dmg + element dmg - int32_t elementDamage = std::round(defaultDmg * factor); - int32_t physDmg = std::round(defaultDmg * (1.0 - factor)); + const double factor = static_cast(elementAttack) / static_cast(attackValue); // attack value here is phys dmg + element dmg + const int32_t elementDamage = std::round(defaultDmg * factor); + const int32_t physDmg = std::round(defaultDmg * (1.0 - factor)); damage.primary.value = physDmg; damage.secondary.value = elementDamage; } else { @@ -1723,7 +1726,7 @@ void ChainCallback::getChainValues(const std::shared_ptr &creature, ui backtracking = m_backtracking; } } -void ChainCallback::onChainCombat(const std::shared_ptr &creature, uint8_t &maxTargets, uint8_t &chainDistance, bool &backtracking) { +void ChainCallback::onChainCombat(const std::shared_ptr &creature, uint8_t &maxTargets, uint8_t &chainDistance, bool &backtracking) const { // onChainCombat(creature) if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[ChainCallback::onTargetCombat - Creature {}] " @@ -1798,7 +1801,7 @@ bool ChainPickerCallback::onChainCombat(const std::shared_ptr &creatur lua_pushnil(L); } - int size0 = lua_gettop(L); + const int size0 = lua_gettop(L); bool result = true; if (lua_pcall(L, 2, 1 /*nReturnValues*/, 0) != 0) { @@ -1856,7 +1859,7 @@ void AreaCombat::getList(const Position ¢erPos, const Position &targetPos, s } } -void AreaCombat::copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op) { +void AreaCombat::copyArea(const std::unique_ptr &input, const std::unique_ptr &output, const MatrixOperation_t &op) const { uint32_t centerY, centerX; input->getCenter(centerY, centerX); @@ -1888,8 +1891,8 @@ void AreaCombat::copyArea(const std::unique_ptr &input, const std::u output->setCenter((input->getCols() - 1) - centerY, centerX); } else { // rotation - int32_t rotateCenterX = (output->getCols() / 2) - 1; - int32_t rotateCenterY = (output->getRows() / 2) - 1; + const int32_t rotateCenterX = (output->getCols() / 2) - 1; + const int32_t rotateCenterY = (output->getRows() / 2) - 1; int32_t angle; switch (op) { @@ -1910,23 +1913,23 @@ void AreaCombat::copyArea(const std::unique_ptr &input, const std::u break; } - double angleRad = M_PI * angle / 180.0; + const double angleRad = M_PI * angle / 180.0; - double a = std::cos(angleRad); - double b = -std::sin(angleRad); - double c = std::sin(angleRad); - double d = std::cos(angleRad); + const double a = std::cos(angleRad); + const double b = -std::sin(angleRad); + const double c = std::sin(angleRad); + const double d = std::cos(angleRad); const uint32_t rows = input->getRows(); for (uint32_t x = 0, cols = input->getCols(); x < cols; ++x) { for (uint32_t y = 0; y < rows; ++y) { // calculate new coordinates using rotation center - int32_t newX = x - centerX; - int32_t newY = y - centerY; + const int32_t newX = x - centerX; + const int32_t newY = y - centerY; // perform rotation - auto rotatedX = static_cast(round(newX * a + newY * b)); - auto rotatedY = static_cast(round(newX * c + newY * d)); + const auto rotatedX = static_cast(round(newX * a + newY * b)); + const auto rotatedY = static_cast(round(newX * c + newY * d)); // write in the output matrix using rotated coordinates (*output)[rotatedY + rotateCenterY][rotatedX + rotateCenterX] = (*input)[y][x]; @@ -1969,7 +1972,7 @@ std::unique_ptr AreaCombat::createArea(const std::list &li return area; } -void AreaCombat::setupArea(const std::list &list, uint32_t rows) { +void AreaCombat::setupArea(const std::list &list, const uint32_t rows) { auto northArea = createArea(list, rows); const uint32_t maxOutput = std::max(northArea->getCols(), northArea->getRows()) * 2; @@ -1992,7 +1995,7 @@ void AreaCombat::setupArea(const std::list &list, uint32_t rows) { void AreaCombat::setupArea(int32_t length, int32_t spread) { std::list list; - uint32_t rows = length; + const uint32_t rows = length; int32_t cols = 1; if (spread != 0) { @@ -2002,8 +2005,8 @@ void AreaCombat::setupArea(int32_t length, int32_t spread) { int32_t colSpread = cols; for (uint32_t y = 1; y <= rows; ++y) { - int32_t mincol = cols - colSpread + 1; - int32_t maxcol = cols - (cols - colSpread); + const int32_t mincol = cols - colSpread + 1; + const int32_t maxcol = cols - (cols - colSpread); for (int32_t x = 1; x <= cols; ++x) { if (y == rows && x == ((cols - (cols % 2)) / 2) + 1) { @@ -2043,7 +2046,7 @@ void AreaCombat::setupArea(int32_t radius) { std::list list; for (auto &row : area) { - for (int cell : row) { + for (const int cell : row) { if (cell == 1) { list.push_back(3); } else if (cell > 0 && cell <= radius) { @@ -2102,16 +2105,16 @@ void MagicField::onStepInField(const std::shared_ptr &creature) { const ItemType &it = items[getID()]; if (it.conditionDamage) { const auto &conditionCopy = it.conditionDamage->clone(); - auto ownerId = getOwnerId(); + const auto ownerId = getOwnerId(); if (ownerId) { bool harmfulField = true; - auto itemTile = getTile(); + const auto &itemTile = getTile(); if (g_game().getWorldType() == WORLD_TYPE_NO_PVP || (itemTile && itemTile->hasFlag(TILESTATE_NOPVPZONE))) { - auto ownerPlayer = g_game().getPlayerByGUID(ownerId); + const auto &ownerPlayer = g_game().getPlayerByGUID(ownerId); if (ownerPlayer) { harmfulField = false; } - auto ownerCreature = g_game().getCreatureByID(ownerId); + const auto &ownerCreature = g_game().getCreatureByID(ownerId); if (ownerCreature) { if (ownerCreature->getPlayer() || (ownerCreature->isSummon() && ownerCreature->getMaster()->getPlayer())) { harmfulField = false; @@ -2155,7 +2158,7 @@ void Combat::applyExtensions(const std::shared_ptr &caster, const std: chance = player->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); bonus = player->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE); if (target && target->getMonster()) { - uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_LOW, false, 0); + const uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_LOW, false, 0); if (playerCharmRaceid != 0) { const auto &mType = g_monsters().getMonsterType(target->getName()); if (mType && playerCharmRaceid == mType->info.raceid) { @@ -2172,8 +2175,8 @@ void Combat::applyExtensions(const std::shared_ptr &caster, const std: } bonus += damage.criticalDamage; - double multiplier = 1.0 + static_cast(bonus) / 10000; - chance += (uint16_t)damage.criticalChance; + const double multiplier = 1.0 + static_cast(bonus) / 10000; + chance += static_cast(damage.criticalChance); if (chance != 0 && uniform_random(1, 10000) <= chance) { damage.critical = true; @@ -2185,8 +2188,8 @@ void Combat::applyExtensions(const std::shared_ptr &caster, const std: // Fatal hit (onslaught) if (const auto &playerWeapon = player->getInventoryItem(CONST_SLOT_LEFT); playerWeapon != nullptr && playerWeapon->getTier() > 0) { - double_t fatalChance = playerWeapon->getFatalChance(); - double_t randomChance = uniform_random(0, 10000) / 100; + const double_t fatalChance = playerWeapon->getFatalChance(); + const double_t randomChance = uniform_random(0, 10000) / 100; if (fatalChance > 0 && randomChance < fatalChance) { damage.fatal = true; damage.primary.value += static_cast(std::round(damage.primary.value * 0.6)); diff --git a/src/creatures/combat/combat.hpp b/src/creatures/combat/combat.hpp index 71a1e08069b..f2831e652c9 100644 --- a/src/creatures/combat/combat.hpp +++ b/src/creatures/combat/combat.hpp @@ -11,7 +11,6 @@ #include "lua/global/baseevents.hpp" #include "creatures/combat/condition.hpp" -#include "declarations.hpp" #include "map/map.hpp" class Condition; @@ -25,7 +24,7 @@ class Weapon; // for luascript callback class ValueCallback final : public CallBack { public: - explicit ValueCallback(formulaType_t initType) : + explicit ValueCallback(const formulaType_t initType) : type(initType) { } /** @@ -61,7 +60,7 @@ class TargetCallback final : public CallBack { class ChainCallback final : public CallBack { public: ChainCallback() = default; - ChainCallback(uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking) : + ChainCallback(const uint8_t &chainTargets, const uint8_t &chainDistance, const bool &backtracking) : m_chainDistance(chainDistance), m_chainTargets(chainTargets), m_backtracking(backtracking) { } void getChainValues(const std::shared_ptr &creature, uint8_t &maxTargets, uint8_t &chainDistance, bool &backtracking); @@ -70,7 +69,7 @@ class ChainCallback final : public CallBack { } private: - void onChainCombat(const std::shared_ptr &creature, uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking); + void onChainCombat(const std::shared_ptr &creature, uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking) const; uint8_t m_chainDistance = 0; uint8_t m_chainTargets = 0; @@ -162,12 +161,11 @@ class MatrixArea { // non-assignable MatrixArea &operator=(const MatrixArea &) = delete; - void setValue(uint32_t row, uint32_t col, bool value) { + void setValue(uint32_t row, uint32_t col, bool value) const { if (row < rows && col < cols) { data_[row][col] = value; } else { g_logger().error("[{}] Access exceeds the upper limit of memory block"); - throw std::out_of_range("Access exceeds the upper limit of memory block"); } } bool getValue(uint32_t row, uint32_t col) const { @@ -232,11 +230,11 @@ class AreaCombat { private: std::unique_ptr createArea(const std::list &list, uint32_t rows); - void copyArea(const std::unique_ptr &input, const std::unique_ptr &output, MatrixOperation_t op); + void copyArea(const std::unique_ptr &input, const std::unique_ptr &output, const MatrixOperation_t &op) const; const std::unique_ptr &getArea(const Position ¢erPos, const Position &targetPos) const { - int32_t dx = Position::getOffsetX(targetPos, centerPos); - int32_t dy = Position::getOffsetY(targetPos, centerPos); + const int32_t dx = Position::getOffsetX(targetPos, centerPos); + const int32_t dy = Position::getOffsetY(targetPos, centerPos); Direction dir; if (dx < 0) { @@ -308,7 +306,7 @@ class Combat { bool doCombat(const std::shared_ptr &caster, const std::shared_ptr &target, const Position &origin, int affected = 1) const; bool doCombat(const std::shared_ptr &caster, const Position &pos) const; - bool setCallback(CallBackParam_t key); + bool setCallback(const CallBackParam_t &key); void setChainCallback(uint8_t chainTargets, uint8_t chainDistance, bool backtracking); CallBack* getCallback(CallBackParam_t key) const; diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 056e282ddbd..835200fecc8 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -54,7 +54,7 @@ bool Creature::canSee(const Position &pos) { return canSee(getPosition(), pos, MAP_MAX_VIEW_PORT_X, MAP_MAX_VIEW_PORT_Y); } -bool Creature::canSeeCreature(std::shared_ptr creature) const { +bool Creature::canSeeCreature(const std::shared_ptr &creature) const { if (!canSeeInvisibility() && creature->isInvisible()) { return false; } @@ -337,7 +337,7 @@ void Creature::onAddTileItem(const std::shared_ptr &tileItem, const Positi } } -void Creature::onUpdateTileItem(std::shared_ptr updateTile, const Position &pos, std::shared_ptr, const ItemType &oldType, std::shared_ptr, const ItemType &newType) { +void Creature::onUpdateTileItem(const std::shared_ptr &updateTile, const Position &pos, const std::shared_ptr &, const ItemType &oldType, const std::shared_ptr &, const ItemType &newType) { if (!isMapLoaded) { return; } @@ -349,7 +349,7 @@ void Creature::onUpdateTileItem(std::shared_ptr updateTile, const Position } } -void Creature::onRemoveTileItem(std::shared_ptr updateTile, const Position &pos, const ItemType &iType, std::shared_ptr) { +void Creature::onRemoveTileItem(const std::shared_ptr &updateTile, const Position &pos, const ItemType &iType, const std::shared_ptr &) { if (!isMapLoaded) { return; } @@ -770,7 +770,7 @@ void Creature::onDeath() { } } -bool Creature::dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { +bool Creature::dropCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { metrics::method_latency measure(__METHOD_NAME__); if (!lootDrop && getMonster()) { if (getMaster()) { @@ -1024,7 +1024,7 @@ BlockType_t Creature::blockHit(const std::shared_ptr &attacker, const return blockType; } -bool Creature::setAttackedCreature(std::shared_ptr creature) { +bool Creature::setAttackedCreature(const std::shared_ptr &creature) { if (creature) { auto monster = getMonster(); auto tile = getTile(); @@ -1135,7 +1135,7 @@ bool Creature::canFollowMaster() const { return tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE) && (canSeeInvisibility() || !master->isInvisible()); } -bool Creature::setFollowCreature(std::shared_ptr creature) { +bool Creature::setFollowCreature(const std::shared_ptr &creature) { metrics::method_latency measure(__METHOD_NAME__); if (creature) { if (getFollowCreature() == creature) { @@ -1190,7 +1190,7 @@ double Creature::getDamageRatio(const std::shared_ptr &attacker) const return (static_cast(attackerDamage) / totalDamage); } -uint64_t Creature::getGainedExperience(std::shared_ptr attacker) const { +uint64_t Creature::getGainedExperience(const std::shared_ptr &attacker) const { return std::floor(getDamageRatio(attacker) * getLostExperience()); } @@ -1268,7 +1268,7 @@ void Creature::onTickCondition(ConditionType_t type, bool &bRemove) { } } -void Creature::onCombatRemoveCondition(std::shared_ptr condition) { +void Creature::onCombatRemoveCondition(const std::shared_ptr &condition) { removeCondition(condition); } @@ -1276,7 +1276,7 @@ void Creature::onAttacked() { // } -void Creature::onAttackedCreatureDrainHealth(std::shared_ptr target, int32_t points) { +void Creature::onAttackedCreatureDrainHealth(const std::shared_ptr &target, int32_t points) { target->addDamagePoints(static_self_cast(), points); } @@ -1303,7 +1303,7 @@ bool Creature::deprecatedOnKilledCreature(const std::shared_ptr &targe return false; } -void Creature::onGainExperience(uint64_t gainExp, std::shared_ptr target) { +void Creature::onGainExperience(uint64_t gainExp, const std::shared_ptr &target) { metrics::method_latency measure(__METHOD_NAME__); auto master = getMaster(); if (gainExp == 0 || !master) { @@ -1462,7 +1462,7 @@ void Creature::removeCombatCondition(ConditionType_t type) { } void Creature::removeCondition(const std::shared_ptr &condition) { - auto it = std::find(conditions.begin(), conditions.end(), condition); + const auto it = std::ranges::find(conditions, condition); if (it == conditions.end()) { return; } diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index 7811d833f46..0a6bf68a8f4 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -117,7 +117,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void addList() = 0; virtual bool canSee(const Position &pos); - virtual bool canSeeCreature(std::shared_ptr creature) const; + virtual bool canSeeCreature(const std::shared_ptr &creature) const; virtual RaceType_t getRace() const { return RACE_NONE; @@ -313,7 +313,7 @@ class Creature : virtual public Thing, public SharedObject { std::shared_ptr getFollowCreature() const { return m_followCreature.lock(); } - virtual bool setFollowCreature(std::shared_ptr creature); + virtual bool setFollowCreature(const std::shared_ptr &creature); // follow events virtual void onFollowCreature(const std::shared_ptr &) { @@ -327,7 +327,7 @@ class Creature : virtual public Thing, public SharedObject { std::shared_ptr getAttackedCreature() { return m_attackedCreature.lock(); } - virtual bool setAttackedCreature(std::shared_ptr creature); + virtual bool setAttackedCreature(const std::shared_ptr &creature); /** * @brief Mitigates damage inflicted on a creature. @@ -433,7 +433,7 @@ class Creature : virtual public Thing, public SharedObject { } void onDeath(); - virtual uint64_t getGainedExperience(std::shared_ptr attacker) const; + virtual uint64_t getGainedExperience(const std::shared_ptr &attacker) const; void addDamagePoints(const std::shared_ptr &attacker, int32_t damagePoints); bool hasBeenAttacked(uint32_t attackerId); @@ -442,11 +442,11 @@ class Creature : virtual public Thing, public SharedObject { virtual void onAddCombatCondition(const ConditionType_t &type); virtual void onEndCondition(const ConditionType_t &type); void onTickCondition(ConditionType_t type, bool &bRemove); - virtual void onCombatRemoveCondition(std::shared_ptr condition); - virtual void onAttackedCreature(std::shared_ptr) { } + virtual void onCombatRemoveCondition(const std::shared_ptr &condition); + virtual void onAttackedCreature(const std::shared_ptr &) { } virtual void onAttacked(); - virtual void onAttackedCreatureDrainHealth(std::shared_ptr target, int32_t points); - virtual void onTargetCreatureGainHealth(std::shared_ptr, int32_t) { } + virtual void onAttackedCreatureDrainHealth(const std::shared_ptr &target, int32_t points); + virtual void onTargetCreatureGainHealth(const std::shared_ptr &, int32_t) { } void onAttackedCreatureKilled(const std::shared_ptr &target); /** * @deprecated -- This is here to trigger the deprecated onKill events in lua @@ -458,8 +458,8 @@ class Creature : virtual public Thing, public SharedObject { virtual bool onKilledMonster([[maybe_unused]] const std::shared_ptr &target) { return false; }; - virtual void onGainExperience(uint64_t gainExp, std::shared_ptr target); - virtual void onAttackedCreatureBlockHit(BlockType_t) { } + virtual void onGainExperience(uint64_t gainExp, const std::shared_ptr &target); + virtual void onAttackedCreatureBlockHit(const BlockType_t &) { } virtual void onBlockHit() { } virtual void onTakeDamage(std::shared_ptr, int32_t) { } virtual void onChangeZone(ZoneType_t zone); @@ -478,8 +478,8 @@ class Creature : virtual public Thing, public SharedObject { virtual void turnToCreature(std::shared_ptr creature); void onAddTileItem(const std::shared_ptr &tile, const Position &pos); - virtual void onUpdateTileItem(std::shared_ptr tile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType); - virtual void onRemoveTileItem(std::shared_ptr tile, const Position &pos, const ItemType &iType, std::shared_ptr item); + virtual void onUpdateTileItem(const std::shared_ptr &tile, const Position &pos, const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType); + virtual void onRemoveTileItem(const std::shared_ptr &tile, const Position &pos, const ItemType &iType, const std::shared_ptr &item); virtual void onCreatureAppear(const std::shared_ptr &creature, bool isLogin); virtual void onRemoveCreature(const std::shared_ptr &creature, bool isLogout); @@ -821,7 +821,7 @@ class Creature : virtual public Thing, public SharedObject { } virtual void getPathSearchParams(const std::shared_ptr &, FindPathParams &fpp); virtual void death(std::shared_ptr) { } - virtual bool dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); + virtual bool dropCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); virtual std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature); friend class Game; diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index bb29b2b1bec..202c8d6a656 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -84,7 +84,7 @@ void NpcType::loadShop(const std::shared_ptr &npcType, ShopBlock shopBl } // Check if the item already exists in the shop vector and ignore it - if (std::any_of(npcType->info.shopItemVector.begin(), npcType->info.shopItemVector.end(), [&shopBlock](const auto &shopIterator) { + if (std::ranges::any_of(npcType->info.shopItemVector, [&shopBlock](const auto &shopIterator) { return shopIterator == shopBlock; })) { return; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index ce122d0275d..50f3f71155e 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -46,7 +46,6 @@ MuteCountMap Player::muteCountMap; Player::Player(ProtocolGame_ptr p) : - Creature(), lastPing(OTSYS_TIME()), lastPong(lastPing), inbox(std::make_shared(ITEM_INBOX)), @@ -60,16 +59,16 @@ Player::Player(ProtocolGame_ptr p) : } Player::~Player() { - for (const std::shared_ptr &item : inventory) { + for (const auto &item : inventory) { if (item) { item->resetParent(); item->stopDecaying(); } } - for (const auto &it : depotLockerMap) { - it.second->removeInbox(inbox); - it.second->stopDecaying(); + for (const auto &[fst, snd] : depotLockerMap) { + snd->removeInbox(inbox); + snd->stopDecaying(); } inbox->stopDecaying(); @@ -231,7 +230,7 @@ std::shared_ptr Player::getInventoryItem(Slots_t slot) const { } bool Player::isSuppress(ConditionType_t conditionType, bool attackerPlayer) const { - auto minDelay = g_configManager().getNumber(MIN_DELAY_BETWEEN_CONDITIONS, __FUNCTION__); + const auto minDelay = g_configManager().getNumber(MIN_DELAY_BETWEEN_CONDITIONS, __FUNCTION__); if (IsConditionSuppressible(conditionType) && checkLastConditionTimeWithin(conditionType, minDelay)) { return true; } @@ -255,7 +254,7 @@ std::shared_ptr Player::getWeapon(Slots_t slot, bool ignoreAmmo) const { return nullptr; } - WeaponType_t weaponType = item->getWeaponType(); + const WeaponType_t &weaponType = item->getWeaponType(); if (weaponType == WEAPON_NONE || weaponType == WEAPON_SHIELD || weaponType == WEAPON_AMMO) { return nullptr; } @@ -276,7 +275,7 @@ bool Player::hasQuiverEquipped() const { } bool Player::hasWeaponDistanceEquipped() const { - const auto item = inventory[CONST_SLOT_LEFT]; + const auto &item = inventory[CONST_SLOT_LEFT]; return item && item->getWeaponType() == WEAPON_DISTANCE; } @@ -285,9 +284,9 @@ std::shared_ptr Player::getQuiverAmmoOfType(const ItemType &it) const { return nullptr; } - std::shared_ptr quiver = inventory[CONST_SLOT_RIGHT]; - for (std::shared_ptr container = quiver->getContainer(); - auto ammoItem : container->getItemList()) { + const auto &quiver = inventory[CONST_SLOT_RIGHT]; + for (const auto &container = quiver->getContainer(); + const auto &ammoItem : container->getItemList()) { if (ammoItem->getAmmoType() == it.ammoType) { if (level >= Item::items[ammoItem->getID()].minReqLevel) { return ammoItem; @@ -311,7 +310,7 @@ std::shared_ptr Player::getWeapon(bool ignoreAmmo /* = false*/) const { } WeaponType_t Player::getWeaponType() const { - const auto item = getWeapon(); + const auto &item = getWeapon(); if (!item) { return WEAPON_NONE; } @@ -325,7 +324,7 @@ int32_t Player::getWeaponSkill(const std::shared_ptr &item) const { int32_t attackSkill; - WeaponType_t weaponType = item->getWeaponType(); + const WeaponType_t &weaponType = item->getWeaponType(); switch (weaponType) { case WEAPON_SWORD: { attackSkill = getSkillLevel(SKILL_SWORD); @@ -359,14 +358,14 @@ int32_t Player::getWeaponSkill(const std::shared_ptr &item) const { int32_t Player::getArmor() const { int32_t armor = 0; - static const Slots_t armorSlots[] = { CONST_SLOT_HEAD, CONST_SLOT_NECKLACE, CONST_SLOT_ARMOR, CONST_SLOT_LEGS, CONST_SLOT_FEET, CONST_SLOT_RING, CONST_SLOT_AMMO }; - for (Slots_t slot : armorSlots) { - std::shared_ptr inventoryItem = inventory[slot]; + static constexpr Slots_t armorSlots[] = { CONST_SLOT_HEAD, CONST_SLOT_NECKLACE, CONST_SLOT_ARMOR, CONST_SLOT_LEGS, CONST_SLOT_FEET, CONST_SLOT_RING, CONST_SLOT_AMMO }; + for (const Slots_t &slot : armorSlots) { + const auto &inventoryItem = inventory[slot]; if (inventoryItem) { armor += inventoryItem->getArmor(); } } - return static_cast(armor * vocation->armorMultiplier); + return armor * static_cast(vocation->armorMultiplier); } void Player::getShieldAndWeapon(std::shared_ptr &shield, std::shared_ptr &weapon) const { @@ -374,7 +373,7 @@ void Player::getShieldAndWeapon(std::shared_ptr &shield, std::shared_ptr Player::getClientIcons() { icons.insert(PlayerIcon::RedSwords); } - auto tile = getTile(); + const auto &tile = getTile(); if (tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { if (icons.size() < 9) { icons.insert(PlayerIcon::Pigeon); @@ -551,7 +550,7 @@ void Player::updateInventoryWeight() { inventoryWeight = 0; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (item) { inventoryWeight += item->getWeight(); } @@ -560,12 +559,12 @@ void Player::updateInventoryWeight() { void Player::updateInventoryImbuement() { // Get the tile the player is currently on - std::shared_ptr playerTile = getTile(); + const auto &playerTile = getTile(); // Check if the player is in a protection zone - bool isInProtectionZone = playerTile && playerTile->hasFlag(TILESTATE_PROTECTIONZONE); + const bool &isInProtectionZone = playerTile && playerTile->hasFlag(TILESTATE_PROTECTIONZONE); // Check if the player is in fight mode - bool isInFightMode = hasCondition(CONDITION_INFIGHT); - bool nonAggressiveFightOnly = g_configManager().getBoolean(TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY, __FUNCTION__); + const bool isInFightMode = hasCondition(CONDITION_INFIGHT); + const bool nonAggressiveFightOnly = g_configManager().getBoolean(TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY, __FUNCTION__); // Iterate through all items in the player's inventory for (const auto &[key, item] : getAllSlotItems()) { @@ -580,12 +579,12 @@ void Player::updateInventoryImbuement() { } // Imbuement from imbuementInfo, this variable reduces code complexity - auto imbuement = imbuementInfo.imbuement; + const auto imbuement = imbuementInfo.imbuement; // Get the category of the imbuement const CategoryImbuement* categoryImbuement = g_imbuements().getCategoryByID(imbuement->getCategory()); // Parent of the imbued item - auto parent = item->getParent(); - bool isInBackpack = parent && parent->getContainer(); + const auto &parent = item->getParent(); + const bool &isInBackpack = parent && parent->getContainer(); // If the imbuement is aggressive and the player is not in fight mode or is in a protection zone, or the item is in a container, ignore it. if (categoryImbuement && (categoryImbuement->agressive || nonAggressiveFightOnly) && (isInProtectionZone || !isInFightMode || isInBackpack)) { continue; @@ -604,14 +603,13 @@ void Player::updateInventoryImbuement() { g_logger().trace("Decaying imbuement {} from item {} of player {}", imbuement->getName(), item->getName(), getName()); // Calculate the new duration of the imbuement, making sure it doesn't go below 0 - uint32_t duration = std::max(0, imbuementInfo.duration - EVENT_IMBUEMENT_INTERVAL / 1000); + const uint32_t duration = std::max(0, imbuementInfo.duration - EVENT_IMBUEMENT_INTERVAL / 1000); // Update the imbuement's duration in the item item->decayImbuementTime(slotid, imbuement->getID(), duration); if (duration == 0) { removeItemImbuementStats(imbuement); updateImbuementTrackerStats(); - continue; } } } @@ -620,7 +618,7 @@ void Player::updateInventoryImbuement() { phmap::flat_hash_map> Player::getAllSlotItems() const { phmap::flat_hash_map> itemMap; for (uint8_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } @@ -779,10 +777,10 @@ void Player::addContainer(uint8_t cid, const std::shared_ptr &contain return; } - auto it = openContainers.find(cid); + const auto it = openContainers.find(cid); if (it != openContainers.end()) { OpenContainer &openContainer = it->second; - auto oldContainer = openContainer.container; + const auto &oldContainer = openContainer.container; if (oldContainer->getID() == ITEM_BROWSEFIELD) { } @@ -797,13 +795,13 @@ void Player::addContainer(uint8_t cid, const std::shared_ptr &contain } void Player::closeContainer(uint8_t cid) { - auto it = openContainers.find(cid); + const auto it = openContainers.find(cid); if (it == openContainers.end()) { return; } OpenContainer openContainer = it->second; - std::shared_ptr container = openContainer.container; + const auto &container = openContainer.container; if (container && container->isAnyKindOfRewardChest() && !hasOtherRewardContainerOpen(container)) { removeEmptyRewards(); @@ -824,14 +822,14 @@ void Player::removeEmptyRewards() { }); } -bool Player::hasOtherRewardContainerOpen(const std::shared_ptr container) const { +bool Player::hasOtherRewardContainerOpen(const std::shared_ptr &container) const { return std::ranges::any_of(openContainers.begin(), openContainers.end(), [container](const auto &containerPair) { return containerPair.second.container != container && containerPair.second.container->isAnyKindOfRewardContainer(); }); } void Player::setContainerIndex(uint8_t cid, uint16_t index) { - auto it = openContainers.find(cid); + const auto it = openContainers.find(cid); if (it == openContainers.end()) { return; } @@ -839,7 +837,7 @@ void Player::setContainerIndex(uint8_t cid, uint16_t index) { } std::shared_ptr Player::getContainerByID(uint8_t cid) { - auto it = openContainers.find(cid); + const auto it = openContainers.find(cid); if (it == openContainers.end()) { return nullptr; } @@ -847,16 +845,16 @@ std::shared_ptr Player::getContainerByID(uint8_t cid) { } int8_t Player::getContainerID(const std::shared_ptr &container) const { - for (const auto &it : openContainers) { - if (it.second.container == container) { - return it.first; + for (const auto &[fst, snd] : openContainers) { + if (snd.container == container) { + return fst; } } return -1; } uint16_t Player::getContainerIndex(uint8_t cid) const { - auto it = openContainers.find(cid); + const auto it = openContainers.find(cid); if (it == openContainers.end()) { return 0; } @@ -870,9 +868,8 @@ bool Player::canOpenCorpse(uint32_t ownerId) const { uint16_t Player::getLookCorpse() const { if (sex == PLAYERSEX_FEMALE) { return ITEM_FEMALE_CORPSE; - } else { - return ITEM_MALE_CORPSE; } + return ITEM_MALE_CORPSE; } void Player::addStorageValue(const uint32_t key, const int32_t value, const bool isLogin /* = false*/) { @@ -883,7 +880,8 @@ void Player::addStorageValue(const uint32_t key, const int32_t value, const bool value & 0xFF ); return; - } else if (IS_IN_KEYRANGE(key, MOUNTS_RANGE)) { + } + if (IS_IN_KEYRANGE(key, MOUNTS_RANGE)) { // do nothing } else if (IS_IN_KEYRANGE(key, FAMILIARS_RANGE)) { familiars.emplace_back( @@ -912,7 +910,7 @@ void Player::addStorageValue(const uint32_t key, const int32_t value, const bool int32_t Player::getStorageValue(const uint32_t key) const { int32_t value = -1; - auto it = storageMap.find(key); + const auto it = storageMap.find(key); if (it == storageMap.end()) { return value; } @@ -922,22 +920,22 @@ int32_t Player::getStorageValue(const uint32_t key) const { } int32_t Player::getStorageValueByName(const std::string &storageName) const { - auto it = g_storages().getStorageMap().find(storageName); + const auto it = g_storages().getStorageMap().find(storageName); if (it == g_storages().getStorageMap().end()) { return -1; } - uint32_t key = it->second; + const uint32_t key = it->second; return getStorageValue(key); } void Player::addStorageValueByName(const std::string &storageName, const int32_t value, const bool isLogin /* = false*/) { - auto it = g_storages().getStorageMap().find(storageName); + const auto &it = g_storages().getStorageMap().find(storageName); if (it == g_storages().getStorageMap().end()) { g_logger().error("[{}] Storage name '{}' not found in storage map, register your storage in 'storages.xml' first for use", __func__, storageName); return; } - uint32_t key = it->second; + const uint32_t key = it->second; addStorageValue(key, value, isLogin); } @@ -948,7 +946,7 @@ bool Player::canSee(const Position &pos) { return client->canSee(pos); } -bool Player::canSeeCreature(std::shared_ptr creature) const { +bool Player::canSeeCreature(const std::shared_ptr &creature) const { if (creature.get() == this) { return true; } @@ -969,8 +967,8 @@ bool Player::canWalkthrough(const std::shared_ptr &creature) { } const auto &player = creature->getPlayer(); - std::shared_ptr monster = creature->getMonster(); - std::shared_ptr npc = creature->getNpc(); + const auto &monster = creature->getMonster(); + const auto &npc = creature->getNpc(); if (monster) { if (!monster->isFamiliar()) { return false; @@ -979,17 +977,17 @@ bool Player::canWalkthrough(const std::shared_ptr &creature) { } if (player) { - std::shared_ptr playerTile = player->getTile(); + const auto &playerTile = player->getTile(); if (!playerTile || (!playerTile->hasFlag(TILESTATE_NOPVPZONE) && !playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && player->getLevel() > static_cast(g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__)) && g_game().getWorldType() != WORLD_TYPE_NO_PVP)) { return false; } - std::shared_ptr playerTileGround = playerTile->getGround(); + const auto &playerTileGround = playerTile->getGround(); if (!playerTileGround || !playerTileGround->hasWalkStack()) { return false; } - std::shared_ptr thisPlayer = getPlayer(); + const auto &thisPlayer = getPlayer(); if ((OTSYS_TIME() - lastWalkthroughAttempt) > 2000) { thisPlayer->setLastWalkthroughAttempt(OTSYS_TIME()); return false; @@ -1002,21 +1000,22 @@ bool Player::canWalkthrough(const std::shared_ptr &creature) { thisPlayer->setLastWalkthroughPosition(creature->getPosition()); return true; - } else if (npc) { - std::shared_ptr tile = npc->getTile(); - std::shared_ptr houseTile = std::dynamic_pointer_cast(tile); + } + if (npc) { + const auto &tile = npc->getTile(); + const auto &houseTile = std::dynamic_pointer_cast(tile); return (houseTile != nullptr); } return false; } -bool Player::canWalkthroughEx(const std::shared_ptr &creature) { +bool Player::canWalkthroughEx(const std::shared_ptr &creature) const { if (group->access) { return true; } - std::shared_ptr monster = creature->getMonster(); + const auto &monster = creature->getMonster(); if (monster) { if (!monster->isFamiliar()) { return false; @@ -1025,17 +1024,17 @@ bool Player::canWalkthroughEx(const std::shared_ptr &creature) { } const auto &player = creature->getPlayer(); - std::shared_ptr npc = creature->getNpc(); + const auto &npc = creature->getNpc(); if (player) { - std::shared_ptr playerTile = player->getTile(); + const auto &playerTile = player->getTile(); return playerTile && (playerTile->hasFlag(TILESTATE_NOPVPZONE) || playerTile->hasFlag(TILESTATE_PROTECTIONZONE) || player->getLevel() <= static_cast(g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__)) || g_game().getWorldType() == WORLD_TYPE_NO_PVP); - } else if (npc) { - std::shared_ptr tile = npc->getTile(); - std::shared_ptr houseTile = std::dynamic_pointer_cast(tile); + } + if (npc) { + const auto &tile = npc->getTile(); + const auto &houseTile = std::dynamic_pointer_cast(tile); return (houseTile != nullptr); - } else { - return false; } + return false; } void Player::onReceiveMail() { @@ -1046,8 +1045,8 @@ void Player::onReceiveMail() { std::shared_ptr Player::refreshManagedContainer(ObjectCategory_t category, const std::shared_ptr &container, bool isLootContainer, bool loading /* = false*/) { std::shared_ptr previousContainer = nullptr; - auto toSetAttribute = isLootContainer ? ItemAttribute_t::QUICKLOOTCONTAINER : ItemAttribute_t::OBTAINCONTAINER; - if (auto it = m_managedContainers.find(category); it != m_managedContainers.end() && !loading) { + const auto toSetAttribute = isLootContainer ? ItemAttribute_t::QUICKLOOTCONTAINER : ItemAttribute_t::OBTAINCONTAINER; + if (const auto &it = m_managedContainers.find(category); it != m_managedContainers.end() && !loading) { previousContainer = isLootContainer ? it->second.first : it->second.second; if (previousContainer) { auto flags = previousContainer->getAttribute(toSetAttribute); @@ -1072,7 +1071,7 @@ std::shared_ptr Player::refreshManagedContainer(ObjectCategory_t cate if (container) { previousContainer = container; - if (m_managedContainers.find(category) != m_managedContainers.end()) { + if (m_managedContainers.contains(category)) { if (isLootContainer) { m_managedContainers[category].first = container; } else { @@ -1091,8 +1090,8 @@ std::shared_ptr Player::refreshManagedContainer(ObjectCategory_t cate } if (!loading) { - auto flags = container->getAttribute(toSetAttribute); - auto sendAttribute = flags | (1 << category); + const auto flags = container->getAttribute(toSetAttribute); + const auto sendAttribute = flags | (1 << category); container->setAttribute(toSetAttribute, sendAttribute); } } @@ -1126,8 +1125,8 @@ void Player::checkLootContainers(const std::shared_ptr &container) { bool shouldSend = false; for (auto it = m_managedContainers.begin(); it != m_managedContainers.end();) { - std::shared_ptr &lootContainer = it->second.first; - std::shared_ptr &obtainContainer = it->second.second; + auto &lootContainer = it->second.first; + auto &obtainContainer = it->second.second; bool removeLoot = false; bool removeObtain = false; if (lootContainer && container->getHoldingPlayer() != getPlayer() && (container == lootContainer || container->isHoldingItem(lootContainer))) { @@ -1169,8 +1168,8 @@ void Player::setMainBackpackUnassigned(const std::shared_ptr &contain // Update containers bool toSendInventoryUpdate = false; - for (bool isLootContainer : { true, false }) { - std::shared_ptr managedContainer = getManagedContainer(OBJECTCATEGORY_DEFAULT, isLootContainer); + for (const bool isLootContainer : { true, false }) { + const auto &managedContainer = getManagedContainer(OBJECTCATEGORY_DEFAULT, isLootContainer); if (!managedContainer) { refreshManagedContainer(OBJECTCATEGORY_DEFAULT, container, isLootContainer); toSendInventoryUpdate = true; @@ -1194,7 +1193,7 @@ void Player::sendLootStats(const std::shared_ptr &item, uint8_t count) { value = count; } } else if ( - auto npc = g_game().getNpcByName("The Lootmonger") + const auto &npc = g_game().getNpcByName("The Lootmonger") ) { const auto &iType = Item::items.getItemType(item->getID()); value = iType.sellPrice * count; @@ -1214,7 +1213,7 @@ bool Player::isNearDepotBox() { const Position &pos = getPosition(); for (int32_t cx = -1; cx <= 1; ++cx) { for (int32_t cy = -1; cy <= 1; ++cy) { - std::shared_ptr posTile = g_game().map.getTile(static_cast(pos.x + cx), static_cast(pos.y + cy), pos.z); + const auto &posTile = g_game().map.getTile(static_cast(pos.x + cx), static_cast(pos.y + cy), pos.z); if (!posTile) { continue; } @@ -1228,7 +1227,7 @@ bool Player::isNearDepotBox() { } std::shared_ptr Player::getDepotChest(uint32_t depotId, bool autoCreate) { - auto it = depotChests.find(depotId); + const auto it = depotChests.find(depotId); if (it != depotChests.end()) { return it->second; } @@ -1253,11 +1252,11 @@ std::shared_ptr Player::getDepotChest(uint32_t depotId, bool autoCre } std::shared_ptr Player::getDepotLocker(uint32_t depotId) { - auto it = depotLockerMap.find(depotId); + const auto it = depotLockerMap.find(depotId); if (it != depotLockerMap.end()) { inbox->setParent(it->second); for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__); i > 0; i--) { - if (std::shared_ptr depotBox = getDepotChest(i, false)) { + if (const auto &depotBox = getDepotChest(i, false)) { depotBox->setParent(it->second->getItemByIndex(0)->getContainer()); } } @@ -1265,16 +1264,16 @@ std::shared_ptr Player::getDepotLocker(uint32_t depotId) { } // We need to make room for supply stash on 12+ protocol versions and remove it for 10x. - bool createSupplyStash = !client->oldProtocol; + const bool createSupplyStash = !client->oldProtocol; - std::shared_ptr depotLocker = std::make_shared(ITEM_LOCKER, createSupplyStash ? 4 : 3); + const auto &depotLocker = std::make_shared(ITEM_LOCKER, createSupplyStash ? 4 : 3); depotLocker->setDepotId(depotId); depotLocker->internalAddThing(Item::CreateItem(ITEM_MARKET)); depotLocker->internalAddThing(inbox); if (createSupplyStash) { depotLocker->internalAddThing(Item::CreateItem(ITEM_SUPPLY_STASH)); } - std::shared_ptr depotChest = Item::CreateItemAsContainer(ITEM_DEPOT, static_cast(g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__))); + const auto &depotChest = Item::CreateItemAsContainer(ITEM_DEPOT, static_cast(g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__))); for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__); i > 0; i--) { std::shared_ptr depotBox = getDepotChest(i, true); depotChest->internalAddThing(depotBox); @@ -1295,7 +1294,7 @@ std::shared_ptr Player::getRewardChest() { } std::shared_ptr Player::getReward(const uint64_t rewardId, const bool autoCreate) { - auto it = rewardMap.find(rewardId); + const auto it = rewardMap.find(rewardId); if (it != rewardMap.end()) { return it->second; } @@ -1317,8 +1316,8 @@ void Player::removeReward(uint64_t rewardId) { void Player::getRewardList(std::vector &rewards) const { rewards.reserve(rewardMap.size()); - for (auto &it : rewardMap) { - rewards.push_back(it.first); + for (const auto &[fst, snd] : rewardMap) { + rewards.emplace_back(fst); } } @@ -1327,10 +1326,10 @@ std::vector> Player::getRewardsFromContainer(const std::sh if (container) { for (const auto &item : container->getItems(false)) { if (item->getID() == ITEM_REWARD_CONTAINER) { - auto items = getRewardsFromContainer(item->getContainer()); + const auto &items = getRewardsFromContainer(item->getContainer()); rewardItemsVector.insert(rewardItemsVector.end(), items.begin(), items.end()); } else { - rewardItemsVector.push_back(item); + rewardItemsVector.emplace_back(item); } } } @@ -1383,7 +1382,7 @@ void Player::sendPing() { } int64_t noPongTime = timeNow - lastPong; - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if ((hasLostConnection || noPongTime >= 7000) && attackedCreature && attackedCreature->getPlayer()) { setAttackedCreature(nullptr); } @@ -1404,8 +1403,8 @@ std::shared_ptr Player::getWriteItem(uint32_t &retWindowTextId, uint16_t & return writeItem; } -void Player::setImbuingItem(std::shared_ptr item) { - imbuingItem = std::move(item); +void Player::setImbuingItem(const std::shared_ptr &item) { + imbuingItem = item; } void Player::setWriteItem(const std::shared_ptr &item, uint16_t maxWriteLength /*= 0*/) { @@ -1443,7 +1442,7 @@ void Player::sendHouseWindow(const std::shared_ptr &house, uint32_t listI } } -void Player::onApplyImbuement(Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm) { +void Player::onApplyImbuement(const Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm) { if (!imbuement || !item) { return; } @@ -1455,7 +1454,7 @@ void Player::onApplyImbuement(Imbuement* imbuement, const std::shared_ptr return; } - const auto items = imbuement->getItems(); + const auto &items = imbuement->getItems(); for (auto &[key, value] : items) { const ItemType &itemType = Item::items[key]; if (static_self_cast()->getItemTypeCount(key) + this->getStashItemCount(itemType.id) < value) { @@ -1564,7 +1563,7 @@ void Player::openImbuementWindow(const std::shared_ptr &item) { return; } - auto itemParent = item->getTopParent(); + const auto &itemParent = item->getTopParent(); if (itemParent && itemParent != getPlayer()) { this->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You have to pick up the item to imbue it."); return; @@ -1579,7 +1578,7 @@ void Player::sendSaleItemList(const std::map &inventoryMap) } } -void Player::sendMarketEnter(uint32_t depotId) { +void Player::sendMarketEnter(uint32_t depotId) const { if (!client || this->getLastDepotId() == -1 || !depotId) { return; } @@ -1597,8 +1596,8 @@ void Player::sendAddContainerItem(const std::shared_ptr &container, s return; } - for (const auto &it : openContainers) { - const OpenContainer &openContainer = it.second; + for (const auto &[fst, snd] : openContainers) { + const OpenContainer &openContainer = snd; if (openContainer.container != container) { continue; } @@ -1616,7 +1615,7 @@ void Player::sendAddContainerItem(const std::shared_ptr &container, s } else if (openContainer.index >= container->capacity()) { item = container->getItemByIndex(openContainer.index - 1); } - client->sendAddContainerItem(it.first, slot, item); + client->sendAddContainerItem(fst, slot, item); } } @@ -1625,8 +1624,8 @@ void Player::sendUpdateContainerItem(const std::shared_ptr &container return; } - for (const auto &it : openContainers) { - const OpenContainer &openContainer = it.second; + for (const auto &[fst, snd] : openContainers) { + const OpenContainer &openContainer = snd; if (openContainer.container != container) { continue; } @@ -1640,7 +1639,7 @@ void Player::sendUpdateContainerItem(const std::shared_ptr &container continue; } - client->sendUpdateContainerItem(it.first, slot, newItem); + client->sendUpdateContainerItem(fst, slot, newItem); } } @@ -1653,8 +1652,8 @@ void Player::sendRemoveContainerItem(const std::shared_ptr &container return; } - for (auto &it : openContainers) { - OpenContainer &openContainer = it.second; + for (auto &[fst, snd] : openContainers) { + OpenContainer &openContainer = snd; if (openContainer.container != container) { continue; } @@ -1662,14 +1661,14 @@ void Player::sendRemoveContainerItem(const std::shared_ptr &container uint16_t &firstIndex = openContainer.index; if (firstIndex > 0 && firstIndex >= container->size() - 1) { firstIndex -= container->capacity(); - sendContainer(it.first, container, false, firstIndex); + sendContainer(fst, container, false, firstIndex); } - client->sendRemoveContainerItem(it.first, std::max(slot, firstIndex), container->getItemByIndex(container->capacity() + firstIndex)); + client->sendRemoveContainerItem(fst, std::max(slot, firstIndex), container->getItemByIndex(container->capacity() + firstIndex)); } } -void Player::onUpdateTileItem(std::shared_ptr updateTile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType) { +void Player::onUpdateTileItem(const std::shared_ptr &updateTile, const Position &pos, const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType) { Creature::onUpdateTileItem(updateTile, pos, oldItem, oldType, newItem, newType); if (oldItem != newItem) { @@ -1683,14 +1682,14 @@ void Player::onUpdateTileItem(std::shared_ptr updateTile, const Position & } } -void Player::onRemoveTileItem(std::shared_ptr fromTile, const Position &pos, const ItemType &iType, std::shared_ptr item) { +void Player::onRemoveTileItem(const std::shared_ptr &fromTile, const Position &pos, const ItemType &iType, const std::shared_ptr &item) { Creature::onRemoveTileItem(fromTile, pos, iType, item); if (tradeState != TRADE_TRANSFER) { checkTradeState(item); if (tradeItem) { - std::shared_ptr container = item->getContainer(); + const auto &container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { g_game().internalCloseTrade(static_self_cast()); } @@ -1718,7 +1717,7 @@ void Player::onCreatureAppear(const std::shared_ptr &creature, bool is updateRegeneration(); - std::shared_ptr bed = g_game().getBedBySleeper(guid); + const auto &bed = g_game().getBedBySleeper(guid); if (bed) { bed->wakeUp(static_self_cast()); } @@ -1738,7 +1737,7 @@ void Player::onCreatureAppear(const std::shared_ptr &creature, bool is offlineTime = 0; } - for (const std::shared_ptr &condition : getMuteConditions()) { + for (const auto &condition : getMuteConditions()) { condition->setTicks(condition->getTicks() - (offlineTime * 1000)); if (condition->getTicks() <= 0) { removeCondition(condition); @@ -1816,7 +1815,7 @@ void Player::onChangeZone(ZoneType_t zone) { } void Player::onAttackedCreatureChangeZone(ZoneType_t zone) { - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature) { return; } @@ -1921,11 +1920,11 @@ bool Player::closeShopWindow() { void Player::onWalk(Direction &dir) { if (hasCondition(CONDITION_FEARED)) { - Position pos = getNextPosition(dir, getPosition()); + const Position pos = getNextPosition(dir, getPosition()); - std::shared_ptr tile = g_game().map.getTile(pos); + const auto &tile = g_game().map.getTile(pos); if (tile) { - std::shared_ptr field = tile->getFieldItem(); + const auto &field = tile->getFieldItem(); if (field && !field->isBlocking() && field->getDamage() != 0) { setNextActionTask(nullptr); setNextAction(OTSYS_TIME() + getStepDuration(dir)); @@ -1987,7 +1986,7 @@ void Player::onCreatureMove(const std::shared_ptr &creature, const std } if (teleport || oldPos.z != newPos.z) { - int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY, __FUNCTION__); + const int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY, __FUNCTION__); if (ticks > 0) { if (const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks, 0)) { addCondition(condition); @@ -1998,7 +1997,7 @@ void Player::onCreatureMove(const std::shared_ptr &creature, const std void Player::onEquipInventory() { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - const auto item = inventory[slot]; + const auto &item = inventory[slot]; if (item) { item->startDecaying(); g_moveEvents().onPlayerEquip(getPlayer(), item, static_cast(slot), false); @@ -2008,7 +2007,7 @@ void Player::onEquipInventory() { void Player::onDeEquipInventory() { for (int32_t slot = CONST_SLOT_FIRST; slot <= CONST_SLOT_LAST; ++slot) { - const auto item = inventory[slot]; + const auto &item = inventory[slot]; if (item) { g_moveEvents().onPlayerDeEquip(getPlayer(), item, static_cast(slot)); } @@ -2049,9 +2048,9 @@ void Player::onCloseContainer(const std::shared_ptr &container) { return; } - for (const auto &it : openContainers) { - if (it.second.container == container) { - client->sendCloseContainer(it.first); + for (const auto &[fst, snd] : openContainers) { + if (snd.container == container) { + client->sendCloseContainer(fst); } } } @@ -2062,10 +2061,10 @@ void Player::onSendContainer(const std::shared_ptr &container) { } bool hasParent = container->hasParent(); - for (const auto &it : openContainers) { - const OpenContainer &openContainer = it.second; + for (const auto &[fst, snd] : openContainers) { + const auto &openContainer = snd; if (openContainer.container == container) { - client->sendContainer(it.first, container, hasParent, openContainer.index); + client->sendContainer(fst, container, hasParent, openContainer.index); } } } @@ -2086,7 +2085,7 @@ void Player::onRemoveInventoryItem(const std::shared_ptr &item) { checkTradeState(item); if (tradeItem) { - std::shared_ptr container = item->getContainer(); + const auto &container = item->getContainer(); if (container && container->isHoldingItem(tradeItem)) { g_game().internalCloseTrade(static_self_cast()); } @@ -2104,7 +2103,7 @@ void Player::checkTradeState(const std::shared_ptr &item) { if (tradeItem == item) { g_game().internalCloseTrade(static_self_cast()); } else { - std::shared_ptr container = std::dynamic_pointer_cast(item->getParent()); + auto container = std::dynamic_pointer_cast(item->getParent()); while (container) { if (container == tradeItem) { g_game().internalCloseTrade(static_self_cast()); @@ -2116,13 +2115,13 @@ void Player::checkTradeState(const std::shared_ptr &item) { } } -void Player::setNextWalkActionTask(std::shared_ptr task) { +void Player::setNextWalkActionTask(const std::shared_ptr &task) { if (walkTaskEvent != 0) { g_dispatcher().stopEvent(walkTaskEvent); walkTaskEvent = 0; } - walkTask = std::move(task); + walkTask = task; } void Player::setNextWalkTask(const std::shared_ptr &task) { @@ -2211,7 +2210,7 @@ void Player::onThink(uint32_t interval) { triggerTranscendance(); // Momentum (cooldown resets) triggerMomentum(); - auto playerTile = getTile(); + const auto &playerTile = getTile(); const bool vipStaysOnline = isVip() && g_configManager().getBoolean(VIP_STAY_ONLINE, __FUNCTION__); idleTime += interval; if (playerTile && !playerTile->hasFlag(TILESTATE_NOLOGOUT) && !isAccessPlayer() && !isExerciseTraining() && !vipStaysOnline) { @@ -2267,14 +2266,14 @@ void Player::removeMessageBuffer() { if (maxMessageBuffer != 0 && MessageBufferCount <= maxMessageBuffer + 1) { if (++MessageBufferCount > maxMessageBuffer) { uint32_t muteCount = 1; - auto it = muteCountMap.find(guid); + const auto it = muteCountMap.find(guid); if (it != muteCountMap.end()) { muteCount = it->second; } uint32_t muteTime = 5 * muteCount * muteCount; muteCountMap[guid] = muteCount + 1; - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000, 0); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000, 0); addCondition(condition); std::ostringstream ss; @@ -2293,7 +2292,7 @@ void Player::drainHealth(const std::shared_ptr &attacker, int32_t dama sendStats(); } -void Player::drainMana(std::shared_ptr attacker, int32_t manaLoss) { +void Player::drainMana(const std::shared_ptr attacker, int32_t manaLoss) { Creature::drainMana(attacker, manaLoss); sendStats(); } @@ -2341,7 +2340,7 @@ void Player::addManaSpent(uint64_t amount) { manaSpent += amount; - uint8_t oldPercent = magLevelPercent; + const uint8_t oldPercent = magLevelPercent; if (nextReqMana > currReqMana) { magLevelPercent = Player::getPercentLevel(manaSpent, nextReqMana); } else { @@ -2359,8 +2358,8 @@ void Player::addManaSpent(uint64_t amount) { } void Player::addExperience(const std::shared_ptr &target, uint64_t exp, bool sendText /* = false*/) { - uint64_t currLevelExp = Player::getExpForLevel(level); - uint64_t nextLevelExp = Player::getExpForLevel(level + 1); + uint64_t currLevelExp = getExpForLevel(level); + uint64_t nextLevelExp = getExpForLevel(level + 1); uint64_t rawExp = exp; if (currLevelExp >= nextLevelExp) { // player has reached max level @@ -2387,8 +2386,8 @@ void Player::addExperience(const std::shared_ptr &target, uint64_t exp } // Hazard system experience - std::shared_ptr monster = target && target->getMonster() ? target->getMonster() : nullptr; - bool handleHazardExperience = monster && monster->getHazard() && getHazardSystemPoints() > 0; + const auto &monster = target && target->getMonster() ? target->getMonster() : nullptr; + const bool handleHazardExperience = monster && monster->getHazard() && getHazardSystemPoints() > 0; if (handleHazardExperience) { exp += (exp * (1.75 * getHazardSystemPoints() * g_configManager().getFloat(HAZARD_EXP_BONUS_MULTIPLIER, __FUNCTION__))) / 100.; } @@ -2415,7 +2414,7 @@ void Player::addExperience(const std::shared_ptr &target, uint64_t exp if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " gained " + expString; - for (const std::shared_ptr &spectator : spectators) { + for (const auto &spectator : spectators) { spectator->getPlayer()->sendTextMessage(message); } } @@ -2441,7 +2440,7 @@ void Player::addExperience(const std::shared_ptr &target, uint64_t exp } currLevelExp = nextLevelExp; - nextLevelExp = Player::getExpForLevel(level + 1); + nextLevelExp = getExpForLevel(level + 1); if (currLevelExp >= nextLevelExp) { // player has reached max level break; @@ -2509,7 +2508,7 @@ void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " lost " + expString; - for (const std::shared_ptr &spectator : spectators) { + for (const auto &spectator : spectators) { spectator->getPlayer()->sendTextMessage(message); } } @@ -2590,7 +2589,7 @@ void Player::onTakeDamage(std::shared_ptr attacker, int32_t damage) { // nothing here yet } -void Player::onAttackedCreatureBlockHit(BlockType_t blockType) { +void Player::onAttackedCreatureBlockHit(const BlockType_t &blockType) { lastAttackBlockType = blockType; switch (blockType) { @@ -2649,7 +2648,7 @@ BlockType_t Player::blockHit(const std::shared_ptr &attacker, const Co continue; } - const auto item = inventory[slot]; + const auto &item = inventory[slot]; if (!item) { continue; } @@ -2657,7 +2656,7 @@ BlockType_t Player::blockHit(const std::shared_ptr &attacker, const Co const ItemType &it = Item::items[item->getID()]; if (it.abilities) { const int16_t &absorbPercent = it.abilities->absorbPercent[combatTypeToIndex(combatType)]; - auto charges = item->getAttribute(ItemAttribute_t::CHARGES); + const auto charges = item->getAttribute(ItemAttribute_t::CHARGES); if (absorbPercent != 0) { damage -= std::round(damage * (absorbPercent / 100.)); if (charges != 0) { @@ -2717,15 +2716,15 @@ void Player::death(std::shared_ptr lastHitCreature) { int othersDmg = 0; uint32_t sumLevels = 0; uint32_t inFightTicks = 5 * 60 * 1000; - for (const auto &it : damageMap) { - CountBlock_t cb = it.second; - if ((OTSYS_TIME() - cb.ticks) <= inFightTicks) { - std::shared_ptr damageDealer = g_game().getPlayerByID(it.first); + for (const auto &[fst, snd] : damageMap) { + auto [total, ticks] = snd; + if ((OTSYS_TIME() - ticks) <= inFightTicks) { + std::shared_ptr damageDealer = g_game().getPlayerByID(fst); if (damageDealer) { - playerDmg += cb.total; + playerDmg += total; sumLevels += damageDealer->getLevel(); } else { - othersDmg += cb.total; + othersDmg += total; } } } @@ -2892,7 +2891,7 @@ void Player::death(std::shared_ptr lastHitCreature) { auto it = conditions.begin(), end = conditions.end(); while (it != end) { - std::shared_ptr condition = *it; + const auto &condition = *it; // isSupress block to delete spells conditions (ensures that the player cannot, for example, reset the cooldown time of the familiar and summon several) if (condition->isPersistent() && condition->isRemovableOnDeath()) { it = conditions.erase(it); @@ -2908,7 +2907,7 @@ void Player::death(std::shared_ptr lastHitCreature) { auto it = conditions.begin(), end = conditions.end(); while (it != end) { - std::shared_ptr condition = *it; + const auto &condition = *it; if (condition->isPersistent()) { it = conditions.erase(it); @@ -2940,7 +2939,7 @@ bool Player::spawn() { return false; } - auto spectators = Spectators().find(position, true); + const auto &spectators = Spectators().find(position, true); for (const auto &spectator : spectators) { if (const auto &tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendCreatureAppear(static_self_cast(), pos, true); @@ -2972,14 +2971,14 @@ void Player::despawn() { Game::removeCreatureCheck(static_self_cast()); // remove from map - std::shared_ptr tile = getTile(); + const auto &tile = getTile(); if (!tile) { return; } std::vector oldStackPosVector; - auto spectators = Spectators().find(tile->getPosition(), true); + const auto &spectators = Spectators().find(tile->getPosition(), true); size_t i = 0; for (const auto &spectator : spectators) { if (const auto &player = spectator->getPlayer()) { @@ -3006,7 +3005,7 @@ void Player::despawn() { setDead(true); } -bool Player::dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { +bool Player::dropCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) { if (getZoneType() != ZONE_PVP || !Player::lastHitIsPlayer(lastHitCreature)) { return Creature::dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } @@ -3016,7 +3015,7 @@ bool Player::dropCorpse(std::shared_ptr lastHitCreature, std::shared_p } std::shared_ptr Player::getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) { - std::shared_ptr corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); + const auto &corpse = Creature::getCorpse(lastHitCreature, mostDamageCreature); if (corpse && corpse->getContainer()) { std::ostringstream ss; if (lastHitCreature) { @@ -3046,7 +3045,7 @@ void Player::addInFightTicks(bool pzlock /*= false*/) { updateImbuementTrackerStats(); - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(PZ_LOCKED, __FUNCTION__), 0); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(PZ_LOCKED, __FUNCTION__), 0); addCondition(condition); } @@ -3078,11 +3077,11 @@ void Player::removePlayer(bool displayEffect, bool forced /*= true*/) { // close container and its child containers void Player::autoCloseContainers(const std::shared_ptr &container) { std::vector closeList; - for (const auto &it : openContainers) { - std::shared_ptr tmpContainer = it.second.container; + for (const auto &[fst, snd] : openContainers) { + auto tmpContainer = snd.container; while (tmpContainer) { if (tmpContainer->isRemoved() || tmpContainer == container) { - closeList.push_back(it.first); + closeList.push_back(fst); break; } @@ -3090,7 +3089,7 @@ void Player::autoCloseContainers(const std::shared_ptr &container) { } } - for (uint32_t containerId : closeList) { + for (const uint32_t containerId : closeList) { closeContainer(containerId); if (client) { client->sendCloseContainer(containerId); @@ -3115,7 +3114,7 @@ bool Player::hasCapacity(const std::shared_ptr &item, uint32_t count) cons } ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { g_logger().error("[Player::queryAdd] - Item is nullptr"); return RETURNVALUE_NOTPOSSIBLE; @@ -3124,10 +3123,10 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, return RETURNVALUE_ITEMISNOTYOURS; } - bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); + const bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { // a child container is querying the player, just check if enough capacity - bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); + const bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); if (skipLimit || hasCapacity(item, count)) { return RETURNVALUE_NOERROR; } @@ -3142,7 +3141,7 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, const int32_t &slotPosition = item->getSlotPosition(); - bool allowPutItemsOnAmmoSlot = g_configManager().getBoolean(ENABLE_PLAYER_PUT_ITEM_IN_AMMO_SLOT, __FUNCTION__); + const bool allowPutItemsOnAmmoSlot = g_configManager().getBoolean(ENABLE_PLAYER_PUT_ITEM_IN_AMMO_SLOT, __FUNCTION__); if (allowPutItemsOnAmmoSlot && index == CONST_SLOT_AMMO) { ret = RETURNVALUE_NOERROR; } else { @@ -3189,7 +3188,7 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, if (item->getWeaponType() != WEAPON_SHIELD && !item->isQuiver()) { ret = RETURNVALUE_CANNOTBEDRESSED; } else { - std::shared_ptr leftItem = inventory[CONST_SLOT_LEFT]; + const auto &leftItem = inventory[CONST_SLOT_LEFT]; if (leftItem) { if ((leftItem->getSlotPosition() | slotPosition) & SLOTP_TWO_HAND) { if (item->isQuiver() && leftItem->getWeaponType() == WEAPON_DISTANCE) { @@ -3207,8 +3206,9 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, } else if (slotPosition & SLOTP_TWO_HAND) { ret = RETURNVALUE_CANNOTBEDRESSED; } else if (inventory[CONST_SLOT_LEFT]) { - std::shared_ptr leftItem = inventory[CONST_SLOT_LEFT]; - WeaponType_t type = item->getWeaponType(), leftType = leftItem->getWeaponType(); + const auto &leftItem = inventory[CONST_SLOT_LEFT]; + const WeaponType_t type = item->getWeaponType(); + const WeaponType_t leftType = leftItem->getWeaponType(); if (leftItem->getSlotPosition() & SLOTP_TWO_HAND) { ret = RETURNVALUE_DROPTWOHANDEDITEM; @@ -3232,7 +3232,7 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, ret = RETURNVALUE_CANNOTBEDRESSED; } else if (slotPosition & SLOTP_TWO_HAND) { if (inventory[CONST_SLOT_RIGHT]) { - WeaponType_t type = item->getWeaponType(); + const WeaponType_t type = item->getWeaponType(); // Allow equip bow when quiver is in SLOT_RIGHT if (type == WEAPON_DISTANCE && inventory[CONST_SLOT_RIGHT]->isQuiver()) { ret = RETURNVALUE_NOERROR; @@ -3243,15 +3243,16 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, ret = RETURNVALUE_NOERROR; } } else if (slotPosition & SLOTP_LEFT) { - WeaponType_t type = item->getWeaponType(); + const WeaponType_t type = item->getWeaponType(); if (type == WEAPON_NONE || type == WEAPON_SHIELD || type == WEAPON_AMMO) { ret = RETURNVALUE_CANNOTBEDRESSED; } else { ret = RETURNVALUE_NOERROR; } } else if (inventory[CONST_SLOT_RIGHT]) { - std::shared_ptr rightItem = inventory[CONST_SLOT_RIGHT]; - WeaponType_t type = item->getWeaponType(), rightType = rightItem->getWeaponType(); + const auto &rightItem = inventory[CONST_SLOT_RIGHT]; + const WeaponType_t type = item->getWeaponType(); + const WeaponType_t rightType = rightItem->getWeaponType(); if (rightItem->getSlotPosition() & SLOTP_TWO_HAND) { ret = RETURNVALUE_DROPTWOHANDEDITEM; @@ -3314,7 +3315,7 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, if (ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_NOTENOUGHROOM) { // need an exchange with source? - std::shared_ptr inventoryItem = getInventoryItem(static_cast(index)); + const auto &inventoryItem = getInventoryItem(static_cast(index)); if (inventoryItem && (!inventoryItem->isStackable() || inventoryItem->getID() != item->getID())) { return RETURNVALUE_NEEDEXCHANGE; } @@ -3333,7 +3334,7 @@ ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr &thing, } ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) { - auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { maxQueryCount = 0; return RETURNVALUE_NOTPOSSIBLE; @@ -3342,16 +3343,16 @@ ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr &t if (index == INDEX_WHEREEVER) { uint32_t n = 0; for (int32_t slotIndex = CONST_SLOT_FIRST; slotIndex <= CONST_SLOT_LAST; ++slotIndex) { - std::shared_ptr inventoryItem = inventory[slotIndex]; + const auto &inventoryItem = inventory[slotIndex]; if (inventoryItem) { - if (std::shared_ptr subContainer = inventoryItem->getContainer()) { + if (const auto &subContainer = inventoryItem->getContainer()) { uint32_t queryCount = 0; subContainer->queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags); n += queryCount; // iterate through all items, including sub-containers (deep search) for (ContainerIterator it = subContainer->iterator(); it.hasNext(); it.advance()) { - if (std::shared_ptr tmpContainer = (*it)->getContainer()) { + if (const auto &tmpContainer = (*it)->getContainer()) { queryCount = 0; tmpContainer->queryMaxCount(INDEX_WHEREEVER, item, item->getItemCount(), queryCount, flags); n += queryCount; @@ -3377,7 +3378,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr &t } else { std::shared_ptr destItem = nullptr; - std::shared_ptr destThing = getThing(index); + const auto &destThing = getThing(index); if (destThing) { destItem = destThing->getItem(); } @@ -3401,9 +3402,8 @@ ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr &t if (maxQueryCount < count) { return RETURNVALUE_NOTENOUGHROOM; - } else { - return RETURNVALUE_NOERROR; } + return RETURNVALUE_NOERROR; } ReturnValue Player::queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr /*= nullptr*/) { @@ -3412,7 +3412,7 @@ ReturnValue Player::queryRemove(const std::shared_ptr &thing, uint32_t co return RETURNVALUE_NOTPOSSIBLE; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -3432,18 +3432,18 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh if (index == 0 /*drop to capacity window*/ || index == INDEX_WHEREEVER) { *destItem = nullptr; - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return getPlayer(); } - bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK); - bool isStackable = item->isStackable(); + const bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK); + const bool isStackable = item->isStackable(); std::vector> containers; for (uint32_t slotIndex = CONST_SLOT_FIRST; slotIndex <= CONST_SLOT_AMMO; ++slotIndex) { - std::shared_ptr inventoryItem = inventory[slotIndex]; + const auto &inventoryItem = inventory[slotIndex]; if (inventoryItem) { if (inventoryItem == tradeItem) { continue; @@ -3463,11 +3463,11 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh } } - if (std::shared_ptr subContainer = inventoryItem->getContainer()) { - containers.push_back(subContainer); + if (const auto &subContainer = inventoryItem->getContainer()) { + containers.emplace_back(subContainer); } - } else if (std::shared_ptr subContainer = inventoryItem->getContainer()) { - containers.push_back(subContainer); + } else if (const auto &subContainer = inventoryItem->getContainer()) { + containers.emplace_back(subContainer); } } else if (queryAdd(slotIndex, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { // empty slot index = slotIndex; @@ -3478,7 +3478,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh size_t i = 0; while (i < containers.size()) { - std::shared_ptr tmpContainer = containers[i++]; + const auto &tmpContainer = containers[i++]; if (!autoStack || !isStackable) { // we need to find first empty container as fast as we can for non-stackable items uint32_t n = tmpContainer->capacity() - tmpContainer->size(); @@ -3492,9 +3492,9 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh n--; } - for (const std::shared_ptr &tmpContainerItem : tmpContainer->getItemList()) { - if (std::shared_ptr subContainer = tmpContainerItem->getContainer()) { - containers.push_back(subContainer); + for (const auto &tmpContainerItem : tmpContainer->getItemList()) { + if (const auto &subContainer = tmpContainerItem->getContainer()) { + containers.emplace_back(subContainer); } } @@ -3503,7 +3503,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh uint32_t n = 0; - for (const std::shared_ptr &tmpItem : tmpContainer->getItemList()) { + for (const auto &tmpItem : tmpContainer->getItemList()) { if (tmpItem == tradeItem) { continue; } @@ -3519,8 +3519,8 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh return tmpContainer; } - if (std::shared_ptr subContainer = tmpItem->getContainer()) { - containers.push_back(subContainer); + if (const auto &subContainer = tmpItem->getContainer()) { + containers.emplace_back(subContainer); } n++; @@ -3536,29 +3536,28 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh return getPlayer(); } - std::shared_ptr destThing = getThing(index); + const auto &destThing = getThing(index); if (destThing) { *destItem = destThing->getItem(); } - const auto item = thing->getItem(); - bool movingAmmoToQuiver = item && *destItem && (*destItem)->isQuiver() && item->isAmmo(); + const auto &item = thing->getItem(); + const bool movingAmmoToQuiver = item && *destItem && (*destItem)->isQuiver() && item->isAmmo(); // force shield any slot right to player cylinder if (index == CONST_SLOT_RIGHT && !movingAmmoToQuiver) { return getPlayer(); } - std::shared_ptr subCylinder = std::dynamic_pointer_cast(destThing); + const auto &subCylinder = std::dynamic_pointer_cast(destThing); if (subCylinder) { index = INDEX_WHEREEVER; *destItem = nullptr; return subCylinder; - } else { - return getPlayer(); } + return getPlayer(); } -void Player::addThing(int32_t index, std::shared_ptr thing) { +void Player::addThing(int32_t index, const std::shared_ptr thing) { if (!thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3567,7 +3566,7 @@ void Player::addThing(int32_t index, std::shared_ptr thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3579,13 +3578,13 @@ void Player::addThing(int32_t index, std::shared_ptr thing) { sendInventoryItem(static_cast(index), item); } -void Player::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) { +void Player::updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3600,17 +3599,17 @@ void Player::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t onUpdateInventoryItem(item, item); } -void Player::replaceThing(uint32_t index, std::shared_ptr thing) { +void Player::replaceThing(uint32_t index, const std::shared_ptr &thing) { if (index > CONST_SLOT_LAST) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr oldItem = getInventoryItem(static_cast(index)); + const auto &oldItem = getInventoryItem(static_cast(index)); if (!oldItem) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3626,8 +3625,8 @@ void Player::replaceThing(uint32_t index, std::shared_ptr thing) { inventory[index] = item; } -void Player::removeThing(std::shared_ptr thing, uint32_t count) { - const auto item = thing->getItem(); +void Player::removeThing(const std::shared_ptr &thing, uint32_t count) { + const auto &item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3669,7 +3668,7 @@ void Player::removeThing(std::shared_ptr thing, uint32_t count) { } } -int32_t Player::getThingIndex(std::shared_ptr thing) const { +int32_t Player::getThingIndex(const std::shared_ptr &thing) const { for (uint8_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { if (inventory[i] == thing) { return i; @@ -3689,7 +3688,7 @@ size_t Player::getLastIndex() const { uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const { uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } @@ -3698,7 +3697,7 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con count += Item::countByType(item, subType); } - if (std::shared_ptr container = item->getContainer()) { + if (const auto &container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if ((*it)->getID() == itemId) { count += Item::countByType(*it, subType); @@ -3711,15 +3710,15 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con void Player::stashContainer(const StashContainerList &itemDict) { StashItemList stashItemDict; // ItemID - Count - for (const auto &it_dict : itemDict) { - stashItemDict[(it_dict.first)->getID()] = it_dict.second; + for (const auto &[fst, snd] : itemDict) { + stashItemDict[(fst)->getID()] = snd; } - for (auto it : stashItems) { - if (!stashItemDict[it.first]) { - stashItemDict[it.first] = it.second; + for (const auto &[fst, snd] : stashItems) { + if (!stashItemDict[fst]) { + stashItemDict[fst] = snd; } else { - stashItemDict[it.first] += it.second; + stashItemDict[fst] += snd; } } @@ -3731,11 +3730,11 @@ void Player::stashContainer(const StashContainerList &itemDict) { uint32_t totalStowed = 0; std::ostringstream retString; uint16_t refreshDepotSearchOnItem = 0; - for (const auto &stashIterator : itemDict) { - uint16_t iteratorCID = (stashIterator.first)->getID(); - if (g_game().internalRemoveItem(stashIterator.first, stashIterator.second) == RETURNVALUE_NOERROR) { - addItemOnStash(iteratorCID, stashIterator.second); - totalStowed += stashIterator.second; + for (const auto &[fst, snd] : itemDict) { + const uint16_t iteratorCID = (fst)->getID(); + if (g_game().internalRemoveItem(fst, snd) == RETURNVALUE_NOERROR) { + addItemOnStash(iteratorCID, snd); + totalStowed += snd; if (isDepotSearchOpenOnItem(iteratorCID)) { refreshDepotSearchOnItem = iteratorCID; } @@ -3760,7 +3759,7 @@ void Player::stashContainer(const StashContainerList &itemDict) { } } -bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped /* = false*/) { +bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool ignoreEquipped /* = false*/) const { if (amount == 0) { return true; } @@ -3769,37 +3768,37 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, uint32_t count = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } if (!ignoreEquipped && item->getID() == itemId) { - uint32_t itemCount = Item::countByType(item, subType); + const uint32_t itemCount = Item::countByType(item, subType); if (itemCount == 0) { continue; } - itemList.push_back(item); + itemList.emplace_back(item); count += itemCount; if (count >= amount) { g_game().internalRemoveItems(itemList, amount, Item::items[itemId].stackable); return true; } - } else if (std::shared_ptr container = item->getContainer()) { + } else if (const auto &container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr containerItem = *it; + const auto &containerItem = *it; if (containerItem->getID() == itemId) { - uint32_t itemCount = Item::countByType(containerItem, subType); + const uint32_t itemCount = Item::countByType(containerItem, subType); if (itemCount == 0) { continue; } - itemList.push_back(containerItem); + itemList.emplace_back(containerItem); count += itemCount; - auto stackable = Item::items[itemId].stackable; + const auto stackable = Item::items[itemId].stackable; // If the amount of items in the backpack is equal to or greater than the amount // It will remove items and stop the iteration if (count >= amount) { @@ -3827,7 +3826,7 @@ bool Player::hasItemCountById(uint16_t itemId, uint32_t itemAmount, bool checkSt // Check items from stash for (StashItemList stashToSend = getStashItems(); - auto [stashItemId, itemCount] : stashToSend) { + const auto &[stashItemId, itemCount] : stashToSend) { if (!checkStash) { break; } @@ -3875,7 +3874,7 @@ bool Player::removeItemCountById(uint16_t itemId, uint32_t itemAmount, bool remo ItemsTierCountList Player::getInventoryItemsId(bool ignoreStoreInbox /* false */) const { ItemsTierCountList itemMap; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } @@ -3900,20 +3899,20 @@ ItemsTierCountList Player::getInventoryItemsId(bool ignoreStoreInbox /* false */ std::vector> Player::getInventoryItemsFromId(uint16_t itemId, bool ignore /*= true*/) const { std::vector> itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } if (!ignore && item->getID() == itemId) { - itemVector.push_back(item); + itemVector.emplace_back(item); } - if (std::shared_ptr container = item->getContainer()) { + if (const auto &container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - auto containerItem = *it; + const auto &containerItem = *it; if (containerItem->getID() == itemId) { - itemVector.push_back(containerItem); + itemVector.emplace_back(containerItem); } } } @@ -3991,7 +3990,7 @@ ItemsTierCountList Player::getStoreInboxItemsId() const { const auto &container = getStoreInbox(); if (container) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - const auto item = *it; + const auto &item = *it; (itemMap[item->getID()])[item->getTier()] += Item::countByType(item, -1); } } @@ -4003,9 +4002,9 @@ ItemsTierCountList Player::getDepotChestItemsId() const { ItemsTierCountList itemMap; for (const auto &[index, depot] : depotChests) { - const std::shared_ptr &container = depot->getContainer(); + const auto &container = depot->getContainer(); for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - const auto item = *it; + const auto &item = *it; (itemMap[item->getID()])[item->getTier()] += Item::countByType(item, -1); } } @@ -4031,22 +4030,22 @@ ItemsTierCountList Player::getDepotInboxItemsId() const { std::vector> Player::getAllInventoryItems(bool ignoreEquiped /*= false*/, bool ignoreItemWithTier /* false*/) const { std::vector> itemVector; for (int i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } // Only get equiped items if ignored equipped is false if (!ignoreEquiped) { - itemVector.push_back(item); + itemVector.emplace_back(item); } - if (std::shared_ptr container = item->getContainer()) { + if (const auto &container = item->getContainer()) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if (ignoreItemWithTier && (*it)->getTier() > 0) { continue; } - itemVector.push_back(*it); + itemVector.emplace_back(*it); } } } @@ -4056,10 +4055,10 @@ std::vector> Player::getAllInventoryItems(bool ignoreEquip std::vector> Player::getEquippedAugmentItemsByType(Augment_t augmentType) const { std::vector> equippedAugmentItemsByType; - const auto equippedAugmentItems = getEquippedItems(); + const auto &equippedAugmentItems = getEquippedItems(); for (const auto &item : equippedAugmentItems) { - for (auto &augment : item->getAugments()) { + for (const auto &augment : item->getAugments()) { if (augment->type == augmentType) { equippedAugmentItemsByType.push_back(item); } @@ -4071,20 +4070,20 @@ std::vector> Player::getEquippedAugmentItemsByType(Augment std::vector> Player::getEquippedAugmentItems() const { std::vector> equippedAugmentItems; - const auto equippedItems = getEquippedItems(); + const auto &equippedItems = getEquippedItems(); for (const auto &item : equippedItems) { if (item->getAugments().empty()) { continue; } - equippedAugmentItems.push_back(item); + equippedAugmentItems.emplace_back(item); } return equippedAugmentItems; } std::vector> Player::getEquippedItems() const { - std::vector valid_slots { + static const std::vector valid_slots { CONST_SLOT_HEAD, CONST_SLOT_NECKLACE, CONST_SLOT_BACKPACK, @@ -4098,12 +4097,12 @@ std::vector> Player::getEquippedItems() const { std::vector> valid_items; for (const auto &slot : valid_slots) { - const auto item = inventory[slot]; + const auto &item = inventory[slot]; if (!item) { continue; } - valid_items.push_back(item); + valid_items.emplace_back(item); } return valid_items; @@ -4136,7 +4135,7 @@ void Player::getAllItemTypeCountAndSubtype(std::map &countMa } std::shared_ptr Player::getForgeItemFromId(uint16_t itemId, uint8_t tier) const { - for (auto item : getAllInventoryItems(true)) { + for (const auto &item : getAllInventoryItems(true)) { if (item->hasImbuements()) { continue; } @@ -4156,7 +4155,7 @@ std::shared_ptr Player::getThing(size_t index) const { return nullptr; } -void Player::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { +void Player::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, const CylinderLink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { // calling movement scripts g_moveEvents().onPlayerEquip(getPlayer(), thing->getItem(), static_cast(index), false); @@ -4164,7 +4163,7 @@ void Player::postAddNotification(std::shared_ptr thing, std::shared_ptr i = (oldParent ? oldParent->getItem() : nullptr); + const auto &i = (oldParent ? oldParent->getItem() : nullptr); const auto &container = i ? i->getContainer() : nullptr; if (container) { requireListUpdate = container->getHoldingPlayer() != getPlayer(); @@ -4179,20 +4178,20 @@ void Player::postAddNotification(std::shared_ptr thing, std::shared_ptrgetItem()) { - if (std::shared_ptr container = item->getContainer()) { + if (const auto &container = item->getContainer()) { onSendContainer(container); } if (shopOwner && !scheduledSaleUpdate && requireListUpdate) { updateSaleShopList(item); } - } else if (std::shared_ptr creature = thing->getCreature()) { + } else if (const auto &creature = thing->getCreature()) { if (creature == getPlayer()) { // check containers std::vector> containers; - for (const auto &it : openContainers) { - std::shared_ptr container = it.second.container; + for (const auto &[fst, snd] : openContainers) { + const auto &container = snd.container; if (container == nullptr) { continue; } @@ -4202,14 +4201,14 @@ void Player::postAddNotification(std::shared_ptr thing, std::shared_ptr &container : containers) { + for (const auto &container : containers) { autoCloseContainers(container); } } } } -void Player::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { +void Player::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { if (link == LINK_OWNER) { // calling movement scripts g_moveEvents().onPlayerDeEquip(getPlayer(), thing->getItem(), static_cast(index)); @@ -4218,7 +4217,7 @@ void Player::postRemoveNotification(std::shared_ptr thing, std::shared_pt bool requireListUpdate = true; if (link == LINK_OWNER || link == LINK_TOPPARENT) { - std::shared_ptr i = (newParent ? newParent->getItem() : nullptr); + const auto &i = (newParent ? newParent->getItem() : nullptr); const auto &container = i ? i->getContainer() : nullptr; if (container) { requireListUpdate = container->getHoldingPlayer() != getPlayer(); @@ -4232,22 +4231,22 @@ void Player::postRemoveNotification(std::shared_ptr thing, std::shared_pt sendStats(); } - if (const auto item = thing->getItem()) { - if (std::shared_ptr container = item->getContainer()) { + if (const auto &item = thing->getItem()) { + if (const auto &container = item->getContainer()) { checkLootContainers(container); if (container->isRemoved() || !Position::areInRange<1, 1, 0>(getPosition(), container->getPosition())) { autoCloseContainers(container); } else if (container->getTopParent() == getPlayer()) { onSendContainer(container); - } else if (std::shared_ptr topContainer = std::dynamic_pointer_cast(container->getTopParent())) { - if (std::shared_ptr depotChest = std::dynamic_pointer_cast(topContainer)) { + } else if (const auto &topContainer = std::dynamic_pointer_cast(container->getTopParent())) { + if (const auto &depotChest = std::dynamic_pointer_cast(topContainer)) { bool isOwner = false; - for (const auto &it : depotChests) { - if (it.second == depotChest) { + for (const auto &[fst, snd] : depotChests) { + if (snd == depotChest) { isOwner = true; - it.second->stopDecaying(); + snd->stopDecaying(); onSendContainer(container); } } @@ -4276,7 +4275,7 @@ void Player::postRemoveNotification(std::shared_ptr thing, std::shared_pt // i will keep this function so it can be reviewed bool Player::updateSaleShopList(const std::shared_ptr &item) { - uint16_t itemId = item->getID(); + const uint16_t itemId = item->getID(); if (!itemId || !item) { return true; } @@ -4293,21 +4292,21 @@ bool Player::hasShopItemForSale(uint16_t itemId, uint8_t subType) const { const ItemType &itemType = Item::items[itemId]; const auto &shoplist = shopOwner->getShopItemVector(getGUID()); - return std::any_of(shoplist.begin(), shoplist.end(), [&](const ShopBlock &shopBlock) { + return std::ranges::any_of(shoplist, [&](const ShopBlock &shopBlock) { return shopBlock.itemId == itemId && shopBlock.itemBuyPrice != 0 && (!itemType.isFluidContainer() || shopBlock.itemSubType == subType); }); } -void Player::internalAddThing(std::shared_ptr thing) { +void Player::internalAddThing(const std::shared_ptr &thing) { internalAddThing(0, thing); } -void Player::internalAddThing(uint32_t index, std::shared_ptr thing) { +void Player::internalAddThing(uint32_t index, const std::shared_ptr &thing) { if (!thing) { return; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return; } @@ -4323,7 +4322,7 @@ void Player::internalAddThing(uint32_t index, std::shared_ptr thing) { } } -bool Player::setFollowCreature(std::shared_ptr creature) { +bool Player::setFollowCreature(const std::shared_ptr &creature) { if (!Creature::setFollowCreature(creature)) { setFollowCreature(nullptr); setAttackedCreature(nullptr); @@ -4336,13 +4335,13 @@ bool Player::setFollowCreature(std::shared_ptr creature) { return true; } -bool Player::setAttackedCreature(std::shared_ptr creature) { +bool Player::setAttackedCreature(const std::shared_ptr &creature) { if (!Creature::setAttackedCreature(creature)) { sendCancelTarget(); return false; } - auto followCreature = getFollowCreature(); + const auto &followCreature = getFollowCreature(); if (chaseMode && creature) { if (followCreature != creature) { setFollowCreature(creature); @@ -4385,7 +4384,7 @@ void Player::doAttacking(uint32_t) { return; } - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature) { return; } @@ -4393,8 +4392,8 @@ void Player::doAttacking(uint32_t) { if ((OTSYS_TIME() - lastAttack) >= getAttackSpeed()) { bool result = false; - std::shared_ptr tool = getWeapon(); - const WeaponShared_ptr weapon = g_weapons().getWeapon(tool); + const auto &tool = getWeapon(); + const auto &weapon = g_weapons().getWeapon(tool); uint32_t delay = getAttackSpeed(); bool classicSpeed = g_configManager().getBoolean(CLASSIC_ATTACK_SPEED, __FUNCTION__); @@ -4430,9 +4429,9 @@ void Player::doAttacking(uint32_t) { } } -uint64_t Player::getGainedExperience(std::shared_ptr attacker) const { +uint64_t Player::getGainedExperience(const std::shared_ptr &attacker) const { if (g_configManager().getBoolean(EXPERIENCE_FROM_PLAYERS, __FUNCTION__)) { - auto attackerPlayer = attacker->getPlayer(); + const auto &attackerPlayer = attacker->getPlayer(); if (attackerPlayer && attackerPlayer.get() != this && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_configManager().getNumber(EXP_FROM_PLAYERS_LEVEL_RANGE, __FUNCTION__)) { return std::max(0, std::floor(getLostExperience() * getDamageRatio(attacker) * 0.75)); } @@ -4449,8 +4448,8 @@ void Player::onFollowCreature(const std::shared_ptr &creature) { void Player::setChaseMode(bool mode) { bool prevChaseMode = chaseMode; chaseMode = mode; - auto attackedCreature = getAttackedCreature(); - auto followCreature = getFollowCreature(); + const auto &attackedCreature = getAttackedCreature(); + const auto &followCreature = getFollowCreature(); if (prevChaseMode != chaseMode) { if (chaseMode) { @@ -4479,7 +4478,7 @@ void Player::onWalkComplete() { */ g_logger().debug("[Player::onWalkComplete] Executing feared conditions as players completed it's walk."); - std::shared_ptr f = getCondition(CONDITION_FEARED); + const auto &f = getCondition(CONDITION_FEARED); f->executeCondition(static_self_cast(), 0); } @@ -4504,9 +4503,9 @@ void Player::updateItemsLight(bool internal /*=false*/) { LightInfo maxLight; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (item) { - LightInfo curLight = item->getLightInfo(); + const auto &curLight = item->getLightInfo(); if (curLight.level > maxLight.level) { maxLight = curLight; @@ -4612,12 +4611,12 @@ void Player::onEndCondition(const ConditionType_t &type) { sendIcons(); } -void Player::onCombatRemoveCondition(std::shared_ptr condition) { +void Player::onCombatRemoveCondition(const std::shared_ptr &condition) { // Creature::onCombatRemoveCondition(condition); if (condition->getId() > 0) { // Means the condition is from an item, id == slot if (g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { - const auto item = getInventoryItem(static_cast(condition->getId())); + const auto &item = getInventoryItem(static_cast(condition->getId())); if (item) { // 25% chance to destroy the item if (25 >= uniform_random(1, 100)) { @@ -4640,7 +4639,7 @@ void Player::onCombatRemoveCondition(std::shared_ptr condition) { } } -void Player::onAttackedCreature(std::shared_ptr target) { +void Player::onAttackedCreature(const std::shared_ptr &target) { Creature::onAttackedCreature(target); if (target->getZoneType() == ZONE_PVP) { @@ -4656,7 +4655,7 @@ void Player::onAttackedCreature(std::shared_ptr target) { return; } - auto targetPlayer = target->getPlayer(); + const auto &targetPlayer = target->getPlayer(); if (targetPlayer && !isPartner(targetPlayer) && !isGuildMate(targetPlayer)) { if (!pzLocked && g_game().getWorldType() == WORLD_TYPE_PVP_ENFORCED) { pzLocked = true; @@ -4714,12 +4713,12 @@ void Player::onPlacedCreature() { sendUnjustifiedPoints(); } -void Player::onAttackedCreatureDrainHealth(std::shared_ptr target, int32_t points) { +void Player::onAttackedCreatureDrainHealth(const std::shared_ptr &target, int32_t points) { Creature::onAttackedCreatureDrainHealth(target, points); if (target) { if (m_party && !Combat::isPlayerCombat(target)) { - auto tmpMonster = target->getMonster(); + const auto &tmpMonster = target->getMonster(); if (tmpMonster && tmpMonster->isHostile()) { // We have fulfilled a requirement for shared experience m_party->updatePlayerTicks(static_self_cast(), points); @@ -4728,14 +4727,14 @@ void Player::onAttackedCreatureDrainHealth(std::shared_ptr target, int } } -void Player::onTargetCreatureGainHealth(std::shared_ptr target, int32_t points) { +void Player::onTargetCreatureGainHealth(const std::shared_ptr &target, int32_t points) { if (target && m_party) { std::shared_ptr tmpPlayer = nullptr; if (isPartner(tmpPlayer) && (tmpPlayer != getPlayer())) { tmpPlayer = target->getPlayer(); - } else if (std::shared_ptr targetMaster = target->getMaster()) { - if (std::shared_ptr targetMasterPlayer = targetMaster->getPlayer()) { + } else if (const auto &targetMaster = target->getMaster()) { + if (const auto &targetMasterPlayer = targetMaster->getPlayer()) { tmpPlayer = targetMasterPlayer; } } @@ -4768,7 +4767,7 @@ bool Player::onKilledPlayer(const std::shared_ptr &target, bool lastHit) if (lastHit && hasCondition(CONDITION_INFIGHT)) { pzLocked = true; - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(WHITE_SKULL_TIME, __FUNCTION__), 0); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(WHITE_SKULL_TIME, __FUNCTION__), 0); addCondition(condition); } } @@ -4822,7 +4821,7 @@ bool Player::onKilledMonster(const std::shared_ptr &monster) { if (monster->hasBeenSummoned()) { return false; } - auto mType = monster->getMonsterType(); + const auto &mType = monster->getMonsterType(); addHuntingTaskKill(mType); addBestiaryKill(mType); addBosstiaryKill(mType); @@ -4837,7 +4836,7 @@ void Player::gainExperience(uint64_t gainExp, const std::shared_ptr &t addExperience(target, gainExp, true); } -void Player::onGainExperience(uint64_t gainExp, std::shared_ptr target) { +void Player::onGainExperience(uint64_t gainExp, const std::shared_ptr &target) { if (hasFlag(PlayerFlags_t::NotGainExperience)) { return; } @@ -4884,7 +4883,7 @@ bool Player::lastHitIsPlayer(const std::shared_ptr &lastHitCreature) { return true; } - std::shared_ptr lastHitMaster = lastHitCreature->getMaster(); + const auto &lastHitMaster = lastHitCreature->getMaster(); return lastHitMaster && lastHitMaster->getPlayer(); } @@ -4934,7 +4933,7 @@ bool Player::canWear(uint16_t lookType, uint8_t addons) const { return true; } - for (const OutfitEntry &outfitEntry : outfits) { + for (const auto &outfitEntry : outfits) { if (outfitEntry.lookType != lookType) { continue; } @@ -4948,7 +4947,7 @@ bool Player::canLogout() { return false; } - auto tile = getTile(); + const auto &tile = getTile(); if (!tile) { return false; } @@ -4967,18 +4966,18 @@ bool Player::canLogout() { void Player::genReservedStorageRange() { // generate outfits range uint32_t outfits_key = PSTRG_OUTFITS_RANGE_START; - for (const OutfitEntry &entry : outfits) { + for (const auto &entry : outfits) { storageMap[++outfits_key] = (entry.lookType << 16) | entry.addons; } // generate familiars range uint32_t familiar_key = PSTRG_FAMILIARS_RANGE_START; - for (const FamiliarEntry &entry : familiars) { + for (const auto &entry : familiars) { storageMap[++familiar_key] = (entry.lookType << 16); } } void Player::addOutfit(uint16_t lookType, uint8_t addons) { - for (OutfitEntry &outfitEntry : outfits) { + for (auto &outfitEntry : outfits) { if (outfitEntry.lookType == lookType) { outfitEntry.addons |= addons; return; @@ -4989,7 +4988,7 @@ void Player::addOutfit(uint16_t lookType, uint8_t addons) { bool Player::removeOutfit(uint16_t lookType) { for (auto it = outfits.begin(), end = outfits.end(); it != end; ++it) { - OutfitEntry &entry = *it; + const auto &entry = *it; if (entry.lookType == lookType) { outfits.erase(it); return true; @@ -5053,32 +5052,29 @@ bool Player::canFamiliar(uint16_t lookType) const { return true; } - for (const FamiliarEntry &familiarEntry : familiars) { - if (familiarEntry.lookType == lookType) { - return true; - } + if (std::ranges::any_of(familiars, [&](const FamiliarEntry &familiarEntry) { + return familiarEntry.lookType == lookType; + })) { + return true; } + return false; } void Player::addFamiliar(uint16_t lookType) { - for (FamiliarEntry &familiarEntry : familiars) { - if (familiarEntry.lookType == lookType) { - return; - } + if (std::ranges::none_of(familiars, [&](const FamiliarEntry &familiarEntry) { + return familiarEntry.lookType == lookType; + })) { + familiars.emplace_back(lookType); } - familiars.emplace_back(lookType); } bool Player::removeFamiliar(uint16_t lookType) { - for (auto it = familiars.begin(), end = familiars.end(); it != end; ++it) { - FamiliarEntry &entry = *it; - if (entry.lookType == lookType) { - familiars.erase(it); - return true; - } - } - return false; + auto initialSize = familiars.size(); + std::erase_if(familiars, [&](const FamiliarEntry &entry) { + return entry.lookType == lookType; + }); + return familiars.size() != initialSize; } bool Player::getFamiliar(const std::shared_ptr &familiar) const { @@ -5090,11 +5086,9 @@ bool Player::getFamiliar(const std::shared_ptr &familiar) const { return false; } - for (const FamiliarEntry &familiarEntry : familiars) { - if (familiarEntry.lookType != familiar->lookType) { - continue; - } - + if (std::ranges::any_of(familiars, [&](const FamiliarEntry &familiarEntry) { + return familiarEntry.lookType == familiar->lookType; + })) { return true; } @@ -5128,10 +5122,10 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { const auto &player = creature->getPlayer(); if (player && player->getSkull() == SKULL_NONE) { if (player.get() == this) { - for (const auto &kill : unjustifiedKills) { - if (kill.unavenged && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, __FUNCTION__) * 24 * 60 * 60) { - return SKULL_ORANGE; - } + if (std::ranges::any_of(unjustifiedKills, [&](const auto &kill) { + return kill.unavenged && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, "Player::getSkullClient") * 24 * 60 * 60; + })) { + return SKULL_ORANGE; } } @@ -5151,13 +5145,9 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { } bool Player::hasKilled(const std::shared_ptr &player) const { - for (const auto &kill : unjustifiedKills) { - if (kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, __FUNCTION__) * 24 * 60 * 60 && kill.unavenged) { - return true; - } - } - - return false; + return std::ranges::any_of(unjustifiedKills, [&](const auto &kill) { + return kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, "Player::hasKilled") * 24 * 60 * 60 && kill.unavenged; + }); } bool Player::hasAttacked(const std::shared_ptr &attacked) const { @@ -5302,12 +5292,9 @@ bool Player::hasLearnedInstantSpell(const std::string &spellName) const { return true; } - for (const auto &learnedSpellName : learnedInstantSpellList) { - if (strcasecmp(learnedSpellName.c_str(), spellName.c_str()) == 0) { - return true; - } - } - return false; + return std::ranges::any_of(learnedInstantSpellList, [&](const auto &learnedSpellName) { + return strcasecmp(learnedSpellName.c_str(), spellName.c_str()) == 0; + }); } bool Player::isInWar(const std::shared_ptr &player) const { @@ -5324,7 +5311,7 @@ bool Player::isInWar(const std::shared_ptr &player) const { } bool Player::isInWarList(uint32_t guildId) const { - return std::find(guildWarVector.begin(), guildWarVector.end(), guildId) != guildWarVector.end(); + return std::ranges::find(guildWarVector, guildId) != guildWarVector.end(); } uint32_t Player::getMagicLevel() const { @@ -5365,7 +5352,8 @@ uint32_t Player::getLoyaltyMagicLevel() const { uint32_t Player::getCapacity() const { if (hasFlag(PlayerFlags_t::CannotPickupItem)) { return 0; - } else if (hasFlag(PlayerFlags_t::HasInfiniteCapacity)) { + } + if (hasFlag(PlayerFlags_t::HasInfiniteCapacity)) { return std::numeric_limits::max(); } return capacity + bonusCapacity + varStats[STAT_CAPACITY] + m_wheelPlayer->getStat(WheelStat_t::CAPACITY); @@ -5474,7 +5462,7 @@ int32_t Player::getCleavePercent(bool useCharges) const { int32_t Player::getPerfectShotDamage(uint8_t range, bool useCharges) const { int32_t result = 0; - auto it = perfectShot.find(range); + const auto &it = perfectShot.find(range); if (it != perfectShot.end()) { result = it->second; } @@ -5691,7 +5679,7 @@ void Player::sendPlayerPartyIcons(const std::shared_ptr &player) const { } bool Player::addPartyInvitation(const std::shared_ptr &newParty) { - auto it = std::find(invitePartyList.begin(), invitePartyList.end(), newParty); + const auto &it = std::ranges::find(invitePartyList, newParty); if (it != invitePartyList.end()) { return false; } @@ -5716,7 +5704,7 @@ GuildEmblems_t Player::getGuildEmblem(const std::shared_ptr &player) con return GUILDEMBLEM_NONE; } - const auto playerGuild = player->getGuild(); + const auto &playerGuild = player->getGuild(); if (!playerGuild) { return GUILDEMBLEM_NONE; } @@ -5724,19 +5712,20 @@ GuildEmblems_t Player::getGuildEmblem(const std::shared_ptr &player) con if (player->getGuildWarVector().empty()) { if (guild == playerGuild) { return GUILDEMBLEM_MEMBER; - } else { - return GUILDEMBLEM_OTHER; } - } else if (guild == playerGuild) { + return GUILDEMBLEM_OTHER; + } + if (guild == playerGuild) { return GUILDEMBLEM_ALLY; - } else if (isInWar(player)) { + } + if (isInWar(player)) { return GUILDEMBLEM_ENEMY; } return GUILDEMBLEM_NEUTRAL; } -void Player::sendUnjustifiedPoints() { +void Player::sendUnjustifiedPoints() const { if (client) { double dayKills = 0; double weekKills = 0; @@ -5793,13 +5782,10 @@ void Player::setCurrentMount(uint8_t mount) { } bool Player::hasAnyMount() const { - const auto mounts = g_game().mounts.getMounts(); - for (const auto &mount : mounts) { - if (hasMount(mount)) { - return true; - } - } - return false; + const auto &mounts = g_game().mounts.getMounts(); + return std::ranges::any_of(mounts, [&](const auto &mount) { + return hasMount(mount); + }); } uint8_t Player::getRandomMountId() const { @@ -5831,7 +5817,7 @@ bool Player::toggleMount(bool mount) { return false; } - auto tile = getTile(); + const auto &tile = getTile(); if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ, __FUNCTION__) && !group->access && tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { sendCancelMessage(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE); return false; @@ -5852,7 +5838,7 @@ bool Player::toggleMount(bool mount) { currentMountId = getRandomMountId(); } - const auto currentMount = g_game().mounts.getMountByID(currentMountId); + const auto ¤tMount = g_game().mounts.getMountByID(currentMountId); if (!currentMount) { return false; } @@ -5962,7 +5948,7 @@ bool Player::hasMount(const std::shared_ptr &mount) const { } void Player::dismount() { - const auto mount = g_game().mounts.getMountByID(getCurrentMount()); + const auto &mount = g_game().mounts.getMountByID(getCurrentMount()); if (mount && mount->speed > 0) { g_game().changeSpeed(static_self_cast(), -mount->speed); } @@ -6120,7 +6106,7 @@ bool Player::addOfflineTrainingTries(skills_t skill, uint64_t tries) { } bool Player::hasModalWindowOpen(uint32_t modalWindowId) const { - return find(modalWindows.begin(), modalWindows.end(), modalWindowId) != modalWindows.end(); + return std::ranges::find(modalWindows, modalWindowId) != modalWindows.end(); } void Player::onModalWindowHandled(uint32_t modalWindowId) { @@ -6181,8 +6167,8 @@ void Player::sendIcons() { } // Iterates over the Bakragore icons to check if the player has any - IconBakragore iconBakragore = IconBakragore::None; - for (auto icon : magic_enum::enum_values()) { + auto iconBakragore = IconBakragore::None; + for (const auto &icon : magic_enum::enum_values()) { if (icon == IconBakragore::None) { continue; } @@ -6203,7 +6189,7 @@ void Player::sendIcons() { client->sendIcons(iconSet, iconBakragore); } -void Player::sendIconBakragore(const IconBakragore icon) { +void Player::sendIconBakragore(const IconBakragore icon) const { if (client) { client->sendIconBakragore(icon); } @@ -6223,7 +6209,7 @@ void Player::removeBakragoreIcon(const IconBakragore icon) { } } -void Player::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked) { +void Player::sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked) const { if (client) { client->sendCyclopediaCharacterAchievements(secretsUnlocked, achievementsUnlocked); } @@ -6234,14 +6220,14 @@ uint64_t Player::getMoney() const { uint64_t moneyCount = 0; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; ++i) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } std::shared_ptr container = item->getContainer(); if (container) { - containers.push_back(container); + containers.emplace_back(container); } else { moneyCount += item->getWorth(); } @@ -6249,11 +6235,11 @@ uint64_t Player::getMoney() const { size_t i = 0; while (i < containers.size()) { - std::shared_ptr container = containers[i++]; + const auto &container = containers[i++]; for (const std::shared_ptr &item : container->getItemList()) { - std::shared_ptr tmpContainer = item->getContainer(); + const auto &tmpContainer = item->getContainer(); if (tmpContainer) { - containers.push_back(tmpContainer); + containers.emplace_back(tmpContainer); } else { moneyCount += item->getWorth(); } @@ -6277,8 +6263,8 @@ std::pair Player::getForgeSliversAndCores() const { } // Check items from stash - for (StashItemList stashToSend = getStashItems(); - auto [itemId, itemCount] : stashToSend) { + for (const auto &stashToSend = getStashItems(); + const auto &[itemId, itemCount] : stashToSend) { if (itemId == ITEM_FORGE_SLIVER) { sliverCount += itemCount; } @@ -6293,7 +6279,8 @@ std::pair Player::getForgeSliversAndCores() const { size_t Player::getMaxDepotItems() const { if (group->maxDepotItems != 0) { return group->maxDepotItems; - } else if (isPremium()) { + } + if (isPremium()) { return g_configManager().getNumber(PREMIUM_DEPOT_LIMIT, __FUNCTION__); } return g_configManager().getNumber(FREE_DEPOT_LIMIT, __FUNCTION__); @@ -6303,12 +6290,12 @@ std::vector> Player::getMuteConditions() const { std::vector> muteConditions; muteConditions.reserve(conditions.size()); - for (const std::shared_ptr &condition : conditions) { + for (const auto &condition : conditions) { if (condition->getTicks() <= 0) { continue; } - ConditionType_t type = condition->getType(); + const auto &type = condition->getType(); if (type != CONDITION_MUTED && type != CONDITION_CHANNELMUTEDTICKS && type != CONDITION_YELLTICKS) { continue; } @@ -6332,7 +6319,7 @@ void Player::setGuild(const std::shared_ptr &newGuild) { guildRank = nullptr; if (newGuild) { - const auto rank = newGuild->getRankByLevel(1); + const auto &rank = newGuild->getRankByLevel(1); if (!rank) { return; } @@ -6343,12 +6330,12 @@ void Player::setGuild(const std::shared_ptr &newGuild) { } } -void Player::updateRegeneration() { +void Player::updateRegeneration() const { if (!vocation) { return; } - std::shared_ptr condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); + const auto &condition = getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); if (condition) { condition->setParam(CONDITION_PARAM_HEALTHGAIN, vocation->getHealthGainAmount()); condition->setParam(CONDITION_PARAM_HEALTHTICKS, vocation->getHealthGainTicks()); @@ -6377,7 +6364,7 @@ bool Player::isImmuneFear() const { } uint64_t Player::getItemCustomPrice(uint16_t itemId, bool buyPrice /* = false*/) const { - auto it = itemPriceMap.find(itemId); + const auto &it = itemPriceMap.find(itemId); if (it != itemPriceMap.end()) { return it->second; } @@ -6387,12 +6374,12 @@ uint64_t Player::getItemCustomPrice(uint16_t itemId, bool buyPrice /* = false*/) } uint16_t Player::getFreeBackpackSlots() const { - std::shared_ptr thing = getThing(CONST_SLOT_BACKPACK); + const auto &thing = getThing(CONST_SLOT_BACKPACK); if (!thing) { return 0; } - std::shared_ptr backpack = thing->getContainer(); + const auto &backpack = thing->getContainer(); if (!backpack) { return 0; } @@ -6508,10 +6495,10 @@ void sendStowItems(const std::shared_ptr &item, const std::shared_ptrgetItemCount()); } - if (auto container = stowItem->getContainer()) { + if (const auto &container = stowItem->getContainer()) { for (const auto &stowable_it : container->getStowableItems()) { if ((stowable_it.first)->getID() == item->getID()) { - itemDict.push_back(stowable_it); + itemDict.emplace_back(stowable_it); } } } @@ -6527,21 +6514,21 @@ void Player::stowItem(const std::shared_ptr &item, uint32_t count, bool al if (allItems) { if (!item->isInsideDepot(true)) { // Stow "all items" from player backpack - if (auto backpack = getInventoryItem(CONST_SLOT_BACKPACK)) { + if (const auto &backpack = getInventoryItem(CONST_SLOT_BACKPACK)) { sendStowItems(item, backpack, itemDict); } // Stow "all items" from loot pouch - auto itemParent = item->getParent(); - auto lootPouch = itemParent->getItem(); + const auto &itemParent = item->getParent(); + const auto &lootPouch = itemParent->getItem(); if (itemParent && lootPouch && lootPouch->getID() == ITEM_GOLD_POUCH) { sendStowItems(item, lootPouch, itemDict); } } // Stow locker items - std::shared_ptr depotLocker = getDepotLocker(getLastDepotId()); - auto [itemVector, itemMap] = requestLockerItems(depotLocker); + const auto &depotLocker = getDepotLocker(getLastDepotId()); + const auto &[itemVector, itemMap] = requestLockerItems(depotLocker); for (const auto &lockerItem : itemVector) { if (lockerItem == nullptr) { break; @@ -6553,7 +6540,7 @@ void Player::stowItem(const std::shared_ptr &item, uint32_t count, bool al } } else if (item->getContainer()) { itemDict = item->getContainer()->getStowableItems(); - for (const std::shared_ptr &containerItem : item->getContainer()->getItems(true)) { + for (const auto &containerItem : item->getContainer()->getItems(true)) { uint32_t depotChest = g_configManager().getNumber(DEPOTCHEST, __FUNCTION__); bool validDepot = depotChest > 0 && depotChest < 21; if (g_configManager().getBoolean(STASH_MOVING, __FUNCTION__) && containerItem && !containerItem->isStackable() && validDepot) { @@ -6578,21 +6565,21 @@ void Player::openPlayerContainers() { std::vector>> openContainersList; for (int32_t i = CONST_SLOT_FIRST; i <= CONST_SLOT_LAST; i++) { - const auto item = inventory[i]; + const auto &item = inventory[i]; if (!item) { continue; } - std::shared_ptr itemContainer = item->getContainer(); + const auto &itemContainer = item->getContainer(); if (itemContainer) { - auto cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); + const auto &cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); if (cid > 0) { openContainersList.emplace_back(cid, itemContainer); } for (ContainerIterator it = itemContainer->iterator(); it.hasNext(); it.advance()) { std::shared_ptr subContainer = (*it)->getContainer(); if (subContainer) { - auto subcid = (*it)->getAttribute(ItemAttribute_t::OPENCONTAINER); + const auto &subcid = (*it)->getAttribute(ItemAttribute_t::OPENCONTAINER); if (subcid > 0) { openContainersList.emplace_back(subcid, subContainer); } @@ -6601,13 +6588,13 @@ void Player::openPlayerContainers() { } } - std::sort(openContainersList.begin(), openContainersList.end(), [](const std::pair> &left, const std::pair> &right) { + std::ranges::sort(openContainersList, [](const std::pair> &left, const std::pair> &right) { return left.first < right.first; }); - for (auto &it : openContainersList) { - addContainer(it.first - 1, it.second); - onSendContainer(it.second); + for (const auto &[fst, snd] : openContainersList) { + addContainer(fst - 1, snd); + onSendContainer(snd); } } @@ -6632,9 +6619,9 @@ void Player::initializePrey() { } void Player::removePreySlotById(PreySlot_t slotid) { - auto it = std::remove_if(preys.begin(), preys.end(), [slotid](const std::unique_ptr &preyIt) { - return preyIt->id == slotid; - }); + const auto it = std::ranges::remove_if(preys, [slotid](const auto &preyIt) { + return preyIt->id == slotid; + }).begin(); preys.erase(it, preys.end()); } @@ -6665,7 +6652,7 @@ void Player::initializeTaskHunting() { std::string Player::getBlessingsName() const { std::vector blessingNames; - for (auto bless : magic_enum::enum_values()) { + for (const auto &bless : magic_enum::enum_values()) { if (hasBlessing(enumToValue(bless))) { std::string name = toStartCaseWithSpace(magic_enum::enum_name(bless).data()); blessingNames.emplace_back(name); @@ -6696,7 +6683,7 @@ bool Player::isCreatureUnlockedOnTaskHunting(const std::shared_ptr } void Player::triggerMomentum() { - auto item = getInventoryItem(CONST_SLOT_HEAD); + const auto &item = getInventoryItem(CONST_SLOT_HEAD); if (item == nullptr) { return; } @@ -6731,7 +6718,7 @@ void Player::triggerMomentum() { void Player::clearCooldowns() { auto it = conditions.begin(); while (it != conditions.end()) { - auto condItem = *it; + const auto &condItem = *it; ConditionType_t type = condItem->getType(); auto maxu16 = std::numeric_limits::max(); auto checkSpellId = condItem->getSubId(); @@ -6749,7 +6736,7 @@ void Player::triggerTranscendance() { return; } - auto item = getInventoryItem(CONST_SLOT_LEGS); + const auto &item = getInventoryItem(CONST_SLOT_LEGS); if (item == nullptr) { return; } @@ -6776,7 +6763,7 @@ void Player::triggerTranscendance() { const auto &task = createPlayerTask( std::max(SCHEDULER_MINTICKS, duration), [playerId = getID()] { - auto player = g_game().getPlayerByID(playerId); + const auto &player = g_game().getPlayerByID(playerId); if (player) { player->sendSkills(); player->sendStats(); @@ -6798,13 +6785,13 @@ void Player::triggerTranscendance() { void Player::requestDepotItems() { ItemsTierCountList itemMap; uint16_t count = 0; - std::shared_ptr depotLocker = getDepotLocker(getLastDepotId()); + const auto &depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return; } - for (const std::shared_ptr &locker : depotLocker->getItemList()) { - std::shared_ptr c = locker->getContainer(); + for (const auto &locker : depotLocker->getItemList()) { + const auto &c = locker->getContainer(); if (!c || c->empty()) { continue; } @@ -6864,17 +6851,20 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { stashCount = getStashItemCount(itemId); } - std::shared_ptr depotLocker = getDepotLocker(getLastDepotId()); + const auto &depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return; } - for (const std::shared_ptr &locker : depotLocker->getItemList()) { - std::shared_ptr c = locker->getContainer(); + for (const auto &locker : depotLocker->getItemList()) { + const auto &c = locker->getContainer(); if (!c || c->empty()) { continue; } + inboxItems.reserve(inboxItems.size()); + depotItems.reserve(depotItems.size()); + for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { const auto item = *it; if (!item || item->getID() != itemId || item->getTier() != tier) { @@ -6883,12 +6873,12 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { if (c->isInbox()) { if (inboxItems.size() < 255) { - inboxItems.push_back(item); + inboxItems.emplace_back(item); } inboxCount += Item::countByType(item, -1); } else { if (depotItems.size() < 255) { - depotItems.push_back(item); + depotItems.emplace_back(item); } depotCount += Item::countByType(item, -1); } @@ -6900,14 +6890,14 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { } void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool isDepot) { - std::shared_ptr depotLocker = getDepotLocker(getLastDepotId()); + const auto &depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return; } std::vector> itemsVector; - for (const std::shared_ptr &locker : depotLocker->getItemList()) { - std::shared_ptr c = locker->getContainer(); + for (const auto &locker : depotLocker->getItemList()) { + const auto &c = locker->getContainer(); if (!c || c->empty() || // Retrieve from inbox. (c->isInbox() && isDepot) || @@ -6917,19 +6907,19 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool } for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { - const auto item = *it; + const auto &item = *it; if (!item) { continue; } if (item->getID() == itemId && item->getTier() == depotSearchOnItem.second) { - itemsVector.push_back(item); + itemsVector.emplace_back(item); } } } ReturnValue ret = RETURNVALUE_NOERROR; - for (const std::shared_ptr &item : itemsVector) { + for (const auto &item : itemsVector) { // First lets try to retrieve the item to the stash retrieve container. if (g_game().tryRetrieveStashItems(static_self_cast(), item)) { continue; @@ -6953,13 +6943,13 @@ void Player::openContainerFromDepotSearch(const Position &pos) { return; } - const auto item = getItemFromDepotSearch(depotSearchOnItem.first, pos); + const auto &item = getItemFromDepotSearch(depotSearchOnItem.first, pos); if (!item) { sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - std::shared_ptr container = item->getParent() ? item->getParent()->getContainer() : nullptr; + const auto &container = item->getParent() ? item->getParent()->getContainer() : nullptr; if (!container) { sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; @@ -6969,21 +6959,21 @@ void Player::openContainerFromDepotSearch(const Position &pos) { } std::shared_ptr Player::getItemFromDepotSearch(uint16_t itemId, const Position &pos) { - std::shared_ptr depotLocker = getDepotLocker(getLastDepotId()); + const auto &depotLocker = getDepotLocker(getLastDepotId()); if (!depotLocker) { return nullptr; } uint8_t index = 0; - for (const std::shared_ptr &locker : depotLocker->getItemList()) { - std::shared_ptr c = locker->getContainer(); + for (const auto &locker : depotLocker->getItemList()) { + const auto &c = locker->getContainer(); if (!c || c->empty() || (c->isInbox() && pos.y != 0x21) || // From inbox. (!c->isInbox() && pos.y != 0x20)) { // From depot. continue; } for (ContainerIterator it = c->iterator(); it.hasNext(); it.advance()) { - const auto item = *it; + const auto &item = *it; if (!item || item->getID() != itemId || item->getTier() != depotSearchOnItem.second) { continue; } @@ -7010,12 +7000,12 @@ Player::requestLockerItems(const std::shared_ptr &depotLocker, bool std::vector> containers { depotLocker }; for (size_t i = 0; i < containers.size(); ++i) { - std::shared_ptr container = containers[i]; + const auto &container = containers[i]; for (const auto &item : container->getItemList()) { - std::shared_ptr lockerContainers = item->getContainer(); + const auto &lockerContainers = item->getContainer(); if (lockerContainers && !lockerContainers->empty()) { - containers.push_back(lockerContainers); + containers.emplace_back(lockerContainers); continue; } @@ -7033,7 +7023,7 @@ Player::requestLockerItems(const std::shared_ptr &depotLocker, bool } lockerItems[itemType.wareId][item->getTier()] += Item::countByType(item, -1); - itemVector.push_back(item); + itemVector.emplace_back(item); } } @@ -7050,7 +7040,7 @@ Player::requestLockerItems(const std::shared_ptr &depotLocker, bool std::pair>, uint16_t> Player::getLockerItemsAndCountById(const std::shared_ptr &depotLocker, uint8_t tier, uint16_t itemId) const { std::vector> lockerItems; - auto [itemVector, itemMap] = requestLockerItems(depotLocker, false, tier); + const auto &[itemVector, itemMap] = requestLockerItems(depotLocker, false, tier); uint16_t totalCount = 0; for (const auto &item : itemVector) { if (!item || item->getID() != itemId) { @@ -7058,7 +7048,7 @@ std::pair>, uint16_t> Player::getLockerItemsAn } totalCount++; - lockerItems.push_back(item); + lockerItems.emplace_back(item); } return std::make_pair(lockerItems, totalCount); @@ -7068,7 +7058,7 @@ bool Player::saySpell( SpeakClasses type, const std::string &text, bool ghostMode, - Spectators* spectatorsPtr /* = nullptr*/, + const Spectators* spectatorsPtr /* = nullptr*/, const Position* pos /* = nullptr*/ ) { if (text.empty()) { @@ -7098,8 +7088,8 @@ bool Player::saySpell( int32_t valueEmote = 0; // Send to client - for (const std::shared_ptr &spectator : spectators) { - if (std::shared_ptr tmpPlayer = spectator->getPlayer()) { + for (const auto &spectator : spectators) { + if (const auto &tmpPlayer = spectator->getPlayer()) { if (g_configManager().getBoolean(EMOTE_SPELLS, __FUNCTION__)) { valueEmote = tmpPlayer->getStorageValue(STORAGEVALUE_EMOTE); } @@ -7114,8 +7104,8 @@ bool Player::saySpell( } // Execute lua event method - for (const std::shared_ptr &spectator : spectators) { - auto tmpPlayer = spectator->getPlayer(); + for (const auto &spectator : spectators) { + const auto &tmpPlayer = spectator->getPlayer(); if (!tmpPlayer) { continue; } @@ -7142,7 +7132,7 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint history.success = success; history.tierLoss = reduceTierLoss; - auto firstForgingItem = getForgeItemFromId(firstItemId, tier); + const auto &firstForgingItem = getForgeItemFromId(firstItemId, tier); if (!firstForgingItem) { g_logger().error("[Log 1] Player with name {} failed to fuse item with id {}", getName(), firstItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7155,7 +7145,7 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto secondForgingItem = getForgeItemFromId(secondItemId, tier); + const auto &secondForgingItem = getForgeItemFromId(secondItemId, tier); if (!secondForgingItem) { g_logger().error("[Log 2] Player with name {} failed to fuse item with id {}", getName(), secondItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7169,20 +7159,20 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint return; } - auto exaltationChest = Item::CreateItem(ITEM_EXALTATION_CHEST, 1); + const auto &exaltationChest = Item::CreateItem(ITEM_EXALTATION_CHEST, 1); if (!exaltationChest) { g_logger().error("Failed to create exaltation chest"); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto exaltationContainer = exaltationChest->getContainer(); + const auto &exaltationContainer = exaltationChest->getContainer(); if (!exaltationContainer) { g_logger().error("Failed to create exaltation container"); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - std::shared_ptr firstForgedItem = Item::CreateItem(firstItemId, 1); + const auto &firstForgedItem = Item::CreateItem(firstItemId, 1); if (!firstForgedItem) { g_logger().error("[Log 3] Player with name {} failed to fuse item with id {}", getName(), firstItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7196,8 +7186,8 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint return; } - auto configKey = convergence ? FORGE_CONVERGENCE_FUSION_DUST_COST : FORGE_FUSION_DUST_COST; - auto dustCost = static_cast(g_configManager().getNumber(configKey, __FUNCTION__)); + const auto configKey = convergence ? FORGE_CONVERGENCE_FUSION_DUST_COST : FORGE_FUSION_DUST_COST; + const auto dustCost = static_cast(g_configManager().getNumber(configKey, __FUNCTION__)); if (convergence) { firstForgedItem->setTier(tier + 1); history.dustCost = dustCost; @@ -7226,7 +7216,7 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint history.cost = cost; } else { firstForgedItem->setTier(tier); - std::shared_ptr secondForgedItem = Item::CreateItem(secondItemId, 1); + const auto &secondForgedItem = Item::CreateItem(secondItemId, 1); if (!secondForgedItem) { g_logger().error("[Log 4] Player with name {} failed to fuse item with id {}", getName(), secondItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7300,7 +7290,7 @@ void Player::forgeFuseItems(ForgeAction_t actionType, uint16_t firstItemId, uint } } } else { - auto isTierLost = uniform_random(1, 100) <= (reduceTierLoss ? g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION, __FUNCTION__) : 100); + const auto isTierLost = uniform_random(1, 100) <= (reduceTierLoss ? g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION, __FUNCTION__) : 100); if (isTierLost) { if (secondForgedItem->getTier() >= 1) { secondForgedItem->setTier(tier - 1); @@ -7384,7 +7374,7 @@ void Player::forgeTransferItemTier(ForgeAction_t actionType, uint16_t donorItemI history.tier = tier; history.success = true; - auto donorItem = getForgeItemFromId(donorItemId, tier); + const auto &donorItem = getForgeItemFromId(donorItemId, tier); if (!donorItem) { g_logger().error("[Log 1] Player with name {} failed to transfer item with id {}", getName(), donorItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7398,7 +7388,7 @@ void Player::forgeTransferItemTier(ForgeAction_t actionType, uint16_t donorItemI return; } - auto receiveItem = getForgeItemFromId(receiveItemId, 0); + const auto &receiveItem = getForgeItemFromId(receiveItemId, 0); if (!receiveItem) { g_logger().error("[Log 2] Player with name {} failed to transfer item with id {}", getName(), receiveItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7412,35 +7402,35 @@ void Player::forgeTransferItemTier(ForgeAction_t actionType, uint16_t donorItemI return; } - auto exaltationChest = Item::CreateItem(ITEM_EXALTATION_CHEST, 1); + const auto &exaltationChest = Item::CreateItem(ITEM_EXALTATION_CHEST, 1); if (!exaltationChest) { g_logger().error("Exaltation chest is nullptr"); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto exaltationContainer = exaltationChest->getContainer(); + const auto &exaltationContainer = exaltationChest->getContainer(); if (!exaltationContainer) { g_logger().error("Exaltation container is nullptr"); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - std::shared_ptr newReceiveItem = Item::CreateItem(receiveItemId, 1); + const auto &newReceiveItem = Item::CreateItem(receiveItemId, 1); if (!newReceiveItem) { g_logger().error("[Log 6] Player with name {} failed to fuse item with id {}", getName(), receiveItemId); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto configKey = convergence ? FORGE_CONVERGENCE_TRANSFER_DUST_COST : FORGE_TRANSFER_DUST_COST; + const auto configKey = convergence ? FORGE_CONVERGENCE_TRANSFER_DUST_COST : FORGE_TRANSFER_DUST_COST; if (getForgeDusts() < g_configManager().getNumber(configKey, __FUNCTION__)) { g_logger().error("[Log 8] Failed to remove transfer dusts from player with name {}", getName()); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; - } else { - setForgeDusts(getForgeDusts() - g_configManager().getNumber(configKey, __FUNCTION__)); } + setForgeDusts(getForgeDusts() - g_configManager().getNumber(configKey, __FUNCTION__)); + if (convergence) { newReceiveItem->setTier(tier); } else { @@ -7465,9 +7455,9 @@ void Player::forgeTransferItemTier(ForgeAction_t actionType, uint16_t donorItemI sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); break; } - auto tierPriecs = itemClassification->tiers.at(donorItem->getTier()); - cost = convergence ? tierPriecs.convergenceTransferPrice : tierPriecs.regularPrice; - coresAmount = tierPriecs.corePrice; + const auto &[corePrice, regularPrice, convergenceFusionPrice, convergenceTransferPrice] = itemClassification->tiers.at(donorItem->getTier()); + cost = convergence ? convergenceTransferPrice : regularPrice; + coresAmount = corePrice; break; } @@ -7518,7 +7508,7 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { } auto itemCount = static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); - const auto item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); + const auto &item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); returnValue = g_game().internalPlayerAddItem(static_self_cast(), item); if (returnValue != RETURNVALUE_NOERROR) { g_logger().error("Failed to add {} slivers to player with name {}", itemCount, getName()); @@ -7530,7 +7520,7 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { history.gained = 3; setForgeDusts(dusts - cost); } else if (actionType == ForgeAction_t::SLIVERSTOCORES) { - auto [sliverCount, coreCount] = getForgeSliversAndCores(); + const auto &[sliverCount, coreCount] = getForgeSliversAndCores(); auto cost = static_cast(g_configManager().getNumber(FORGE_CORE_COST, __FUNCTION__)); if (cost > sliverCount) { g_logger().error("[{}] Not enough sliver", __FUNCTION__); @@ -7544,7 +7534,7 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { return; } - if (const auto item = Item::CreateItem(ITEM_FORGE_CORE, 1); + if (const auto &item = Item::CreateItem(ITEM_FORGE_CORE, 1); item) { returnValue = g_game().internalPlayerAddItem(static_self_cast(), item); } @@ -7747,25 +7737,25 @@ void Player::closeAllExternalContainers() { } std::vector> containerToClose; - for (const auto &it : openContainers) { - std::shared_ptr container = it.second.container; + for (const auto &[fst, snd] : openContainers) { + const auto &container = snd.container; if (!container) { continue; } if (container->getHoldingPlayer() != getPlayer()) { - containerToClose.push_back(container); + containerToClose.emplace_back(container); } } - for (const std::shared_ptr &container : containerToClose) { + for (const auto &container : containerToClose) { autoCloseContainers(container); } } SoundEffect_t Player::getHitSoundEffect() const { // Distance sound effects - std::shared_ptr tool = getWeapon(); + const auto &tool = getWeapon(); if (tool == nullptr) { return SoundEffect_t::SILENCE; } @@ -7774,10 +7764,12 @@ SoundEffect_t Player::getHitSoundEffect() const { case WEAPON_AMMO: { if (it.ammoType == AMMO_BOLT) { return SoundEffect_t::DIST_ATK_CROSSBOW_SHOT; - } else if (it.ammoType == AMMO_ARROW) { + } + if (it.ammoType == AMMO_ARROW) { if (it.shootType == CONST_ANI_BURSTARROW) { return SoundEffect_t::BURST_ARROW_EFFECT; - } else if (it.shootType == CONST_ANI_DIAMONDARROW) { + } + if (it.shootType == CONST_ANI_DIAMONDARROW) { return SoundEffect_t::DIAMOND_ARROW_EFFECT; } } else { @@ -7787,11 +7779,11 @@ SoundEffect_t Player::getHitSoundEffect() const { case WEAPON_DISTANCE: { if (tool->getAmmoType() == AMMO_BOLT) { return SoundEffect_t::DIST_ATK_CROSSBOW_SHOT; - } else if (tool->getAmmoType() == AMMO_ARROW) { + } + if (tool->getAmmoType() == AMMO_ARROW) { return SoundEffect_t::DIST_ATK_BOW_SHOT; - } else { - return SoundEffect_t::DIST_ATK_THROW_SHOT; } + return SoundEffect_t::DIST_ATK_THROW_SHOT; } case WEAPON_WAND: { // Separate between wand and rod here @@ -7807,7 +7799,7 @@ SoundEffect_t Player::getHitSoundEffect() const { } SoundEffect_t Player::getAttackSoundEffect() const { - std::shared_ptr tool = getWeapon(); + const auto &tool = getWeapon(); if (tool == nullptr) { return SoundEffect_t::HUMAN_CLOSE_ATK_FIST; } @@ -7831,11 +7823,11 @@ SoundEffect_t Player::getAttackSoundEffect() const { case WEAPON_DISTANCE: { if (tool->getAmmoType() == AMMO_BOLT) { return SoundEffect_t::DIST_ATK_CROSSBOW; - } else if (tool->getAmmoType() == AMMO_ARROW) { + } + if (tool->getAmmoType() == AMMO_ARROW) { return SoundEffect_t::DIST_ATK_BOW; - } else { - return SoundEffect_t::DIST_ATK_THROW; } + return SoundEffect_t::DIST_ATK_THROW; break; } @@ -7857,7 +7849,7 @@ bool Player::canAutoWalk(const Position &toPosition, const std::function if (getPathTo(toPosition, listDir, 0, 1, true, true)) { g_dispatcher().addEvent([creatureId = getID(), listDir] { g_game().playerAutoWalk(creatureId, listDir); }, __FUNCTION__); - std::shared_ptr task = createPlayerTask(delay, function, __FUNCTION__); + const auto &task = createPlayerTask(delay, function, __FUNCTION__); setNextWalkActionTask(task); return true; } else { @@ -7879,7 +7871,7 @@ bool Player::setAccount(uint32_t accountId) { } uint8_t Player::getAccountType() const { - return static_cast(account ? account->getAccountType() : static_cast(AccountType::ACCOUNT_TYPE_NORMAL)); + return account ? account->getAccountType() : static_cast(AccountType::ACCOUNT_TYPE_NORMAL); } uint32_t Player::getAccountId() const { @@ -7966,7 +7958,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, const std::shared } } -void Player::parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster) { +void Player::parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster) const { if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM, __FUNCTION__)) { return; } @@ -8015,7 +8007,6 @@ void Player::parseAttackDealtHazardSystem(CombatDamage &damage, const std::share if (damage.secondary.value != 0) { damage.secondary.value -= static_cast(std::ceil((static_cast(damage.secondary.value) * stage) / 10000)); } - return; } } } @@ -8079,13 +8070,13 @@ const std::unique_ptr &Player::cyclopedia() const { } void Player::sendLootMessage(const std::string &message) const { - auto party = getParty(); + const auto &party = getParty(); if (!party) { sendTextMessage(MESSAGE_LOOT, message); return; } - if (auto partyLeader = party->getLeader()) { + if (const auto &partyLeader = party->getLeader()) { partyLeader->sendTextMessage(MESSAGE_LOOT, message); } for (const auto &partyMember : party->getMembers()) { @@ -8097,20 +8088,20 @@ void Player::sendLootMessage(const std::string &message) const { std::shared_ptr Player::getLootPouch() { // Allow players with CM access or higher have the loot pouch anywhere - auto parentItem = getParent() ? getParent()->getItem() : nullptr; + const auto &parentItem = getParent() ? getParent()->getItem() : nullptr; if (isPlayerGroup() && parentItem && parentItem->getID() != ITEM_STORE_INBOX) { return nullptr; } - auto inventoryItems = getInventoryItemsFromId(ITEM_GOLD_POUCH); + const auto &inventoryItems = getInventoryItemsFromId(ITEM_GOLD_POUCH); if (inventoryItems.empty()) { return nullptr; } - auto containerItem = inventoryItems.front(); + const auto &containerItem = inventoryItems.front(); if (!containerItem) { return nullptr; } - auto container = containerItem->getContainer(); + const auto &container = containerItem->getContainer(); if (!container) { return nullptr; } @@ -8119,12 +8110,12 @@ std::shared_ptr Player::getLootPouch() { } std::shared_ptr Player::getStoreInbox() const { - auto thing = getThing(CONST_SLOT_STORE_INBOX); + const auto &thing = getThing(CONST_SLOT_STORE_INBOX); if (!thing) { return nullptr; } - auto storeInbox = thing->getContainer(); + const auto &storeInbox = thing->getContainer(); return storeInbox ? storeInbox : nullptr; } @@ -8139,7 +8130,7 @@ bool Player::hasPermittedConditionInPZ() const { }; bool hasPermittedCondition = false; - for (auto condition : allowedConditions) { + for (const auto &condition : allowedConditions) { if (getCondition(condition)) { hasPermittedCondition = true; break; @@ -8151,7 +8142,7 @@ bool Player::hasPermittedConditionInPZ() const { uint16_t Player::getDodgeChance() const { uint16_t chance = 0; - if (auto playerArmor = getInventoryItem(CONST_SLOT_ARMOR); + if (const auto &playerArmor = getInventoryItem(CONST_SLOT_ARMOR); playerArmor != nullptr && playerArmor->getTier()) { chance += static_cast(playerArmor->getDodgeChance() * 100); } @@ -8199,7 +8190,7 @@ bool Player::canSpeakWithHireling(uint8_t speechbubble) { } uint16_t Player::getPlayerVocationEnum() const { - int cipTibiaId = getVocation()->getClientId(); + const int cipTibiaId = getVocation()->getClientId(); if (cipTibiaId == 1 || cipTibiaId == 11) { return Vocation_t::VOCATION_KNIGHT_CIP; // Knight } else if (cipTibiaId == 2 || cipTibiaId == 12) { diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index b7ff5e1d3d2..4c448da90e0 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -67,7 +67,7 @@ struct ModalWindow; struct Achievement; struct Badge; struct Title; -struct VIPGroup; +class VIPGroup; struct ForgeHistory { ForgeAction_t actionType = ForgeAction_t::FUSION; @@ -194,13 +194,13 @@ class Player final : public Creature, public Cylinder, public Bankable { randomMount = isMountRandomized; } - void sendFYIBox(const std::string &message) { + void sendFYIBox(const std::string &message) const { if (client) { client->sendFYIBox(message); } } - void BestiarysendCharms() { + void BestiarysendCharms() const { if (client) { client->BestiarysendCharms(); } @@ -242,7 +242,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return staminaMinutes; } - void sendItemsPrice() { + void sendItemsPrice() const { if (client) { client->sendItemsPrice(); } @@ -329,7 +329,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void removeMonsterFromCyclopediaTrackerList(const std::shared_ptr &mtype, bool isBoss, bool reloadClient = false); - void sendBestiaryEntryChanged(uint16_t raceid) { + void sendBestiaryEntryChanged(uint16_t raceid) const { if (client) { client->sendBestiaryEntryChanged(raceid); } @@ -358,7 +358,7 @@ class Player final : public Creature, public Cylinder, public Bankable { operatingSystem = clientos; } - bool isOldProtocol() { + bool isOldProtocol() const { return client && client->oldProtocol; } @@ -430,7 +430,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void removePartyInvitation(const std::shared_ptr &party); void clearPartyInvitations(); - void sendUnjustifiedPoints(); + void sendUnjustifiedPoints() const; GuildEmblems_t getGuildEmblem(const std::shared_ptr &player) const; @@ -457,10 +457,10 @@ class Player final : public Creature, public Cylinder, public Bankable { bedItem = std::move(b); } - bool hasImbuingItem() { + bool hasImbuingItem() const { return imbuingItem != nullptr; } - void setImbuingItem(std::shared_ptr item); + void setImbuingItem(const std::shared_ptr &item); void addBlessing(uint8_t index, uint8_t count) { if (blessings[index - 1] == 255) { @@ -497,7 +497,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isOffline() const { return (getID() == 0); } - void disconnect() { + void disconnect() const { if (client) { client->disconnect(); } @@ -703,7 +703,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void addMessageBuffer(); void removeMessageBuffer(); - bool removeItemOfType(uint16_t itemId, uint32_t itemAmount, int32_t subType, bool ignoreEquipped = false); + bool removeItemOfType(uint16_t itemId, uint32_t itemAmount, int32_t subType, bool ignoreEquipped = false) const; /** * @param itemAmount is uint32_t because stash item is uint32_t max */ @@ -814,10 +814,10 @@ class Player final : public Creature, public Cylinder, public Bankable { void setMainBackpackUnassigned(const std::shared_ptr &container); bool canSee(const Position &pos) override; - bool canSeeCreature(std::shared_ptr creature) const override; + bool canSeeCreature(const std::shared_ptr &creature) const override; bool canWalkthrough(const std::shared_ptr &creature); - bool canWalkthroughEx(const std::shared_ptr &creature); + bool canWalkthroughEx(const std::shared_ptr &creature) const; RaceType_t getRace() const override { return RACE_BLOOD; @@ -847,7 +847,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } // follow functions - bool setFollowCreature(std::shared_ptr creature) override; + bool setFollowCreature(const std::shared_ptr &creature) override; void goToFollowCreature() override; // follow events @@ -880,7 +880,7 @@ class Player final : public Creature, public Cylinder, public Bankable { faction = factionId; } // combat functions - bool setAttackedCreature(std::shared_ptr creature) override; + bool setAttackedCreature(const std::shared_ptr &creature) override; bool isImmune(CombatType_t type) const override; bool isImmune(ConditionType_t type) const override; bool hasShield() const; @@ -987,22 +987,22 @@ class Player final : public Creature, public Cylinder, public Bankable { void addInFightTicks(bool pzlock = false); - uint64_t getGainedExperience(std::shared_ptr attacker) const override; + uint64_t getGainedExperience(const std::shared_ptr &attacker) const override; // combat event functions void onAddCondition(const ConditionType_t &type) override; void onAddCombatCondition(const ConditionType_t &type) override; void onEndCondition(const ConditionType_t &type) override; - void onCombatRemoveCondition(std::shared_ptr condition) override; - void onAttackedCreature(std::shared_ptr target) override; + void onCombatRemoveCondition(const std::shared_ptr &condition) override; + void onAttackedCreature(const std::shared_ptr &target) override; void onAttacked() override; - void onAttackedCreatureDrainHealth(std::shared_ptr target, int32_t points) override; - void onTargetCreatureGainHealth(std::shared_ptr target, int32_t points) override; + void onAttackedCreatureDrainHealth(const std::shared_ptr &target, int32_t points) override; + void onTargetCreatureGainHealth(const std::shared_ptr &target, int32_t points) override; bool onKilledPlayer(const std::shared_ptr &target, bool lastHit) override; bool onKilledMonster(const std::shared_ptr &target) override; - void onGainExperience(uint64_t gainExp, std::shared_ptr target) override; + void onGainExperience(uint64_t gainExp, const std::shared_ptr &target) override; void onGainSharedExperience(uint64_t gainExp, const std::shared_ptr &target); - void onAttackedCreatureBlockHit(BlockType_t blockType) override; + void onAttackedCreatureBlockHit(const BlockType_t &blockType) override; void onBlockHit() override; void onTakeDamage(std::shared_ptr attacker, int32_t damage) override; void onChangeZone(ZoneType_t zone) override; @@ -1076,7 +1076,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendRemoveTileThing(const Position &pos, int32_t stackpos) { + void sendRemoveTileThing(const Position &pos, int32_t stackpos) const { if (stackpos != -1 && client) { client->sendRemoveTileThing(pos, stackpos); } @@ -1086,18 +1086,18 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendUpdateTileCreature(creature->getPosition(), creature->getTile()->getClientIndexOfCreature(static_self_cast(), creature), creature); } } - void sendUpdateTile(const std::shared_ptr &updateTile, const Position &pos) { + void sendUpdateTile(const std::shared_ptr &updateTile, const Position &pos) const { if (client) { client->sendUpdateTile(updateTile, pos); } } - void sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel) { + void sendChannelMessage(const std::string &author, const std::string &text, SpeakClasses type, uint16_t channel) const { if (client) { client->sendChannelMessage(author, text, type, channel); } } - void sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent) { + void sendChannelEvent(uint16_t channelId, const std::string &playerName, ChannelEvent_t channelEvent) const { if (client) { client->sendChannelEvent(channelId, playerName, channelEvent); } @@ -1116,7 +1116,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendAddCreature(creature, pos, tile->getStackposOfCreature(static_self_cast(), creature), isLogin); } } - void sendCreatureMove(const std::shared_ptr &creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) { + void sendCreatureMove(const std::shared_ptr &creature, const Position &newPos, int32_t newStackPos, const Position &oldPos, int32_t oldStackPos, bool teleport) const { if (client) { client->sendMoveCreature(creature, newPos, newStackPos, oldPos, oldStackPos, teleport); } @@ -1138,27 +1138,27 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr) { + void sendCreatureSay(const std::shared_ptr &creature, SpeakClasses type, const std::string &text, const Position* pos = nullptr) const { if (client) { client->sendCreatureSay(creature, type, text, pos); } } - void sendCreatureReload(const std::shared_ptr &creature) { + void sendCreatureReload(const std::shared_ptr &creature) const { if (client) { client->reloadCreature(creature); } } - void sendPrivateMessage(const std::shared_ptr &speaker, SpeakClasses type, const std::string &text) { + void sendPrivateMessage(const std::shared_ptr &speaker, SpeakClasses type, const std::string &text) const { if (client) { client->sendPrivateMessage(speaker, type, text); } } - void sendCreatureSquare(const std::shared_ptr &creature, SquareColor_t color) { + void sendCreatureSquare(const std::shared_ptr &creature, SquareColor_t color) const { if (client) { client->sendCreatureSquare(creature, color); } } - void sendCreatureChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) { + void sendCreatureChangeOutfit(const std::shared_ptr &creature, const Outfit_t &outfit) const { if (client) { client->sendCreatureOutfit(creature, outfit); } @@ -1194,12 +1194,12 @@ class Player final : public Creature, public Cylinder, public Bankable { } } } - void sendCreatureLight(const std::shared_ptr &creature) { + void sendCreatureLight(const std::shared_ptr &creature) const { if (client) { client->sendCreatureLight(creature); } } - void sendCreatureIcon(const std::shared_ptr &creature) { + void sendCreatureIcon(const std::shared_ptr &creature) const { if (client && !client->oldProtocol) { client->sendCreatureIcon(creature); } @@ -1209,27 +1209,27 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendUpdateCreature(creature); } } - void sendCreatureWalkthrough(const std::shared_ptr &creature, bool walkthrough) { + void sendCreatureWalkthrough(const std::shared_ptr &creature, bool walkthrough) const { if (client) { client->sendCreatureWalkthrough(creature, walkthrough); } } - void sendCreatureShield(const std::shared_ptr &creature) { + void sendCreatureShield(const std::shared_ptr &creature) const { if (client) { client->sendCreatureShield(creature); } } - void sendCreatureType(const std::shared_ptr &creature, uint8_t creatureType) { + void sendCreatureType(const std::shared_ptr &creature, uint8_t creatureType) const { if (client) { client->sendCreatureType(creature, creatureType); } } - void sendSpellCooldown(uint16_t spellId, uint32_t time) { + void sendSpellCooldown(uint16_t spellId, uint32_t time) const { if (client) { client->sendSpellCooldown(spellId, time); } } - void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) { + void sendSpellGroupCooldown(SpellGroup_t groupId, uint32_t time) const { if (client) { client->sendSpellGroupCooldown(groupId, time); } @@ -1239,7 +1239,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendUseItemCooldown(time); } } - void reloadCreature(const std::shared_ptr &creature) { + void reloadCreature(const std::shared_ptr &creature) const { if (client) { client->reloadCreature(creature); } @@ -1251,7 +1251,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void sendAddContainerItem(const std::shared_ptr &container, std::shared_ptr item); void sendUpdateContainerItem(const std::shared_ptr &container, uint16_t slot, const std::shared_ptr &newItem); void sendRemoveContainerItem(const std::shared_ptr &container, uint16_t slot); - void sendContainer(uint8_t cid, const std::shared_ptr &container, bool hasParent, uint16_t firstIndex) { + void sendContainer(uint8_t cid, const std::shared_ptr &container, bool hasParent, uint16_t firstIndex) const { if (client) { client->sendContainer(cid, container, hasParent, firstIndex); } @@ -1273,17 +1273,17 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendDepotSearchResultDetail(itemId, tier, depotCount, depotItems, inboxCount, inboxItems, stashCount); } } - void sendCoinBalance() { + void sendCoinBalance() const { if (client) { client->sendCoinBalance(); } } - void sendInventoryItem(Slots_t slot, const std::shared_ptr &item) { + void sendInventoryItem(Slots_t slot, const std::shared_ptr &item) const { if (client) { client->sendInventoryItem(slot, item); } } - void sendInventoryIds() { + void sendInventoryIds() const { if (client) { client->sendInventoryIds(); } @@ -1292,19 +1292,19 @@ class Player final : public Creature, public Cylinder, public Bankable { void openPlayerContainers(); // Quickloot - void sendLootContainers() { + void sendLootContainers() const { if (client) { client->sendLootContainers(); } } - void sendSingleSoundEffect(const Position &pos, SoundEffect_t id, SourceEffect_t source) { + void sendSingleSoundEffect(const Position &pos, SoundEffect_t id, SourceEffect_t source) const { if (client) { client->sendSingleSoundEffect(pos, id, source); } } - void sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundId, SourceEffect_t mainSource, SoundEffect_t secondarySoundId, SourceEffect_t secondarySource) { + void sendDoubleSoundEffect(const Position &pos, SoundEffect_t mainSoundId, SourceEffect_t mainSource, SoundEffect_t secondarySoundId, SourceEffect_t secondarySource) const { if (client) { client->sendDoubleSoundEffect(pos, mainSoundId, mainSource, secondarySoundId, secondarySource); } @@ -1314,8 +1314,8 @@ class Player final : public Creature, public Cylinder, public Bankable { SoundEffect_t getHitSoundEffect() const; // event methods - void onUpdateTileItem(std::shared_ptr tile, const Position &pos, std::shared_ptr oldItem, const ItemType &oldType, std::shared_ptr newItem, const ItemType &newType) override; - void onRemoveTileItem(std::shared_ptr tile, const Position &pos, const ItemType &iType, std::shared_ptr item) override; + void onUpdateTileItem(const std::shared_ptr &tile, const Position &pos, const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType) override; + void onRemoveTileItem(const std::shared_ptr &tile, const Position &pos, const ItemType &iType, const std::shared_ptr &item) override; void onCreatureAppear(const std::shared_ptr &creature, bool isLogin) override; void onRemoveCreature(const std::shared_ptr &creature, bool isLogout) override; @@ -1412,14 +1412,14 @@ class Player final : public Creature, public Cylinder, public Bankable { } } void sendHouseWindow(const std::shared_ptr &house, uint32_t listId) const; - void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) { + void sendCreatePrivateChannel(uint16_t channelId, const std::string &channelName) const { if (client) { client->sendCreatePrivateChannel(channelId, channelName); } } void sendClosePrivate(uint16_t channelId); void sendIcons(); - void sendIconBakragore(const IconBakragore icon); + void sendIconBakragore(IconBakragore icon) const; void removeBakragoreIcons(); void removeBakragoreIcon(const IconBakragore icon); void sendClientCheck() const { @@ -1500,7 +1500,7 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendCloseShop(); } } - void sendMarketEnter(uint32_t depotId); + void sendMarketEnter(uint32_t depotId) const; void sendMarketLeave() { inMarket = false; if (client) { @@ -1547,22 +1547,22 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendCloseTrade(); } } - void sendWorldLight(LightInfo lightInfo) { + void sendWorldLight(LightInfo lightInfo) const { if (client) { client->sendWorldLight(lightInfo); } } - void sendTibiaTime(int32_t time) { + void sendTibiaTime(int32_t time) const { if (client) { client->sendTibiaTime(time); } } - void sendChannelsDialog() { + void sendChannelsDialog() const { if (client) { client->sendChannelsDialog(); } } - void sendOpenPrivateChannel(const std::string &receiver) { + void sendOpenPrivateChannel(const std::string &receiver) const { if (client) { client->sendOpenPrivateChannel(receiver); } @@ -1572,16 +1572,16 @@ class Player final : public Creature, public Cylinder, public Bankable { client->sendExperienceTracker(rawExp, finalExp); } } - void sendOutfitWindow() { + void sendOutfitWindow() const { if (client) { client->sendOutfitWindow(); } } // Imbuements - void onApplyImbuement(Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm); + void onApplyImbuement(const Imbuement* imbuement, const std::shared_ptr &item, uint8_t slot, bool protectionCharm); void onClearImbuement(const std::shared_ptr &item, uint8_t slot); void openImbuementWindow(const std::shared_ptr &item); - void sendImbuementResult(const std::string &message) { + void sendImbuementResult(const std::string &message) const { if (client) { client->sendImbuementResult(message); } @@ -1591,104 +1591,104 @@ class Player final : public Creature, public Cylinder, public Bankable { client->closeImbuementWindow(); } } - void sendPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos) { + void sendPodiumWindow(const std::shared_ptr &podium, const Position &position, uint16_t itemId, uint8_t stackpos) const { if (client) { client->sendPodiumWindow(podium, position, itemId, stackpos); } } - void sendCloseContainer(uint8_t cid) { + void sendCloseContainer(uint8_t cid) const { if (client) { client->sendCloseContainer(cid); } } - void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers) { + void sendChannel(uint16_t channelId, const std::string &channelName, const UsersMap* channelUsers, const InvitedMap* invitedUsers) const { if (client) { client->sendChannel(channelId, channelName, channelUsers, invitedUsers); } } - void sendTutorial(uint8_t tutorialId) { + void sendTutorial(uint8_t tutorialId) const { if (client) { client->sendTutorial(tutorialId); } } - void sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc) { + void sendAddMarker(const Position &pos, uint8_t markType, const std::string &desc) const { if (client) { client->sendAddMarker(pos, markType, desc); } } - void sendItemInspection(uint16_t itemId, uint8_t itemCount, const std::shared_ptr &item, bool cyclopedia) { + void sendItemInspection(uint16_t itemId, uint8_t itemCount, const std::shared_ptr &item, bool cyclopedia) const { if (client) { client->sendItemInspection(itemId, itemCount, item, cyclopedia); } } - void sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode) { + void sendCyclopediaCharacterNoData(CyclopediaCharacterInfoType_t characterInfoType, uint8_t errorCode) const { if (client) { client->sendCyclopediaCharacterNoData(characterInfoType, errorCode); } } - void sendCyclopediaCharacterBaseInformation() { + void sendCyclopediaCharacterBaseInformation() const { if (client) { client->sendCyclopediaCharacterBaseInformation(); } } - void sendCyclopediaCharacterGeneralStats() { + void sendCyclopediaCharacterGeneralStats() const { if (client) { client->sendCyclopediaCharacterGeneralStats(); } } - void sendCyclopediaCharacterCombatStats() { + void sendCyclopediaCharacterCombatStats() const { if (client) { client->sendCyclopediaCharacterCombatStats(); } } - void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries) { + void sendCyclopediaCharacterRecentDeaths(uint16_t page, uint16_t pages, const std::vector &entries) const { if (client) { client->sendCyclopediaCharacterRecentDeaths(page, pages, entries); } } - void sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries) { + void sendCyclopediaCharacterRecentPvPKills(uint16_t page, uint16_t pages, const std::vector &entries) const { if (client) { client->sendCyclopediaCharacterRecentPvPKills(page, pages, entries); } } - void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked); - void sendCyclopediaCharacterItemSummary(const ItemsTierCountList &inventoryItems, const ItemsTierCountList &storeInboxItems, const StashItemList &supplyStashItems, const ItemsTierCountList &depotBoxItems, const ItemsTierCountList &inboxItems) { + void sendCyclopediaCharacterAchievements(uint16_t secretsUnlocked, const std::vector> &achievementsUnlocked) const; + void sendCyclopediaCharacterItemSummary(const ItemsTierCountList &inventoryItems, const ItemsTierCountList &storeInboxItems, const StashItemList &supplyStashItems, const ItemsTierCountList &depotBoxItems, const ItemsTierCountList &inboxItems) const { if (client) { client->sendCyclopediaCharacterItemSummary(inventoryItems, storeInboxItems, supplyStashItems, depotBoxItems, inboxItems); } } - void sendCyclopediaCharacterOutfitsMounts() { + void sendCyclopediaCharacterOutfitsMounts() const { if (client) { client->sendCyclopediaCharacterOutfitsMounts(); } } - void sendCyclopediaCharacterStoreSummary() { + void sendCyclopediaCharacterStoreSummary() const { if (client) { client->sendCyclopediaCharacterStoreSummary(); } } - void sendCyclopediaCharacterInspection() { + void sendCyclopediaCharacterInspection() const { if (client) { client->sendCyclopediaCharacterInspection(); } } - void sendCyclopediaCharacterBadges() { + void sendCyclopediaCharacterBadges() const { if (client) { client->sendCyclopediaCharacterBadges(); } } - void sendCyclopediaCharacterTitles() { + void sendCyclopediaCharacterTitles() const { if (client) { client->sendCyclopediaCharacterTitles(); } } - void sendHighscoresNoData() { + void sendHighscoresNoData() const { if (client) { client->sendHighscoresNoData(); } } - void sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages, uint32_t updateTimer) { + void sendHighscores(const std::vector &characters, uint8_t categoryId, uint32_t vocationId, uint16_t page, uint16_t pages, uint32_t updateTimer) const { if (client) { client->sendHighscores(characters, categoryId, vocationId, page, pages, updateTimer); } @@ -1702,17 +1702,17 @@ class Player final : public Creature, public Cylinder, public Bankable { void resetAsyncOngoingTask(uint64_t flags) { asyncOngoingTasks &= ~(flags); } - void sendEnterWorld() { + void sendEnterWorld() const { if (client) { client->sendEnterWorld(); } } - void sendFightModes() { + void sendFightModes() const { if (client) { client->sendFightModes(); } } - void sendNetworkMessage(const NetworkMessage &message) { + void sendNetworkMessage(const NetworkMessage &message) const { if (client) { client->writeToOutputBuffer(message); } @@ -1722,13 +1722,13 @@ class Player final : public Creature, public Cylinder, public Bankable { lastPong = OTSYS_TIME(); } - void sendOpenStash(bool isNpc = false) { + void sendOpenStash(bool isNpc = false) const { if (client && ((getLastDepotId() != -1) || isNpc)) { client->sendOpenStash(); } } - void sendTakeScreenshot(Screenshot_t screenshotType) { + void sendTakeScreenshot(Screenshot_t screenshotType) const { if (client) { client->sendTakeScreenshot(screenshotType); } @@ -1736,8 +1736,8 @@ class Player final : public Creature, public Cylinder, public Bankable { void onThink(uint32_t interval) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void setNextAction(int64_t time) { if (time > nextAction) { @@ -1783,7 +1783,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void forgetInstantSpell(const std::string &spellName); bool hasLearnedInstantSpell(const std::string &spellName) const; - void updateRegeneration(); + void updateRegeneration() const; void setScheduledSaleUpdate(bool scheduled) { scheduledSaleUpdate = scheduled; @@ -1801,7 +1801,7 @@ class Player final : public Creature, public Cylinder, public Bankable { inEventMovePush = b; } - bool walkExhausted() { + bool walkExhausted() const { if (hasCondition(CONDITION_PARALYZE)) { return lastWalking > OTSYS_TIME(); } @@ -1879,11 +1879,11 @@ class Player final : public Creature, public Cylinder, public Bankable { return false; } - auto it = std::find(quickLootListItemIds.begin(), quickLootListItemIds.end(), item->getID()); + const auto &it = std::ranges::find(quickLootListItemIds, item->getID()); return it != quickLootListItemIds.end(); } - bool updateKillTracker(const std::shared_ptr &corpse, const std::string &playerName, const Outfit_t creatureOutfit) const { + bool updateKillTracker(const std::shared_ptr &corpse, const std::string &playerName, const Outfit_t &creatureOutfit) const { if (client) { client->sendKillTrackerUpdate(corpse, playerName, creatureOutfit); return true; @@ -1902,28 +1902,28 @@ class Player final : public Creature, public Cylinder, public Bankable { void updateSupplyTracker(const std::shared_ptr &item); void updateImpactTracker(CombatType_t type, int32_t amount) const; - void updateInputAnalyzer(CombatType_t type, int32_t amount, const std::string &target) { + void updateInputAnalyzer(CombatType_t type, int32_t amount, const std::string &target) const { if (client) { client->sendUpdateInputAnalyzer(type, amount, target); } } - void createLeaderTeamFinder(NetworkMessage &msg) { + void createLeaderTeamFinder(NetworkMessage &msg) const { if (client) { client->createLeaderTeamFinder(msg); } } - void sendLeaderTeamFinder(bool reset) { + void sendLeaderTeamFinder(bool reset) const { if (client) { client->sendLeaderTeamFinder(reset); } } - void sendTeamFinderList() { + void sendTeamFinderList() const { if (client) { client->sendTeamFinderList(); } } - void sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) { + void sendCreatureHelpers(uint32_t creatureId, uint16_t helpers) const { if (client) { client->sendCreatureHelpers(creatureId, helpers); } @@ -2158,7 +2158,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } const std::unique_ptr &getPreySlotById(PreySlot_t slotid) { - if (auto it = std::find_if(preys.begin(), preys.end(), [slotid](const std::unique_ptr &preyIt) { + if (const auto &it = std::ranges::find_if(preys, [slotid](const std::unique_ptr &preyIt) { return preyIt->id == slotid; }); it != preys.end()) { @@ -2225,7 +2225,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return PreySlotNull; } - if (auto it = std::find_if(preys.begin(), preys.end(), [raceId](const std::unique_ptr &it) { + if (const auto &it = std::ranges::find_if(preys, [raceId](const std::unique_ptr &it) { return it->selectedRaceId == raceId; }); it != preys.end()) { @@ -2256,7 +2256,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } const std::unique_ptr &getTaskHuntingSlotById(PreySlot_t slotid) { - if (auto it = std::find_if(taskHunting.begin(), taskHunting.end(), [slotid](const std::unique_ptr &itTask) { + if (const auto &it = std::ranges::find_if(taskHunting, [slotid](const std::unique_ptr &itTask) { return itTask->id == slotid; }); it != taskHunting.end()) { @@ -2269,12 +2269,12 @@ class Player final : public Creature, public Cylinder, public Bankable { std::vector getTaskHuntingBlackList() const { std::vector rt; - std::for_each(taskHunting.begin(), taskHunting.end(), [&rt](const std::unique_ptr &slot) { + std::ranges::for_each(taskHunting, [&rt](const std::unique_ptr &slot) { if (slot->isOccupied()) { - rt.push_back(slot->selectedRaceId); + rt.emplace_back(slot->selectedRaceId); } else { - std::for_each(slot->raceIdList.begin(), slot->raceIdList.end(), [&rt](uint16_t raceId) { - rt.push_back(raceId); + std::ranges::for_each(slot->raceIdList, [&rt](uint16_t raceId) { + rt.emplace_back(raceId); }); } }); @@ -2325,7 +2325,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return TaskHuntingSlotNull; } - if (auto it = std::find_if(taskHunting.begin(), taskHunting.end(), [raceId](const std::unique_ptr &itTask) { + if (const auto &it = std::ranges::find_if(taskHunting, [raceId](const std::unique_ptr &itTask) { return itTask->selectedRaceId == raceId; }); it != taskHunting.end()) { @@ -2380,7 +2380,7 @@ class Player final : public Creature, public Cylinder, public Bankable { SpeakClasses type, const std::string &text, bool ghostMode, - Spectators* spectatorsPtr = nullptr, + const Spectators* spectatorsPtr = nullptr, const Position* pos = nullptr ); @@ -2516,7 +2516,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } } - void sendBosstiaryEntryChanged(uint32_t bossid) { + void sendBosstiaryEntryChanged(uint32_t bossid) const { if (client) { client->sendBosstiaryEntryChanged(bossid); } @@ -2533,13 +2533,12 @@ class Player final : public Creature, public Cylinder, public Bankable { ******************************************************************************/ // Parser void parseAttackRecvHazardSystem(CombatDamage &damage, const std::shared_ptr &monster); - void parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster); + void parseAttackDealtHazardSystem(CombatDamage &damage, const std::shared_ptr &monster) const; // Points increase: void setHazardSystemPoints(int32_t amount); // Points get: uint16_t getHazardSystemPoints() const { - int32_t points = 0; - points = getStorageValue(STORAGEVALUE_HAZARDCOUNT); + const int32_t points = getStorageValue(STORAGEVALUE_HAZARDCOUNT); if (points <= 0) { return 0; } @@ -2680,7 +2679,7 @@ class Player final : public Creature, public Cylinder, public Bankable { */ void updateInventoryImbuement(); - void setNextWalkActionTask(std::shared_ptr task); + void setNextWalkActionTask(const std::shared_ptr &task); void setNextWalkTask(const std::shared_ptr &task); void setNextActionTask(const std::shared_ptr &task, bool resetIdleTime = true); void setNextActionPushTask(const std::shared_ptr &task); @@ -2689,7 +2688,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void death(std::shared_ptr lastHitCreature) override; bool spawn(); void despawn(); - bool dropCorpse(std::shared_ptr lastHitCreature, std::shared_ptr mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; + bool dropCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) override; // cylinder implementations @@ -2701,12 +2700,12 @@ class Player final : public Creature, public Cylinder, public Bankable { void addThing(std::shared_ptr) override { } void addThing(int32_t index, std::shared_ptr thing) override; - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, std::shared_ptr thing) override; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, const std::shared_ptr &thing) override; - void removeThing(std::shared_ptr thing, uint32_t count) override; + void removeThing(const std::shared_ptr &thing, uint32_t count) override; - int32_t getThingIndex(std::shared_ptr thing) const override; + int32_t getThingIndex(const std::shared_ptr &thing) const override; size_t getFirstIndex() const override; size_t getLastIndex() const override; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const override; @@ -2721,8 +2720,8 @@ class Player final : public Creature, public Cylinder, public Bankable { std::shared_ptr getForgeItemFromId(uint16_t itemId, uint8_t tier) const; std::shared_ptr getThing(size_t index) const override; - void internalAddThing(std::shared_ptr thing) override; - void internalAddThing(uint32_t index, std::shared_ptr thing) override; + void internalAddThing(const std::shared_ptr &thing) override; + void internalAddThing(uint32_t index, const std::shared_ptr &thing) override; void addHuntingTaskKill(const std::shared_ptr &mType); void addBestiaryKill(const std::shared_ptr &mType); @@ -3068,7 +3067,7 @@ class Player final : public Creature, public Cylinder, public Bankable { double_t calculateDamageReduction(double_t currentTotal, int16_t resistance) const; void removeEmptyRewards(); - bool hasOtherRewardContainerOpen(std::shared_ptr container) const; + bool hasOtherRewardContainerOpen(const std::shared_ptr &container) const; void checkAndShowBlessingMessage(); diff --git a/src/creatures/players/storages/storages.cpp b/src/creatures/players/storages/storages.cpp index 2ec4bde5543..886db3e61e1 100644 --- a/src/creatures/players/storages/storages.cpp +++ b/src/creatures/players/storages/storages.cpp @@ -11,6 +11,7 @@ #include "creatures/players/storages/storages.hpp" #include "config/configmanager.hpp" +#include "config/config_enums.hpp" #include "lib/di/container.hpp" Storages &Storages::getInstance() { diff --git a/src/creatures/players/vip/player_vip.hpp b/src/creatures/players/vip/player_vip.hpp index 18e661ef78d..09a20dd1788 100644 --- a/src/creatures/players/vip/player_vip.hpp +++ b/src/creatures/players/vip/player_vip.hpp @@ -9,6 +9,8 @@ #pragma once +#include + #include "creatures/creatures_definitions.hpp" class Player; @@ -20,8 +22,8 @@ struct VIPGroup { phmap::flat_hash_set vipGroupGuids; VIPGroup() = default; - VIPGroup(uint8_t id, const std::string &name, bool customizable) : - id(id), name(name), customizable(customizable) { } + VIPGroup(uint8_t id, std::string name, bool customizable) : + id(id), name(std::move(name)), customizable(customizable) { } }; class PlayerVIP { diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index 91b644e5cbd..ee0f68de332 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -104,22 +104,22 @@ void Teleport::addThing(int32_t, std::shared_ptr thing) { } } -void Teleport::updateThing(std::shared_ptr, uint16_t, uint32_t) { +void Teleport::updateThing(const std::shared_ptr &, uint16_t, uint32_t) { // } -void Teleport::replaceThing(uint32_t, std::shared_ptr) { +void Teleport::replaceThing(uint32_t, const std::shared_ptr &) { // } -void Teleport::removeThing(std::shared_ptr, uint32_t) { +void Teleport::removeThing(const std::shared_ptr &, uint32_t) { // } -void Teleport::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void Teleport::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void Teleport::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Teleport::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/game/movement/teleport.hpp b/src/game/movement/teleport.hpp index da647e9c486..1cd2b5fdae6 100644 --- a/src/game/movement/teleport.hpp +++ b/src/game/movement/teleport.hpp @@ -46,13 +46,13 @@ class Teleport final : public Item, public Cylinder { void addThing(std::shared_ptr thing) override; void addThing(int32_t index, std::shared_ptr thing) override; - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, std::shared_ptr thing) override; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, const std::shared_ptr &thing) override; - void removeThing(std::shared_ptr thing, uint32_t count) override; + void removeThing(const std::shared_ptr &thing, uint32_t count) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; private: Position destPos; diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index c4bf4a23c37..2ff29c8a872 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -717,7 +717,7 @@ void Container::addItemBack(const std::shared_ptr &item) { } } -void Container::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) { +void Container::updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -739,7 +739,7 @@ void Container::updateThing(std::shared_ptr thing, uint16_t itemId, uint3 } } -void Container::replaceThing(uint32_t index, std::shared_ptr thing) { +void Container::replaceThing(uint32_t index, const std::shared_ptr &thing) { const auto item = thing->getItem(); if (!item) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -762,7 +762,7 @@ void Container::replaceThing(uint32_t index, std::shared_ptr thing) { replacedItem->resetParent(); } -void Container::removeThing(std::shared_ptr thing, uint32_t count) { +void Container::removeThing(const std::shared_ptr &thing, uint32_t count) { const auto item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -796,7 +796,7 @@ void Container::removeThing(std::shared_ptr thing, uint32_t count) { } } -int32_t Container::getThingIndex(std::shared_ptr thing) const { +int32_t Container::getThingIndex(const std::shared_ptr &thing) const { int32_t index = 0; for (const std::shared_ptr &item : itemlist) { if (item == thing) { @@ -850,7 +850,7 @@ ItemVector Container::getItems(bool recursive /*= false*/) { return containerItems; } -void Container::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void Container::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { std::shared_ptr topParent = getTopParent(); if (topParent->getCreature()) { topParent->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); @@ -864,7 +864,7 @@ void Container::postAddNotification(std::shared_ptr thing, std::shared_pt } } -void Container::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Container::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { std::shared_ptr topParent = getTopParent(); if (topParent->getCreature()) { topParent->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); @@ -878,11 +878,11 @@ void Container::postRemoveNotification(std::shared_ptr thing, std::shared } } -void Container::internalAddThing(std::shared_ptr thing) { +void Container::internalAddThing(const std::shared_ptr &thing) { internalAddThing(0, thing); } -void Container::internalAddThing(uint32_t, std::shared_ptr thing) { +void Container::internalAddThing(uint32_t, const std::shared_ptr &thing) { if (!thing) { return; } @@ -914,8 +914,8 @@ void Container::stopDecaying() { uint16_t Container::getFreeSlots() { uint16_t counter = std::max(0, capacity() - size()); - for (const std::shared_ptr &item : itemlist) { - if (std::shared_ptr container = item->getContainer()) { + for (const auto &item : itemlist) { + if (const auto &container = item->getContainer()) { counter += std::max(0, container->getFreeSlots()); } } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index 77c5aedd813..4780bf27646 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -147,12 +147,12 @@ class Container : public Item, public Cylinder { void addThing(int32_t index, std::shared_ptr thing) final; void addItemBack(const std::shared_ptr &item); - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) final; - void replaceThing(uint32_t index, std::shared_ptr thing) override final; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) final; + void replaceThing(uint32_t index, const std::shared_ptr &thing) override final; - void removeThing(std::shared_ptr thing, uint32_t count) final; + void removeThing(const std::shared_ptr &thing, uint32_t count) final; - int32_t getThingIndex(std::shared_ptr thing) const final; + int32_t getThingIndex(const std::shared_ptr &thing) const final; size_t getFirstIndex() const final; size_t getLastIndex() const final; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const final; @@ -161,11 +161,11 @@ class Container : public Item, public Cylinder { ItemVector getItems(bool recursive = false); - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void internalAddThing(std::shared_ptr thing) final; - void internalAddThing(uint32_t index, std::shared_ptr thing) final; + void internalAddThing(const std::shared_ptr &thing) final; + void internalAddThing(uint32_t index, const std::shared_ptr &thing) final; void startDecaying() override; void stopDecaying() override; diff --git a/src/items/containers/depot/depotchest.cpp b/src/items/containers/depot/depotchest.cpp index a1547b3a508..579366d122b 100644 --- a/src/items/containers/depot/depotchest.cpp +++ b/src/items/containers/depot/depotchest.cpp @@ -56,14 +56,14 @@ ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr &th return Container::queryAdd(index, thing, count, flags, actor); } -void DepotChest::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void DepotChest::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotChest::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void DepotChest::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); diff --git a/src/items/containers/depot/depotchest.hpp b/src/items/containers/depot/depotchest.hpp index 6b64ca2b897..a1693af3b86 100644 --- a/src/items/containers/depot/depotchest.hpp +++ b/src/items/containers/depot/depotchest.hpp @@ -23,8 +23,8 @@ class DepotChest final : public Container { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; bool isDepotChest() const override { return true; diff --git a/src/items/containers/depot/depotlocker.cpp b/src/items/containers/depot/depotlocker.cpp index ef8acdf2217..b9b77fab8f0 100644 --- a/src/items/containers/depot/depotlocker.cpp +++ b/src/items/containers/depot/depotlocker.cpp @@ -28,14 +28,14 @@ ReturnValue DepotLocker::queryAdd(int32_t, const std::shared_ptr &, uint3 return RETURNVALUE_NOTENOUGHROOM; } -void DepotLocker::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void DepotLocker::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { auto parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void DepotLocker::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void DepotLocker::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { auto parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postRemoveNotification(thing, newParent, index, LINK_PARENT); diff --git a/src/items/containers/depot/depotlocker.hpp b/src/items/containers/depot/depotlocker.hpp index d572e3b60b8..4079091c22d 100644 --- a/src/items/containers/depot/depotlocker.hpp +++ b/src/items/containers/depot/depotlocker.hpp @@ -35,8 +35,8 @@ class DepotLocker final : public Container { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; bool canRemove() const override { return false; diff --git a/src/items/containers/inbox/inbox.cpp b/src/items/containers/inbox/inbox.cpp index 797c4f168ec..e0ab1e3ab29 100644 --- a/src/items/containers/inbox/inbox.cpp +++ b/src/items/containers/inbox/inbox.cpp @@ -52,14 +52,14 @@ ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr &thing, uint32 return RETURNVALUE_NOERROR; } -void Inbox::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void Inbox::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void Inbox::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Inbox::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); diff --git a/src/items/containers/inbox/inbox.hpp b/src/items/containers/inbox/inbox.hpp index 79eb126edc8..6d3423f1824 100644 --- a/src/items/containers/inbox/inbox.hpp +++ b/src/items/containers/inbox/inbox.hpp @@ -22,8 +22,8 @@ class Inbox final : public Container { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; bool isInbox() const override { return true; diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index b0714b87e7b..ca019a7f7b8 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -51,23 +51,23 @@ void Mailbox::addThing(int32_t, std::shared_ptr thing) { } } -void Mailbox::updateThing(std::shared_ptr, uint16_t, uint32_t) { +void Mailbox::updateThing(const std::shared_ptr &, uint16_t, uint32_t) { // } -void Mailbox::replaceThing(uint32_t, std::shared_ptr) { +void Mailbox::replaceThing(uint32_t, const std::shared_ptr &) { // } -void Mailbox::removeThing(std::shared_ptr, uint32_t) { +void Mailbox::removeThing(const std::shared_ptr &, uint32_t) { // } -void Mailbox::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void Mailbox::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void Mailbox::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Mailbox::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index 03f8506b411..ffa9b408b6a 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -34,13 +34,13 @@ class Mailbox final : public Item, public Cylinder { void addThing(std::shared_ptr thing) override; void addThing(int32_t index, std::shared_ptr thing) override; - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, std::shared_ptr thing) override; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, const std::shared_ptr &thing) override; - void removeThing(std::shared_ptr thing, uint32_t count) override; + void removeThing(const std::shared_ptr &thing, uint32_t count) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; private: bool getReceiver(const std::shared_ptr &item, std::string &name) const; diff --git a/src/items/containers/rewards/reward.cpp b/src/items/containers/rewards/reward.cpp index fec8b6884df..f1f9424a128 100644 --- a/src/items/containers/rewards/reward.cpp +++ b/src/items/containers/rewards/reward.cpp @@ -39,14 +39,14 @@ ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr &thing, uint3 return RETURNVALUE_NOERROR; } -void Reward::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void Reward::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void Reward::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Reward::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { std::shared_ptr localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); diff --git a/src/items/containers/rewards/reward.hpp b/src/items/containers/rewards/reward.hpp index 1ab3c8f9b70..61a589a73bd 100644 --- a/src/items/containers/rewards/reward.hpp +++ b/src/items/containers/rewards/reward.hpp @@ -22,8 +22,8 @@ class Reward : public Container { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) final; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; // overrides bool canRemove() const final { diff --git a/src/items/containers/rewards/rewardchest.cpp b/src/items/containers/rewards/rewardchest.cpp index c9bb8112f90..dc1bac1d708 100644 --- a/src/items/containers/rewards/rewardchest.cpp +++ b/src/items/containers/rewards/rewardchest.cpp @@ -26,14 +26,14 @@ ReturnValue RewardChest::queryAdd(int32_t, const std::shared_ptr &, uint3 return RETURNVALUE_NOERROR; } -void RewardChest::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void RewardChest::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { auto parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postAddNotification(thing, oldParent, index, LINK_PARENT); } } -void RewardChest::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void RewardChest::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { auto parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postRemoveNotification(thing, newParent, index, LINK_PARENT); diff --git a/src/items/containers/rewards/rewardchest.hpp b/src/items/containers/rewards/rewardchest.hpp index 2960128eb75..7de4854d910 100644 --- a/src/items/containers/rewards/rewardchest.hpp +++ b/src/items/containers/rewards/rewardchest.hpp @@ -22,8 +22,8 @@ class RewardChest final : public Container { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) final; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; bool canRemove() const final { return false; diff --git a/src/items/cylinder.cpp b/src/items/cylinder.cpp index 0636e5ff34c..3c37c17348c 100644 --- a/src/items/cylinder.cpp +++ b/src/items/cylinder.cpp @@ -13,7 +13,7 @@ std::shared_ptr VirtualCylinder::virtualCylinder = std::make_shared(); -int32_t Cylinder::getThingIndex(std::shared_ptr) const { +int32_t Cylinder::getThingIndex(const std::shared_ptr &) const { return -1; } @@ -37,11 +37,11 @@ std::shared_ptr Cylinder::getThing(size_t) const { return nullptr; } -void Cylinder::internalAddThing(std::shared_ptr) { +void Cylinder::internalAddThing(const std::shared_ptr &) { // } -void Cylinder::internalAddThing(uint32_t, std::shared_ptr) { +void Cylinder::internalAddThing(uint32_t, const std::shared_ptr &) { // } diff --git a/src/items/cylinder.hpp b/src/items/cylinder.hpp index f6c149dd589..4a352008904 100644 --- a/src/items/cylinder.hpp +++ b/src/items/cylinder.hpp @@ -84,21 +84,21 @@ class Cylinder : virtual public Thing { * \param itemId is the new item id * \param count is the new count value */ - virtual void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) = 0; + virtual void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) = 0; /** * Replace an object with a new * \param index is the position to change (inventory slot/container position) * \param thing is the object to update */ - virtual void replaceThing(uint32_t index, std::shared_ptr thing) = 0; + virtual void replaceThing(uint32_t index, const std::shared_ptr &thing) = 0; /** * Remove an object * \param thing is the object to delete * \param count is the new count value */ - virtual void removeThing(std::shared_ptr thing, uint32_t count) = 0; + virtual void removeThing(const std::shared_ptr &thing, uint32_t count) = 0; /** * Is sent after an operation (move/add) to update internal values @@ -106,7 +106,7 @@ class Cylinder : virtual public Thing { * \param index is the objects new index value * \param link holds the relation the object has to the cylinder */ - virtual void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) = 0; + virtual void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, const CylinderLink_t link = LINK_OWNER) = 0; /** * Is sent after an operation (move/remove) to update internal values @@ -114,14 +114,14 @@ class Cylinder : virtual public Thing { * \param index is the previous index of the removed object * \param link holds the relation the object has to the cylinder */ - virtual void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) = 0; + virtual void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) = 0; /** * Gets the index of an object * \param thing the object to get the index value from * \returns the index of the object, returns -1 if not found */ - virtual int32_t getThingIndex(std::shared_ptr thing) const; + virtual int32_t getThingIndex(const std::shared_ptr &thing) const; /** * Returns the first index @@ -160,14 +160,14 @@ class Cylinder : virtual public Thing { * Adds an object to the cylinder without sending to the client(s) * \param thing is the object to add */ - virtual void internalAddThing(std::shared_ptr thing); + virtual void internalAddThing(const std::shared_ptr &thing); /** * Adds an object to the cylinder without sending to the client(s) * \param thing is the object to add * \param index points to the destination index (inventory slot/container position) */ - virtual void internalAddThing(uint32_t index, std::shared_ptr thing); + virtual void internalAddThing(uint32_t index, const std::shared_ptr &thing); virtual void startDecaying(); }; @@ -191,12 +191,12 @@ class VirtualCylinder final : public Cylinder { virtual void addThing(std::shared_ptr) override { } virtual void addThing(int32_t, std::shared_ptr) override { } - virtual void updateThing(std::shared_ptr, uint16_t, uint32_t) override { } - virtual void replaceThing(uint32_t, std::shared_ptr) override { } - virtual void removeThing(std::shared_ptr, uint32_t) override { } + virtual void updateThing(const std::shared_ptr &, uint16_t, uint32_t) override { } + virtual void replaceThing(uint32_t, const std::shared_ptr &) override { } + virtual void removeThing(const std::shared_ptr &, uint32_t) override { } - virtual void postAddNotification(std::shared_ptr, std::shared_ptr, int32_t, CylinderLink_t = LINK_OWNER) override { } - virtual void postRemoveNotification(std::shared_ptr, std::shared_ptr, int32_t, CylinderLink_t = LINK_OWNER) override { } + virtual void postAddNotification(const std::shared_ptr &, const std::shared_ptr &, int32_t, CylinderLink_t = LINK_OWNER) override { } + virtual void postRemoveNotification(const std::shared_ptr &, const std::shared_ptr &, int32_t, CylinderLink_t = LINK_OWNER) override { } bool isPushable() override { return false; diff --git a/src/items/items.hpp b/src/items/items.hpp index 721c3cdc0f5..11ef019de9f 100644 --- a/src/items/items.hpp +++ b/src/items/items.hpp @@ -10,6 +10,7 @@ #pragma once #include "config/configmanager.hpp" +#include "config/config_enums.hpp" #include "utils/utils_definitions.hpp" #include "declarations.hpp" #include "game/movement/position.hpp" diff --git a/src/items/tile.cpp b/src/items/tile.cpp index b8f7af486fe..76226211dba 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -1096,7 +1096,7 @@ void Tile::addThing(int32_t, std::shared_ptr thing) { onAddTileItem(item); } -void Tile::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) { +void Tile::updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) { int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -1116,7 +1116,7 @@ void Tile::updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t c onUpdateTileItem(item, oldType, item, newType); } -void Tile::replaceThing(uint32_t index, std::shared_ptr thing) { +void Tile::replaceThing(uint32_t index, const std::shared_ptr &thing) { int32_t pos = index; const auto item = thing->getItem(); @@ -1187,7 +1187,7 @@ void Tile::replaceThing(uint32_t index, std::shared_ptr thing) { } } -void Tile::removeThing(std::shared_ptr thing, uint32_t count) { +void Tile::removeThing(const std::shared_ptr &thing, uint32_t count) { std::shared_ptr creature = thing->getCreature(); if (creature) { CreatureVector* creatures = getCreatures(); @@ -1277,7 +1277,7 @@ void Tile::removeCreature(const std::shared_ptr &creature) { removeThing(creature, 0); } -int32_t Tile::getThingIndex(std::shared_ptr thing) const { +int32_t Tile::getThingIndex(const std::shared_ptr &thing) const { int32_t n = -1; if (ground) { if (ground == thing) { @@ -1488,7 +1488,7 @@ std::shared_ptr Tile::getThing(size_t index) const { return nullptr; } -void Tile::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { +void Tile::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { for (const auto &spectator : Spectators().find(getPosition(), true)) { spectator->getPlayer()->postAddNotification(thing, oldParent, index, LINK_NEAR); } @@ -1529,7 +1529,7 @@ void Tile::postAddNotification(std::shared_ptr thing, std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void Tile::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { auto spectators = Spectators().find(getPosition(), true); if (getThingCount() > 8) { @@ -1552,7 +1552,7 @@ void Tile::postRemoveNotification(std::shared_ptr thing, std::shared_ptr< } } -void Tile::internalAddThing(std::shared_ptr thing) { +void Tile::internalAddThing(const std::shared_ptr &thing) { internalAddThing(0, thing); if (!thing || !thing->getParent()) { return; @@ -1572,7 +1572,7 @@ void Tile::internalAddThing(std::shared_ptr thing) { } } -void Tile::internalAddThing(uint32_t, std::shared_ptr thing) { +void Tile::internalAddThing(uint32_t, const std::shared_ptr &thing) { if (!thing) { return; } diff --git a/src/items/tile.hpp b/src/items/tile.hpp index 777a846d783..c2bf20a38f6 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -104,7 +104,7 @@ class Tile : public Cylinder, public SharedObject { static const std::shared_ptr &nullptr_tile; Tile(uint16_t x, uint16_t y, uint8_t z) : tilePos(x, y, z) { } - ~Tile() override {}; + ~Tile() override = default; // non-copyable Tile(const Tile &) = delete; @@ -218,24 +218,24 @@ class Tile : public Cylinder, public SharedObject { void addThing(int32_t index, std::shared_ptr thing) override; void updateTileFlags(const std::shared_ptr &item); - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) final; - void replaceThing(uint32_t index, std::shared_ptr thing) final; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) final; + void replaceThing(uint32_t index, const std::shared_ptr &thing) final; - void removeThing(std::shared_ptr thing, uint32_t count) final; + void removeThing(const std::shared_ptr &thing, uint32_t count) final; void removeCreature(const std::shared_ptr &creature); - int32_t getThingIndex(std::shared_ptr thing) const final; + int32_t getThingIndex(const std::shared_ptr &thing) const final; size_t getFirstIndex() const final; size_t getLastIndex() const final; uint32_t getItemTypeCount(uint16_t itemId, int32_t subType = -1) const final; std::shared_ptr getThing(size_t index) const final; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void internalAddThing(std::shared_ptr thing) override; - void virtual internalAddThing(uint32_t index, std::shared_ptr thing) override; + void internalAddThing(const std::shared_ptr &thing) override; + void internalAddThing(uint32_t index, const std::shared_ptr &thing) override; const Position &getPosition() final { return tilePos; @@ -276,7 +276,7 @@ class Tile : public Cylinder, public SharedObject { std::shared_ptr ground = nullptr; Position tilePos; uint32_t flags = 0; - std::unordered_set> zones; + std::unordered_set> zones {}; }; // Used for walkable tiles, where there is high likeliness of diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index 4da1bc6a48d..0a0efc72aad 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -72,22 +72,22 @@ void TrashHolder::addThing(int32_t, std::shared_ptr thing) { } } -void TrashHolder::updateThing(std::shared_ptr, uint16_t, uint32_t) { +void TrashHolder::updateThing(const std::shared_ptr &, uint16_t, uint32_t) { // } -void TrashHolder::replaceThing(uint32_t, std::shared_ptr) { +void TrashHolder::replaceThing(uint32_t, const std::shared_ptr &) { // } -void TrashHolder::removeThing(std::shared_ptr, uint32_t) { +void TrashHolder::removeThing(const std::shared_ptr &, uint32_t) { // } -void TrashHolder::postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t) { +void TrashHolder::postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t) { getParent()->postAddNotification(thing, oldParent, index, LINK_PARENT); } -void TrashHolder::postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t) { +void TrashHolder::postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t) { getParent()->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/items/trashholder.hpp b/src/items/trashholder.hpp index 424ad5cd03e..2ea833fd808 100644 --- a/src/items/trashholder.hpp +++ b/src/items/trashholder.hpp @@ -34,11 +34,11 @@ class TrashHolder final : public Item, public Cylinder { void addThing(std::shared_ptr thing) override; void addThing(int32_t index, std::shared_ptr thing) override; - void updateThing(std::shared_ptr thing, uint16_t itemId, uint32_t count) override; - void replaceThing(uint32_t index, std::shared_ptr thing) override; + void updateThing(const std::shared_ptr &thing, uint16_t itemId, uint32_t count) override; + void replaceThing(uint32_t index, const std::shared_ptr &thing) override; - void removeThing(std::shared_ptr thing, uint32_t count) override; + void removeThing(const std::shared_ptr &thing, uint32_t count) override; - void postAddNotification(std::shared_ptr thing, std::shared_ptr oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - void postRemoveNotification(std::shared_ptr thing, std::shared_ptr newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postAddNotification(const std::shared_ptr &thing, const std::shared_ptr &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr &thing, const std::shared_ptr &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; }; diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 7d580acec27..0064bd17b97 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -32,7 +32,7 @@ void HouseTile::addThing(int32_t index, std::shared_ptr thing) { } } -void HouseTile::internalAddThing(uint32_t index, std::shared_ptr thing) { +void HouseTile::internalAddThing(uint32_t index, const std::shared_ptr &thing) { Tile::internalAddThing(index, thing); if (!thing || !thing->getParent()) { diff --git a/src/map/house/housetile.hpp b/src/map/house/housetile.hpp index 1e7e5a1984d..69b17fa3482 100644 --- a/src/map/house/housetile.hpp +++ b/src/map/house/housetile.hpp @@ -25,7 +25,7 @@ class HouseTile final : public DynamicTile { ReturnValue queryRemove(const std::shared_ptr &thing, uint32_t count, uint32_t flags, std::shared_ptr actor = nullptr) override; void addThing(int32_t index, std::shared_ptr thing) override; - void virtual internalAddThing(uint32_t index, std::shared_ptr thing) override; + void internalAddThing(uint32_t index, const std::shared_ptr &thing) override; std::shared_ptr getHouse() override { return house; From 87f688d4759cacc8c1c25522c5a94e71fd2bff99 Mon Sep 17 00:00:00 2001 From: Beats Date: Sun, 1 Sep 2024 19:35:37 -0400 Subject: [PATCH 20/34] update --- src/account/account_repository_db.cpp | 2 +- src/creatures/appearance/outfit/outfit.hpp | 4 +- src/creatures/combat/condition.cpp | 25 +- src/creatures/combat/condition.hpp | 26 +- src/creatures/combat/spells.cpp | 131 +++++---- src/creatures/combat/spells.hpp | 26 +- src/creatures/interactions/chat.cpp | 138 +++++----- src/creatures/interactions/chat.hpp | 6 +- src/creatures/monsters/monster.cpp | 250 ++++++++++-------- src/creatures/monsters/monster.hpp | 6 +- .../monsters/spawns/spawn_monster.cpp | 36 +-- .../monsters/spawns/spawn_monster.hpp | 2 +- src/creatures/players/player.cpp | 14 +- src/game/game.cpp | 6 +- src/game/scheduling/task.hpp | 2 +- 15 files changed, 359 insertions(+), 315 deletions(-) diff --git a/src/account/account_repository_db.cpp b/src/account/account_repository_db.cpp index 678584208ad..cb9981e3e9b 100644 --- a/src/account/account_repository_db.cpp +++ b/src/account/account_repository_db.cpp @@ -122,7 +122,7 @@ bool AccountRepositoryDB::registerCoinsTransaction( const uint8_t &coinType, const std::string &description ) { - bool successful = g_database().executeQuery( + const bool successful = g_database().executeQuery( fmt::format( "INSERT INTO `coins_transactions` (`account_id`, `type`, `coin_type`, `amount`, `description`) VALUES ({}, {}, {}, {}, {})", id, diff --git a/src/creatures/appearance/outfit/outfit.hpp b/src/creatures/appearance/outfit/outfit.hpp index a0503045db0..bf1dbc319cb 100644 --- a/src/creatures/appearance/outfit/outfit.hpp +++ b/src/creatures/appearance/outfit/outfit.hpp @@ -15,8 +15,8 @@ struct OutfitEntry { constexpr explicit OutfitEntry(const uint16_t initLookType, const uint8_t initAddons) : lookType(initLookType), addons(initAddons) { } - uint16_t lookType; - uint8_t addons; + uint16_t lookType {}; + uint8_t addons {}; }; struct Outfit { diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index a946423577d..bcc93ae5d51 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -606,7 +606,7 @@ void ConditionAttributes::updatePercentStats(const std::shared_ptr &play } } -void ConditionAttributes::updateStats(const std::shared_ptr &player) { +void ConditionAttributes::updateStats(const std::shared_ptr &player) const { bool needUpdate = false; for (int32_t i = STAT_FIRST; i <= STAT_LAST; ++i) { @@ -634,7 +634,7 @@ void ConditionAttributes::updatePercentSkills(const std::shared_ptr &pla } } -void ConditionAttributes::updateSkills(const std::shared_ptr &player) { +void ConditionAttributes::updateSkills(const std::shared_ptr &player) const { bool needUpdateSkills = false; for (int32_t i = SKILL_FIRST; i <= SKILL_LAST; ++i) { @@ -705,7 +705,7 @@ void ConditionAttributes::updatePercentBuffs(const std::shared_ptr &cr } } -void ConditionAttributes::updateBuffs(const std::shared_ptr &creature) { +void ConditionAttributes::updateBuffs(const std::shared_ptr &creature) const { bool needUpdate = false; for (int32_t i = BUFF_FIRST; i <= BUFF_LAST; ++i) { if (buffs[i]) { @@ -1671,7 +1671,7 @@ bool ConditionDamage::getNextDamage(int32_t &damage) { return false; } -bool ConditionDamage::doDamage(const std::shared_ptr &creature, int32_t healthChange) { +bool ConditionDamage::doDamage(const std::shared_ptr &creature, int32_t healthChange) const { const auto &attacker = g_game().getPlayerByGUID(owner) ? g_game().getPlayerByGUID(owner)->getCreature() : g_game().getCreatureByID(owner); bool isPlayer = attacker && attacker->getPlayer(); if (creature->isSuppress(getType(), isPlayer)) { @@ -1830,7 +1830,7 @@ void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::lis /** * ConditionFeared */ -bool ConditionFeared::isStuck(std::shared_ptr creature, Position pos) const { +bool ConditionFeared::isStuck(const std::shared_ptr &creature, Position pos) const { return std::ranges::all_of(m_directionsVector, [&](Direction dir) { return !canWalkTo(creature, pos, dir); }); @@ -1848,12 +1848,15 @@ bool ConditionFeared::getRandomDirection(const std::shared_ptr &creatu DIRECTION_NORTHWEST }; - std::ranges::shuffle(directions.begin(), directions.end(), getRandomGenerator()); - for (Direction dir : directions) { - if (canWalkTo(creature, pos, dir)) { - this->fleeIndx = static_cast(dir); - return true; - } + std::ranges::shuffle(directions, getRandomGenerator()); + + const auto &it = std::ranges::find_if(directions, [&](Direction dir) { + return canWalkTo(creature, pos, dir); + }); + + if (it != directions.end()) { + this->fleeIndx = static_cast(*it); + return true; } return false; diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index 3fdadc26a77..c2432b5e594 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -154,20 +154,20 @@ class ConditionAttributes final : public ConditionGeneric { ConditionAttributes(ConditionId_t initId, ConditionType_t initType, int32_t initTicks, bool initBuff = false, uint32_t initSubId = 0) : ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } - bool startCondition(std::shared_ptr creature) final; - bool executeCondition(const std::shared_ptr &creature, int32_t interval) final; - void endCondition(std::shared_ptr creature) final; - void addCondition(std::shared_ptr creature, std::shared_ptr condition) final; + bool startCondition(std::shared_ptr creature) override; + bool executeCondition(const std::shared_ptr &creature, int32_t interval) override; + void endCondition(std::shared_ptr creature) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; - bool setParam(ConditionParam_t param, int32_t value) final; + bool setParam(ConditionParam_t param, int32_t value) override; - std::shared_ptr clone() const final { + std::shared_ptr clone() const override { return std::make_shared(*this); } // serialization - void serialize(PropWriteStream &propWriteStream) final; - bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) final; + void serialize(PropWriteStream &propWriteStream) override; + bool unserializeProp(ConditionAttr_t attr, PropStream &propStream) override; private: // Helpers @@ -202,10 +202,10 @@ class ConditionAttributes final : public ConditionGeneric { bool disableDefense = false; void updatePercentStats(const std::shared_ptr &player); - void updateStats(const std::shared_ptr &player); + void updateStats(const std::shared_ptr &player) const; void updatePercentSkills(const std::shared_ptr &player); - void updateSkills(const std::shared_ptr &player); - void updateBuffs(const std::shared_ptr &creature); + void updateSkills(const std::shared_ptr &player) const; + void updateBuffs(const std::shared_ptr &creature) const; // 12.72 mechanics void updatePercentAbsorbs(const std::shared_ptr &creature); @@ -358,7 +358,7 @@ class ConditionDamage final : public Condition { std::list damageList; bool getNextDamage(int32_t &damage); - bool doDamage(const std::shared_ptr &creature, int32_t healthChange); + bool doDamage(const std::shared_ptr &creature, int32_t healthChange) const; bool updateCondition(const std::shared_ptr &addCondition) override; }; @@ -386,7 +386,7 @@ class ConditionFeared final : public Condition { bool getFleeDirection(const std::shared_ptr &creature); bool getFleePath(const std::shared_ptr &creature, const Position &pos, std::vector &dirList); bool getRandomDirection(const std::shared_ptr &creature, Position pos); - bool isStuck(std::shared_ptr creature, Position pos) const; + bool isStuck(const std::shared_ptr &creature, Position pos) const; std::vector m_directionsVector { DIRECTION_NORTH, diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index dce79dadda8..f5cb2738523 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -24,12 +24,12 @@ Spells::Spells() = default; Spells::~Spells() = default; -TalkActionResult_t Spells::playerSaySpell(const std::shared_ptr &player, std::string &words) { - auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); +TalkActionResult_t Spells::playerSaySpell(const std::shared_ptr &player, std::string &words) const { + const auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); const auto &tile = player->getTile(); if (maxOnline > 1 && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE)) { auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT, __FUNCTION__); - auto accountPlayers = g_game().getPlayersByAccount(player->getAccount()); + const auto accountPlayers = g_game().getPlayersByAccount(player->getAccount()); int countOutsizePZ = 0; for (const auto &accountPlayer : accountPlayers) { if (accountPlayer == player || accountPlayer->isOffline()) { @@ -133,6 +133,7 @@ bool Spells::registerInstantLuaEvent(const std::shared_ptr &instan } // Register spell word in the map setInstantSpell(words, instant); + return true; } return false; @@ -141,8 +142,8 @@ bool Spells::registerInstantLuaEvent(const std::shared_ptr &instan bool Spells::registerRuneLuaEvent(const std::shared_ptr &rune) { if (rune) { uint16_t id = rune->getRuneItemId(); - auto result = runes.emplace(rune->getRuneItemId(), rune); - if (!result.second) { + const auto &[fst, snd] = runes.emplace(rune->getRuneItemId(), rune); + if (!snd) { g_logger().warn( "[{}] duplicate registered rune with id: {}, for script: {}", __FUNCTION__, @@ -150,31 +151,29 @@ bool Spells::registerRuneLuaEvent(const std::shared_ptr &rune) { rune->getScriptInterface()->getLoadingScriptName() ); } - return result.second; + return snd; } return false; } -std::list Spells::getSpellsByVocation(uint16_t vocationId) { +std::list Spells::getSpellsByVocation(uint16_t vocationId) const { std::list spellsList; - VocSpellMap vocSpells; - std::map::const_iterator vocSpellsIt; - for (const auto &it : instants) { - vocSpells = it.second->getVocMap(); - vocSpellsIt = vocSpells.find(vocationId); + for (const auto &[fst, snd] : instants) { + const VocSpellMap &vocSpells = snd->getVocMap(); + const auto &vocSpellsIt = vocSpells.find(vocationId); if (vocSpellsIt != vocSpells.end() && vocSpellsIt->second) { - spellsList.push_back(it.second->getSpellId()); + spellsList.emplace_back(snd->getSpellId()); } } return spellsList; } -std::shared_ptr Spells::getSpellByName(const std::string &name) { +std::shared_ptr Spells::getSpellByName(const std::string &name) const { std::shared_ptr spell = getRuneSpellByName(name); if (!spell) { spell = getInstantSpellByName(name); @@ -183,11 +182,11 @@ std::shared_ptr Spells::getSpellByName(const std::string &name) { } std::shared_ptr Spells::getRuneSpell(uint16_t id) { - auto it = runes.find(id); + const auto &it = runes.find(id); if (it == runes.end()) { - for (const auto &rune : runes) { - if (rune.second->getRuneItemId() == id) { - return rune.second; + for (const auto &[fst, snd] : runes) { + if (snd->getRuneItemId() == id) { + return snd; } } return nullptr; @@ -195,24 +194,24 @@ std::shared_ptr Spells::getRuneSpell(uint16_t id) { return it->second; } -std::shared_ptr Spells::getRuneSpellByName(const std::string &name) { - for (const auto &it : runes) { - if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { - return it.second; +std::shared_ptr Spells::getRuneSpellByName(const std::string &name) const { + for (const auto &[fst, snd] : runes) { + if (strcasecmp(snd->getName().c_str(), name.c_str()) == 0) { + return snd; } } return nullptr; } -std::shared_ptr Spells::getInstantSpell(const std::string &words) { +std::shared_ptr Spells::getInstantSpell(const std::string &words) const { std::shared_ptr result = nullptr; - for (const auto &it : instants) { - const std::string &instantSpellWords = it.second->getWords(); - size_t spellLen = instantSpellWords.length(); + for (const auto &[fst, snd] : instants) { + const std::string &instantSpellWords = snd->getWords(); + const size_t spellLen = instantSpellWords.length(); if (strncasecmp(instantSpellWords.c_str(), words.c_str(), spellLen) == 0) { if (!result || spellLen > result->getWords().length()) { - result = it.second; + result = snd; if (words.length() == spellLen) { break; } @@ -227,8 +226,8 @@ std::shared_ptr Spells::getInstantSpell(const std::string &words) return nullptr; } - size_t spellLen = resultWords.length(); - size_t paramLen = words.length() - spellLen; + const size_t spellLen = resultWords.length(); + const size_t paramLen = words.length() - spellLen; if (paramLen < 2 || words[spellLen] != ' ') { return nullptr; } @@ -238,19 +237,19 @@ std::shared_ptr Spells::getInstantSpell(const std::string &words) return nullptr; } -std::shared_ptr Spells::getInstantSpellById(uint16_t spellId) { - for (const auto &it : instants) { - if (it.second->getSpellId() == spellId) { - return it.second; +std::shared_ptr Spells::getInstantSpellById(uint16_t spellId) const { + for (const auto &[fst, snd] : instants) { + if (snd->getSpellId() == spellId) { + return snd; } } return nullptr; } -std::shared_ptr Spells::getInstantSpellByName(const std::string &name) { - for (const auto &it : instants) { - if (strcasecmp(it.second->getName().c_str(), name.c_str()) == 0) { - return it.second; +std::shared_ptr Spells::getInstantSpellByName(const std::string &name) const { + for (const auto &[fst, snd] : instants) { + if (strcasecmp(snd->getName().c_str(), name.c_str()) == 0) { + return snd; } } return nullptr; @@ -294,7 +293,7 @@ bool CombatSpell::castSpell(const std::shared_ptr &creature) { pos = creature->getPosition(); } - auto combat = getCombat(); + const auto &combat = getCombat(); if (!combat) { return false; } @@ -312,7 +311,7 @@ bool CombatSpell::castSpell(const std::shared_ptr &creature) { } bool CombatSpell::castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) { - auto combat = getCombat(); + const auto &combat = getCombat(); if (!combat) { return false; } @@ -503,7 +502,7 @@ bool Spell::playerInstantSpellCheck(const std::shared_ptr &player, const const auto &tile = g_game().map.getOrCreateTile(toPos); - ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); + const ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -525,7 +524,7 @@ bool Spell::playerInstantSpellCheck(const std::shared_ptr &player, const return true; } -bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos) { +bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos) const { if (!playerSpellCheck(player)) { return false; } @@ -558,7 +557,7 @@ bool Spell::playerRuneSpellCheck(const std::shared_ptr &player, const Po return false; } - ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); + const ReturnValue ret = Combat::canDoCombat(player, tile, aggressive); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); g_game().addMagicEffect(player->getPosition(), CONST_ME_POFF); @@ -626,11 +625,11 @@ void Spell::setWheelOfDestinyBoost(WheelSpellBoost_t boost, WheelSpellGrade_t gr } } -void Spell::getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage) { +void Spell::getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage) const { if (!(damage.instantSpellName).empty()) { - const auto equippedAugmentItems = player->getEquippedAugmentItems(); + const auto &equippedAugmentItems = player->getEquippedAugmentItems(); for (const auto &item : equippedAugmentItems) { - const auto augments = item->getAugmentsBySpellName(damage.instantSpellName); + const auto &augments = item->getAugmentsBySpellName(damage.instantSpellName); for (auto &augment : augments) { if (augment->value == 0) { continue; @@ -652,10 +651,10 @@ void Spell::getCombatDataAugment(const std::shared_ptr &player, CombatDa int32_t Spell::calculateAugmentSpellCooldownReduction(const std::shared_ptr &player) const { int32_t spellCooldown = 0; - const auto equippedAugmentItems = player->getEquippedAugmentItemsByType(Augment_t::Cooldown); + const auto &equippedAugmentItems = player->getEquippedAugmentItemsByType(Augment_t::Cooldown); for (const auto &item : equippedAugmentItems) { - const auto augments = item->getAugmentsBySpellNameAndType(getName(), Augment_t::Cooldown); - for (auto &augment : augments) { + const auto &augments = item->getAugmentsBySpellNameAndType(getName(), Augment_t::Cooldown); + for (const auto &augment : augments) { spellCooldown += augment->value; } } @@ -664,8 +663,8 @@ int32_t Spell::calculateAugmentSpellCooldownReduction(const std::shared_ptr &player) const { - WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); - bool isUpgraded = getWheelOfDestinyUpgraded() && static_cast(spellGrade) > 0; + const WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); + const bool isUpgraded = getWheelOfDestinyUpgraded() && static_cast(spellGrade) > 0; // Safety check to prevent division by zero auto rateCooldown = g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); if (std::abs(rateCooldown) < std::numeric_limits::epsilon()) { @@ -693,7 +692,7 @@ void Spell::applyCooldownConditions(const std::shared_ptr &player) const spellGroupCooldown -= getWheelOfDestinyBoost(WheelSpellBoost_t::GROUP_COOLDOWN, spellGrade); } if (spellGroupCooldown > 0) { - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, spellGroupCooldown / rateCooldown, 0, false, group); + const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_SPELLGROUPCOOLDOWN, spellGroupCooldown / rateCooldown, 0, false, group); player->addCondition(condition); } } @@ -727,7 +726,7 @@ void Spell::postCastSpell(const std::shared_ptr &player, bool finishedCa } if (payCost) { - Spell::postCastSpell(player, getManaCost(player), getSoulCost()); + postCastSpell(player, getManaCost(player), getSoulCost()); } } @@ -760,8 +759,8 @@ uint32_t Spell::getManaCost(const std::shared_ptr &player) const { } if (manaPercent != 0) { - uint32_t maxMana = player->getMaxMana(); - uint32_t manaCost = (maxMana * manaPercent) / 100; + const uint32_t maxMana = player->getMaxMana(); + const uint32_t manaCost = (maxMana * manaPercent) / 100; if (manaRedution > manaCost) { return 0; } @@ -771,7 +770,7 @@ uint32_t Spell::getManaCost(const std::shared_ptr &player) const { return 0; } -bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std::string ¶m) { +bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std::string ¶m) const { if (!playerSpellCheck(player)) { return false; } @@ -788,7 +787,7 @@ bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std: bool useDirection = false; if (hasParam) { - ReturnValue ret = g_game().getPlayerByNameWildcard(param, playerTarget); + const ReturnValue ret = g_game().getPlayerByNameWildcard(param, playerTarget); if (playerTarget && playerTarget->isAccessPlayer() && !player->isAccessPlayer()) { playerTarget = nullptr; @@ -844,7 +843,7 @@ bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std: var.type = VARIANT_STRING; if (getHasPlayerNameParam()) { - ReturnValue ret = g_game().getPlayerByNameWildcard(param, playerTarget); + const ReturnValue ret = g_game().getPlayerByNameWildcard(param, playerTarget); if (ret != RETURNVALUE_NOERROR) { applyCooldownConditions(player); @@ -879,13 +878,13 @@ bool InstantSpell::playerCastInstant(const std::shared_ptr &player, std: return false; } - auto worldType = g_game().getWorldType(); + const auto worldType = g_game().getWorldType(); if (pzLocked && (worldType == WORLD_TYPE_PVP || worldType == WORLD_TYPE_PVP_ENFORCED)) { player->addInFightTicks(true); player->updateLastAggressiveAction(); } - bool result = executeCastSpell(player, var); + const bool result = executeCastSpell(player, var); if (result) { postCastSpell(player); } @@ -920,7 +919,8 @@ bool InstantSpell::castSpell(const std::shared_ptr &creature) { } return false; - } else if (needDirection) { + } + if (needDirection) { var.type = VARIANT_POSITION; var.pos = Spells::getCasterPosition(creature, creature->getDirection()); } else { @@ -937,9 +937,8 @@ bool InstantSpell::castSpell(const std::shared_ptr &creature, const st var.type = VARIANT_NUMBER; var.number = target->getID(); return executeCastSpell(creature, var); - } else { - return castSpell(creature); } + return castSpell(creature); } bool InstantSpell::executeCastSpell(const std::shared_ptr &creature, const LuaVariant &var) const { @@ -993,7 +992,7 @@ ReturnValue RuneSpell::canExecuteAction(const std::shared_ptr &player, c return RETURNVALUE_CANNOTUSETHISOBJECT; } - ReturnValue ret = Action::canExecuteAction(player, toPos); + const ReturnValue ret = Action::canExecuteAction(player, toPos); if (ret != RETURNVALUE_NOERROR) { return ret; } @@ -1047,12 +1046,12 @@ bool RuneSpell::executeUse(const std::shared_ptr &player, const std::sha postCastSpell(player); if (hasCharges && item && g_configManager().getBoolean(REMOVE_RUNE_CHARGES, __FUNCTION__)) { - int32_t newCount = std::max(0, item->getItemCount() - 1); + const int32_t newCount = std::max(0, item->getItemCount() - 1); g_game().transformItem(item, item->getID(), newCount); player->updateSupplyTracker(item); } - auto worldType = g_game().getWorldType(); + const auto worldType = g_game().getWorldType(); if (pzLocked && (worldType == WORLD_TYPE_PVP || worldType == WORLD_TYPE_PVP_ENFORCED)) { player->addInFightTicks(true); player->updateLastAggressiveAction(); @@ -1077,7 +1076,7 @@ bool RuneSpell::castSpell(const std::shared_ptr &creature, const std:: return internalCastSpell(creature, var, false); } -bool RuneSpell::internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) { +bool RuneSpell::internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) const { bool result; if (isLoadedCallback()) { result = executeCastSpell(creature, var, isHotkey); diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index 2771331f50f..d3b96b150e6 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -37,20 +37,20 @@ class Spells final : public Scripts { return inject(); } - std::shared_ptr getSpellByName(const std::string &name); + std::shared_ptr getSpellByName(const std::string &name) const; std::shared_ptr getRuneSpell(uint16_t id); - std::shared_ptr getRuneSpellByName(const std::string &name); + std::shared_ptr getRuneSpellByName(const std::string &name) const; - std::shared_ptr getInstantSpell(const std::string &words); - std::shared_ptr getInstantSpellByName(const std::string &name); + std::shared_ptr getInstantSpell(const std::string &words) const; + std::shared_ptr getInstantSpellByName(const std::string &name) const; - std::shared_ptr getInstantSpellById(uint16_t spellId); + std::shared_ptr getInstantSpellById(uint16_t spellId) const; - TalkActionResult_t playerSaySpell(const std::shared_ptr &player, std::string &words); + TalkActionResult_t playerSaySpell(const std::shared_ptr &player, std::string &words) const; static Position getCasterPosition(const std::shared_ptr &creature, Direction dir); - std::list getSpellsByVocation(uint16_t vocationId); + std::list getSpellsByVocation(uint16_t vocationId) const; [[nodiscard]] const std::map> &getInstantSpells() const { return instants; @@ -201,13 +201,13 @@ class Spell : public BaseSpell { vocSpellMap[vocationId] = b; } - SpellGroup_t getGroup() { + SpellGroup_t getGroup() const { return group; } void setGroup(SpellGroup_t g) { group = g; } - SpellGroup_t getSecondaryGroup() { + SpellGroup_t getSecondaryGroup() const { return secondaryGroup; } void setSecondaryGroup(SpellGroup_t g) { @@ -345,14 +345,14 @@ class Spell : public BaseSpell { m_separator = newSeparator.data(); } - void getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage); + void getCombatDataAugment(const std::shared_ptr &player, CombatDamage &damage) const; int32_t calculateAugmentSpellCooldownReduction(const std::shared_ptr &player) const; protected: void applyCooldownConditions(const std::shared_ptr &player) const; bool playerSpellCheck(const std::shared_ptr &player) const; bool playerInstantSpellCheck(const std::shared_ptr &player, const Position &toPos) const; - bool playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos); + bool playerRuneSpellCheck(const std::shared_ptr &player, const Position &toPos) const; VocSpellMap vocSpellMap; @@ -399,7 +399,7 @@ class InstantSpell final : public Script, public Spell { public: using Script::Script; - virtual bool playerCastInstant(const std::shared_ptr &player, std::string ¶m); + bool playerCastInstant(const std::shared_ptr &player, std::string ¶m) const; bool castSpell(const std::shared_ptr &creature) override; bool castSpell(const std::shared_ptr &creature, const std::shared_ptr &target) override; @@ -499,7 +499,7 @@ class RuneSpell final : public Action, public Spell { return "onCastSpell"; } - bool internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey); + bool internalCastSpell(const std::shared_ptr &creature, const LuaVariant &var, bool isHotkey) const; uint16_t runeId = 0; uint32_t charges = 0; diff --git a/src/creatures/interactions/chat.cpp b/src/creatures/interactions/chat.cpp index b32cf170132..bd14634f50f 100644 --- a/src/creatures/interactions/chat.cpp +++ b/src/creatures/interactions/chat.cpp @@ -18,7 +18,7 @@ bool PrivateChatChannel::isInvited(uint32_t guid) const { if (guid == getOwner()) { return true; } - return invites.find(guid) != invites.end(); + return invites.contains(guid); } bool PrivateChatChannel::removeInvite(uint32_t guid) { @@ -26,8 +26,8 @@ bool PrivateChatChannel::removeInvite(uint32_t guid) { } void PrivateChatChannel::invitePlayer(const std::shared_ptr &player, const std::shared_ptr &invitePlayer) { - auto result = invites.emplace(invitePlayer->getGUID(), invitePlayer); - if (!result.second) { + auto [fst, snd] = invites.emplace(invitePlayer->getGUID(), invitePlayer); + if (!snd) { return; } @@ -39,8 +39,8 @@ void PrivateChatChannel::invitePlayer(const std::shared_ptr &player, con ss << invitePlayer->getName() << " has been invited."; player->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, ss.str()); - for (const auto &it : users) { - it.second->sendChannelEvent(id, invitePlayer->getName(), CHANNELEVENT_INVITE); + for (const auto &[fst, snd] : users) { + snd->sendChannelEvent(id, invitePlayer->getName(), CHANNELEVENT_INVITE); } } @@ -57,19 +57,19 @@ void PrivateChatChannel::excludePlayer(const std::shared_ptr &player, co excludePlayer->sendClosePrivate(id); - for (const auto &it : users) { - it.second->sendChannelEvent(id, excludePlayer->getName(), CHANNELEVENT_EXCLUDE); + for (const auto &[fst, snd] : users) { + snd->sendChannelEvent(id, excludePlayer->getName(), CHANNELEVENT_EXCLUDE); } } void PrivateChatChannel::closeChannel() const { - for (const auto &it : users) { - it.second->sendClosePrivate(id); + for (const auto &[fst, snd] : users) { + snd->sendClosePrivate(id); } } bool ChatChannel::addUser(const std::shared_ptr &player) { - if (users.find(player->getID()) != users.end()) { + if (users.contains(player->getID())) { return false; } @@ -88,8 +88,8 @@ bool ChatChannel::addUser(const std::shared_ptr &player) { } if (!publicChannel) { - for (const auto &it : users) { - it.second->sendChannelEvent(id, player->getName(), CHANNELEVENT_JOIN); + for (const auto &[fst, snd] : users) { + snd->sendChannelEvent(id, player->getName(), CHANNELEVENT_JOIN); } } @@ -98,7 +98,7 @@ bool ChatChannel::addUser(const std::shared_ptr &player) { } bool ChatChannel::removeUser(const std::shared_ptr &player) { - auto iter = users.find(player->getID()); + const auto iter = users.find(player->getID()); if (iter == users.end()) { return false; } @@ -106,8 +106,8 @@ bool ChatChannel::removeUser(const std::shared_ptr &player) { users.erase(iter); if (!publicChannel) { - for (const auto &it : users) { - it.second->sendChannelEvent(id, player->getName(), CHANNELEVENT_LEAVE); + for (const auto &[fst, snd] : users) { + snd->sendChannelEvent(id, player->getName(), CHANNELEVENT_LEAVE); } } @@ -115,23 +115,23 @@ bool ChatChannel::removeUser(const std::shared_ptr &player) { return true; } -bool ChatChannel::hasUser(const std::shared_ptr &player) { - return users.find(player->getID()) != users.end(); +bool ChatChannel::hasUser(const std::shared_ptr &player) const { + return users.contains(player->getID()); } void ChatChannel::sendToAll(const std::string &message, SpeakClasses type) const { - for (const auto &it : users) { - it.second->sendChannelMessage("", message, type, id); + for (const auto &[fst, snd] : users) { + snd->sendChannelMessage("", message, type, id); } } -bool ChatChannel::talk(const std::shared_ptr &fromPlayer, SpeakClasses type, const std::string &text) { - if (users.find(fromPlayer->getID()) == users.end()) { +bool ChatChannel::talk(const std::shared_ptr &fromPlayer, SpeakClasses type, const std::string &text) const { + if (!users.contains(fromPlayer->getID())) { return false; } - for (const auto &it : users) { - it.second->sendToChannel(fromPlayer, type, text, id); + for (const auto &[fst, snd] : users) { + snd->sendToChannel(fromPlayer, type, text, id); } return true; } @@ -241,8 +241,8 @@ bool ChatChannel::executeOnSpeakEvent(const std::shared_ptr &player, Spe LuaScriptInterface::pushString(L, message); bool result = false; - int size0 = lua_gettop(L); - int ret = LuaScriptInterface::protectedCall(L, 3, 1); + const int size0 = lua_gettop(L); + const int ret = LuaScriptInterface::protectedCall(L, 3, 1); if (ret != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(L)); } else if (lua_gettop(L) > 0) { @@ -270,9 +270,9 @@ Chat::Chat() : bool Chat::load() { pugi::xml_document doc; - auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); - auto folder = coreFolder + "/chatchannels/chatchannels.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); + const auto folder = coreFolder + "/chatchannels/chatchannels.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -281,7 +281,7 @@ bool Chat::load() { for (const auto &channelNode : doc.child("channels").children()) { auto channelId = pugi::cast(channelNode.attribute("id").value()); std::string channelName = channelNode.attribute("name").as_string(); - bool isPublic = channelNode.attribute("public").as_bool(); + const bool isPublic = channelNode.attribute("public").as_bool(); pugi::xml_attribute scriptAttribute = channelNode.attribute("script"); auto it = normalChannels.find(channelId); @@ -302,8 +302,8 @@ bool Chat::load() { } UsersMap tempUserMap = std::move(channel->users); - for (const auto &pair : tempUserMap) { - channel->addUser(pair.second); + for (const auto &[fst, snd] : tempUserMap) { + channel->addUser(snd); } continue; } @@ -336,8 +336,8 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & case CHANNEL_GUILD: { const auto &guild = player->getGuild(); if (guild != nullptr) { - auto ret = guildChannels.emplace(std::make_pair(guild->getId(), std::make_shared(channelId, guild->getName()))); - return ret.first->second; + auto [fst, snd] = guildChannels.emplace(std::make_pair(guild->getId(), std::make_shared(channelId, guild->getName()))); + return fst->second; } break; } @@ -345,8 +345,8 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & case CHANNEL_PARTY: { const auto &party = player->getParty(); if (party != nullptr) { - auto ret = partyChannels.emplace(std::make_pair(party, std::make_shared(channelId, "Party"))); - return ret.first->second; + auto [fst, snd] = partyChannels.emplace(std::make_pair(party, std::make_shared(channelId, "Party"))); + return fst->second; } break; } @@ -359,9 +359,9 @@ std::shared_ptr Chat::createChannel(const std::shared_ptr & // find a free private channel slot for (uint16_t i = 100; i < 10000; ++i) { - auto ret = privateChannels.emplace(std::make_pair(i, std::make_shared(i, player->getName() + "'s Channel"))); - if (ret.second) { // second is a bool that indicates that a new channel has been placed in the map - const auto &newChannel = (*ret.first).second; + auto [fst, snd] = privateChannels.emplace(std::make_pair(i, std::make_shared(i, player->getName() + "'s Channel"))); + if (snd) { // second is a bool that indicates that a new channel has been placed in the map + const auto &newChannel = fst->second; newChannel->setOwner(player->getGUID()); return newChannel; } @@ -383,7 +383,7 @@ bool Chat::deleteChannel(const std::shared_ptr &player, uint16_t channel return false; } - auto it = guildChannels.find(guild->getId()); + const auto it = guildChannels.find(guild->getId()); if (it == guildChannels.end()) { return false; } @@ -398,7 +398,7 @@ bool Chat::deleteChannel(const std::shared_ptr &player, uint16_t channel return false; } - auto it = partyChannels.find(party); + const auto it = partyChannels.find(party); if (it == partyChannels.end()) { return false; } @@ -408,7 +408,7 @@ bool Chat::deleteChannel(const std::shared_ptr &player, uint16_t channel } default: { - auto it = privateChannels.find(channelId); + const auto it = privateChannels.find(channelId); if (it == privateChannels.end()) { return false; } @@ -443,16 +443,16 @@ bool Chat::removeUserFromChannel(const std::shared_ptr &player, uint16_t } void Chat::removeUserFromAllChannels(const std::shared_ptr &player) { - for (const auto &it : normalChannels) { - it.second->removeUser(player); + for (const auto &[fst, snd] : normalChannels) { + snd->removeUser(player); } - for (const auto &it : partyChannels) { - it.second->removeUser(player); + for (const auto &[fst, snd] : partyChannels) { + snd->removeUser(player); } - for (const auto &it : guildChannels) { - it.second->removeUser(player); + for (const auto &[fst, snd] : guildChannels) { + snd->removeUser(player); } auto it = privateChannels.begin(); @@ -498,11 +498,11 @@ ChannelList Chat::getChannelList(const std::shared_ptr &player) { if (player->getGuild()) { auto channel = getChannel(player, CHANNEL_GUILD); if (channel) { - list.push_back(channel); + list.emplace_back(channel); } else { channel = createChannel(player, CHANNEL_GUILD); if (channel) { - list.push_back(channel); + list.emplace_back(channel); } } } @@ -510,28 +510,28 @@ ChannelList Chat::getChannelList(const std::shared_ptr &player) { if (player->getParty()) { auto channel = getChannel(player, CHANNEL_PARTY); if (channel) { - list.push_back(channel); + list.emplace_back(channel); } else { channel = createChannel(player, CHANNEL_PARTY); if (channel) { - list.push_back(channel); + list.emplace_back(channel); } } } - for (const auto &it : normalChannels) { - const auto &channel = getChannel(player, it.first); + for (const auto &[fst, snd] : normalChannels) { + const auto &channel = getChannel(player, fst); if (channel) { - list.push_back(channel); + list.emplace_back(channel); } } bool hasPrivate = false; - for (const auto &it : privateChannels) { - if (const auto &channel = it.second) { - uint32_t guid = player->getGUID(); + for (const auto &[fst, snd] : privateChannels) { + if (const auto &channel = snd) { + const uint32_t guid = player->getGUID(); if (channel->isInvited(guid)) { - list.push_back(channel); + list.emplace_back(channel); } if (channel->getOwner() == guid) { @@ -541,7 +541,7 @@ ChannelList Chat::getChannelList(const std::shared_ptr &player) { } if (!hasPrivate && player->isPremium()) { - list.push_front(dummyPrivate); + list.emplace_back(dummyPrivate); } return list; } @@ -551,7 +551,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla case CHANNEL_GUILD: { const auto &guild = player->getGuild(); if (guild != nullptr) { - auto it = guildChannels.find(guild->getId()); + const auto &it = guildChannels.find(guild->getId()); if (it != guildChannels.end()) { return it->second; } @@ -562,7 +562,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla case CHANNEL_PARTY: { const auto &party = player->getParty(); if (party != nullptr) { - auto it = partyChannels.find(party); + const auto &it = partyChannels.find(party); if (it != partyChannels.end()) { return it->second; } @@ -571,7 +571,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla } default: { - auto it = normalChannels.find(channelId); + const auto &it = normalChannels.find(channelId); if (it != normalChannels.end()) { const auto &channel = it->second; if (!channel->executeCanJoinEvent(player)) { @@ -580,7 +580,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla return channel; } - auto it2 = privateChannels.find(channelId); + const auto &it2 = privateChannels.find(channelId); if (it2 != privateChannels.end() && it2->second->isInvited(player->getGUID())) { return it2->second; } @@ -591,7 +591,7 @@ std::shared_ptr Chat::getChannel(const std::shared_ptr &pla } std::shared_ptr Chat::getGuildChannelById(uint32_t guildId) { - auto it = guildChannels.find(guildId); + const auto &it = guildChannels.find(guildId); if (it == guildChannels.end()) { return nullptr; } @@ -599,17 +599,17 @@ std::shared_ptr Chat::getGuildChannelById(uint32_t guildId) { } std::shared_ptr Chat::getChannelById(uint16_t channelId) { - auto it = normalChannels.find(channelId); + const auto &it = normalChannels.find(channelId); if (it == normalChannels.end()) { return nullptr; } return it->second; } -std::shared_ptr Chat::getPrivateChannel(const std::shared_ptr &player) { - for (const auto &it : privateChannels) { - if (it.second->getOwner() == player->getGUID()) { - return it.second; +std::shared_ptr Chat::getPrivateChannel(const std::shared_ptr &player) const { + for (const auto &[fst, snd] : privateChannels) { + if (snd->getOwner() == player->getGUID()) { + return snd; } } return nullptr; diff --git a/src/creatures/interactions/chat.hpp b/src/creatures/interactions/chat.hpp index 59c190fe2c1..7e2b471f4be 100644 --- a/src/creatures/interactions/chat.hpp +++ b/src/creatures/interactions/chat.hpp @@ -30,9 +30,9 @@ class ChatChannel { bool addUser(const std::shared_ptr &player); bool removeUser(const std::shared_ptr &player); - bool hasUser(const std::shared_ptr &player); + bool hasUser(const std::shared_ptr &player) const; - bool talk(const std::shared_ptr &fromPlayer, SpeakClasses type, const std::string &text); + bool talk(const std::shared_ptr &fromPlayer, SpeakClasses type, const std::string &text) const; void sendToAll(const std::string &message, SpeakClasses type) const; const std::string &getName() const { @@ -137,7 +137,7 @@ class Chat { std::shared_ptr getChannel(const std::shared_ptr &player, uint16_t channelId); std::shared_ptr getChannelById(uint16_t channelId); std::shared_ptr getGuildChannelById(uint32_t guildId); - std::shared_ptr getPrivateChannel(const std::shared_ptr &player); + std::shared_ptr getPrivateChannel(const std::shared_ptr &player) const; LuaScriptInterface* getScriptInterface() { return &scriptInterface; diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index fb031615f47..9892f29de42 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -32,7 +32,6 @@ std::shared_ptr Monster::createMonster(const std::string &name) { } Monster::Monster(const std::shared_ptr &mType) : - Creature(), nameDescription(asLowerCaseString(mType->nameDescription)), mType(mType) { defaultOutfit = mType->info.outfit; @@ -80,7 +79,7 @@ void Monster::setName(const std::string &name) { // NOTE: Due to how client caches known creatures, // it is not feasible to send creature update to everyone that has ever met it - auto spectators = Spectators().find(position, true); + const auto spectators = Spectators().find(position, true); for (const auto &spectator : spectators) { if (const auto &tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendUpdateTileCreature(static_self_cast()); @@ -110,7 +109,7 @@ bool Monster::canWalkOnFieldType(CombatType_t combatType) const { int32_t Monster::getReflectPercent(CombatType_t reflectType, bool useCharges) const { int32_t result = Creature::getReflectPercent(reflectType, useCharges); - auto it = mType->info.reflectMap.find(reflectType); + const auto &it = mType->info.reflectMap.find(reflectType); if (it != mType->info.reflectMap.end()) { result += it->second; } @@ -118,7 +117,7 @@ int32_t Monster::getReflectPercent(CombatType_t reflectType, bool useCharges) co } uint32_t Monster::getHealingCombatValue(CombatType_t healingType) const { - auto it = mType->info.healingMap.find(healingType); + const auto &it = mType->info.healingMap.find(healingType); if (it != mType->info.healingMap.end()) { return it->second; } @@ -246,8 +245,8 @@ void Monster::onCreatureMove(const std::shared_ptr &creature, const st updateTargetList(); updateIdleStatus(); } else { - bool canSeeNewPos = canSee(newPos); - bool canSeeOldPos = canSee(oldPos); + const bool canSeeNewPos = canSee(newPos); + const bool canSeeOldPos = canSee(oldPos); if (canSeeNewPos && !canSeeOldPos) { onCreatureEnter(creature); @@ -262,10 +261,10 @@ void Monster::onCreatureMove(const std::shared_ptr &creature, const st const Position &followPosition = followCreature->getPosition(); const Position &pos = getPosition(); - int32_t offset_x = Position::getDistanceX(followPosition, pos); - int32_t offset_y = Position::getDistanceY(followPosition, pos); + const int32_t offset_x = Position::getDistanceX(followPosition, pos); + const int32_t offset_y = Position::getDistanceY(followPosition, pos); if ((offset_x > 1 || offset_y > 1) && mType->info.changeTargetChance > 0) { - Direction dir = getDirectionTo(pos, followPosition); + const Direction dir = getDirectionTo(pos, followPosition); const auto &checkPosition = getNextPosition(dir, pos); if (const auto &nextTile = g_game().map.getTile(checkPosition)) { @@ -480,7 +479,7 @@ void Monster::onCreatureLeave(const std::shared_ptr &creature) { bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAULT*/) { if (searchType == TARGETSEARCH_DEFAULT) { - int32_t rnd = uniform_random(1, 100); + const int32_t rnd = uniform_random(1, 100); searchType = TARGETSEARCH_NEAREST; @@ -506,7 +505,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL const auto &creature = cref.lock(); if (creature && isTarget(creature)) { if ((static_self_cast()->targetDistance == 1) || canUseAttack(myPos, creature)) { - resultList.push_back(creature); + resultList.emplace_back(creature); } } } @@ -527,11 +526,11 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL if (++it != resultList.end()) { const Position &targetPosition = getTarget->getPosition(); int32_t minRange = std::max(Position::getDistanceX(myPos, targetPosition), Position::getDistanceY(myPos, targetPosition)); - int32_t factionOffset = static_cast(getTarget->getFaction()) * 100; + const int32_t factionOffset = static_cast(getTarget->getFaction()) * 100; do { const Position &pos = (*it)->getPosition(); - int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)) + factionOffset; + const int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)) + factionOffset; if (distance < minRange) { getTarget = *it; minRange = distance; @@ -546,8 +545,8 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL } const Position &pos = creature->getPosition(); - int32_t factionOffset = static_cast(getTarget->getFaction()) * 100; - int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)) + factionOffset; + const int32_t factionOffset = static_cast(getTarget->getFaction()) * 100; + const int32_t distance = std::max(Position::getDistanceX(myPos, pos), Position::getDistanceY(myPos, pos)) + factionOffset; if (distance < minRange) { getTarget = creature; minRange = distance; @@ -569,7 +568,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL int32_t factionOffset = static_cast(getTarget->getFaction()) * 100000; int32_t minHp = getTarget->getHealth() + factionOffset; do { - auto hp = (*it)->getHealth() + factionOffset; + const auto hp = (*it)->getHealth() + factionOffset; factionOffset = static_cast((*it)->getFaction()) * 100000; if (hp < minHp) { getTarget = *it; @@ -591,7 +590,7 @@ bool Monster::searchTarget(TargetSearchType_t searchType /*= TARGETSEARCH_DEFAUL if (++it != resultList.end()) { int32_t mostDamage = 0; do { - int32_t factionOffset = static_cast((*it)->getFaction()) * 100000; + const int32_t factionOffset = static_cast((*it)->getFaction()) * 100000; const auto dmg = damageMap.find((*it)->getID()); if (dmg != damageMap.end() && dmg->second.total + factionOffset > mostDamage) { mostDamage = dmg->second.total; @@ -641,7 +640,7 @@ BlockType_t Monster::blockHit(const std::shared_ptr &attacker, const C if (damage != 0) { int32_t elementMod = 0; - auto it = mType->info.elementMap.find(combatType); + const auto it = mType->info.elementMap.find(combatType); if (it != mType->info.elementMap.end()) { elementMod = it->second; } @@ -913,7 +912,7 @@ void Monster::doAttacking(uint32_t interval) { bool Monster::canUseAttack(const Position &pos, const std::shared_ptr &target) const { if (isHostile()) { const Position &targetPos = target->getPosition(); - uint32_t distance = std::max(Position::getDistanceX(pos, targetPos), Position::getDistanceY(pos, targetPos)); + const uint32_t distance = std::max(Position::getDistanceX(pos, targetPos), Position::getDistanceY(pos, targetPos)); for (const spellBlock_t &spellBlock : mType->info.attackSpells) { if (spellBlock.range != 0 && distance <= spellBlock.range) { return g_game().isSightClear(pos, targetPos, true); @@ -1028,8 +1027,8 @@ void Monster::onThinkDefense(uint32_t interval) { } if (!isSummon() && m_summons.size() < mType->info.maxSummons && hasFollowPath) { - for (const summonBlock_t &summonBlock : mType->info.summons) { - if (summonBlock.speed > defenseTicks) { + for (const auto &[name, chance, speed, count, force] : mType->info.summons) { + if (speed > defenseTicks) { resetTicks = false; continue; } @@ -1038,29 +1037,29 @@ void Monster::onThinkDefense(uint32_t interval) { continue; } - if (defenseTicks % summonBlock.speed >= interval) { + if (defenseTicks % speed >= interval) { // already used this spell for this round continue; } uint32_t summonCount = 0; for (const auto &summon : m_summons) { - if (summon && summon->getName() == summonBlock.name) { + if (summon && summon->getName() == name) { ++summonCount; } } - if (summonCount >= summonBlock.count) { + if (summonCount >= count) { continue; } - if (summonBlock.chance < static_cast(uniform_random(1, 100))) { + if (chance < static_cast(uniform_random(1, 100))) { continue; } - const auto &summon = Monster::createMonster(summonBlock.name); + const auto &summon = Monster::createMonster(name); if (summon) { - if (g_game().placeCreature(summon, getPosition(), false, summonBlock.force)) { + if (g_game().placeCreature(summon, getPosition(), false, force)) { summon->setMaster(static_self_cast(), true); g_game().addMagicEffect(getPosition(), CONST_ME_MAGIC_BLUE); g_game().addMagicEffect(summon->getPosition(), CONST_ME_TELEPORT); @@ -1085,13 +1084,13 @@ void Monster::onThinkYell(uint32_t interval) { yellTicks = 0; if (!mType->info.voiceVector.empty() && (mType->info.yellChance >= static_cast(uniform_random(1, 100)))) { - uint32_t index = uniform_random(0, mType->info.voiceVector.size() - 1); - const voiceBlock_t &vb = mType->info.voiceVector[index]; + const uint32_t index = uniform_random(0, mType->info.voiceVector.size() - 1); + const auto &[text, yellText] = mType->info.voiceVector[index]; - if (vb.yellText) { - g_game().internalCreatureSay(static_self_cast(), TALKTYPE_MONSTER_YELL, vb.text, false); + if (yellText) { + g_game().internalCreatureSay(static_self_cast(), TALKTYPE_MONSTER_YELL, text, false); } else { - g_game().internalCreatureSay(static_self_cast(), TALKTYPE_MONSTER_SAY, vb.text, false); + g_game().internalCreatureSay(static_self_cast(), TALKTYPE_MONSTER_SAY, text, false); } } } @@ -1107,7 +1106,7 @@ void Monster::onThinkSound(uint32_t interval) { soundTicks = 0; if (!mType->info.soundVector.empty() && (mType->info.soundChance >= static_cast(uniform_random(1, 100)))) { - int64_t index = uniform_random(0, static_cast(mType->info.soundVector.size() - 1)); + const int64_t index = uniform_random(0, static_cast(mType->info.soundVector.size() - 1)); g_game().sendSingleSoundEffect(static_self_cast()->getPosition(), mType->info.soundVector[index], getMonster()); } } @@ -1132,7 +1131,7 @@ void Monster::pushItems(const std::shared_ptr &tile, const Direction &next if (const auto &items = tile->getItemList()) { uint32_t moveCount = 0; uint32_t removeCount = 0; - int32_t downItemSize = tile->getDownItemCount(); + const int32_t downItemSize = tile->getDownItemCount(); for (int32_t i = downItemSize; --i >= 0;) { const auto &item = items->at(i); if (item && item->hasProperty(CONST_PROP_MOVABLE) && (item->hasProperty(CONST_PROP_BLOCKPATH) || item->hasProperty(CONST_PROP_BLOCKSOLID)) && item->canBeMoved()) { @@ -1155,7 +1154,7 @@ bool Monster::pushCreature(const std::shared_ptr &creature) { DIRECTION_WEST, DIRECTION_EAST, DIRECTION_SOUTH }; - std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); + std::ranges::shuffle(dirList, getRandomGenerator()); for (const Direction &dir : dirList) { const Position &tryPos = Spells::getCasterPosition(creature, dir); @@ -1170,7 +1169,7 @@ bool Monster::pushCreature(const std::shared_ptr &creature) { void Monster::pushCreatures(const std::shared_ptr &tile) { // We can not use iterators here since we can push a creature to another tile // which will invalidate the iterator. - if (CreatureVector* creatures = tile->getCreatures()) { + if (const CreatureVector* creatures = tile->getCreatures()) { uint32_t removeCount = 0; std::shared_ptr lastPushedMonster = nullptr; @@ -1215,7 +1214,7 @@ bool Monster::getNextStep(Direction &nextDirection, uint32_t &flags) { if (result && (canPushItems() || canPushCreatures())) { const Position &pos = getNextPosition(nextDirection, getPosition()); - auto posTile = g_game().map.getTile(pos); + const auto &posTile = g_game().map.getTile(pos); if (posTile) { if (canPushItems()) { Monster::pushItems(posTile, nextDirection); @@ -1247,7 +1246,7 @@ void Monster::doWalkBack(uint32_t &flags, Direction &nextDirection, bool &result updateMapCache(); } - int32_t distance = std::max(Position::getDistanceX(position, masterPos), Position::getDistanceY(position, masterPos)); + const int32_t distance = std::max(Position::getDistanceX(position, masterPos), Position::getDistanceY(position, masterPos)); if (distance == 0) { isWalkingBack = false; return; @@ -1291,7 +1290,7 @@ bool Monster::getRandomStep(const Position &creaturePos, Direction &moveDirectio DIRECTION_WEST, DIRECTION_EAST, DIRECTION_SOUTH }; - std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); + std::ranges::shuffle(dirList, getRandomGenerator()); for (const Direction &dir : dirList) { if (canWalkTo(creaturePos, dir)) { @@ -1307,25 +1306,25 @@ bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection if (!attackedCreature) { return false; } - bool canDoAttackNow = canUseAttack(creaturePos, attackedCreature); + const bool canDoAttackNow = canUseAttack(creaturePos, attackedCreature); const Position ¢erPos = attackedCreature->getPosition(); - int_fast32_t offset_x = Position::getOffsetX(creaturePos, centerPos); - int_fast32_t offset_y = Position::getOffsetY(creaturePos, centerPos); + const int_fast32_t offset_x = Position::getOffsetX(creaturePos, centerPos); + const int_fast32_t offset_y = Position::getOffsetY(creaturePos, centerPos); - int_fast32_t distance_x = std::abs(offset_x); - int_fast32_t distance_y = std::abs(offset_y); + const int_fast32_t distance_x = std::abs(offset_x); + const int_fast32_t distance_y = std::abs(offset_y); - uint32_t centerToDist = std::max(distance_x, distance_y); + const uint32_t centerToDist = std::max(distance_x, distance_y); // monsters not at targetDistance shouldn't dancestep - if (centerToDist < (uint32_t)targetDistance) { + if (centerToDist < static_cast(targetDistance)) { return false; } std::vector dirList; if (!keepDistance || offset_y >= 0) { - uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() - 1) - centerPos.getY())); + const uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() - 1) - centerPos.getY())); if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_NORTH)) { bool result = true; @@ -1334,13 +1333,13 @@ bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection } if (result) { - dirList.push_back(DIRECTION_NORTH); + dirList.emplace_back(DIRECTION_NORTH); } } } if (!keepDistance || offset_y <= 0) { - uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() + 1) - centerPos.getY())); + const uint32_t tmpDist = std::max(distance_x, std::abs((creaturePos.getY() + 1) - centerPos.getY())); if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_SOUTH)) { bool result = true; @@ -1349,13 +1348,13 @@ bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection } if (result) { - dirList.push_back(DIRECTION_SOUTH); + dirList.emplace_back(DIRECTION_SOUTH); } } } if (!keepDistance || offset_x <= 0) { - uint32_t tmpDist = std::max(std::abs((creaturePos.getX() + 1) - centerPos.getX()), distance_y); + const uint32_t tmpDist = std::max(std::abs((creaturePos.getX() + 1) - centerPos.getX()), distance_y); if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_EAST)) { bool result = true; @@ -1364,13 +1363,13 @@ bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection } if (result) { - dirList.push_back(DIRECTION_EAST); + dirList.emplace_back(DIRECTION_EAST); } } } if (!keepDistance || offset_x >= 0) { - uint32_t tmpDist = std::max(std::abs((creaturePos.getX() - 1) - centerPos.getX()), distance_y); + const uint32_t tmpDist = std::max(std::abs((creaturePos.getX() - 1) - centerPos.getX()), distance_y); if (tmpDist == centerToDist && canWalkTo(creaturePos, DIRECTION_WEST)) { bool result = true; @@ -1379,13 +1378,13 @@ bool Monster::getDanceStep(const Position &creaturePos, Direction &moveDirection } if (result) { - dirList.push_back(DIRECTION_WEST); + dirList.emplace_back(DIRECTION_WEST); } } } if (!dirList.empty()) { - std::shuffle(dirList.begin(), dirList.end(), getRandomGenerator()); + std::ranges::shuffle(dirList, getRandomGenerator()); moveDirection = dirList[uniform_random(0, dirList.size() - 1)]; return true; } @@ -1431,13 +1430,16 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (s && e) { moveDirection = boolean_random() ? DIRECTION_SOUTH : DIRECTION_EAST; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; - } else if (canWalkTo(creaturePos, DIRECTION_SOUTHEAST)) { + } + if (canWalkTo(creaturePos, DIRECTION_SOUTHEAST)) { moveDirection = DIRECTION_SOUTHEAST; return true; } @@ -1450,10 +1452,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && w) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_WEST; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; } @@ -1468,7 +1472,8 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio } return true; - } else if (offsetx <= -1 && offsety <= -1) { + } + if (offsetx <= -1 && offsety <= -1) { // player is SE // escape to NW , W or N [and some extra] bool w = canWalkTo(creaturePos, DIRECTION_WEST); @@ -1477,10 +1482,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && n) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_NORTH; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; } @@ -1498,10 +1505,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (s && e) { moveDirection = boolean_random() ? DIRECTION_SOUTH : DIRECTION_EAST; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; } @@ -1516,7 +1525,8 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio } return true; - } else if (offsetx >= 1 && offsety <= -1) { + } + if (offsetx >= 1 && offsety <= -1) { // player is SW // escape to NE, N, E [and some extra] bool n = canWalkTo(creaturePos, DIRECTION_NORTH); @@ -1524,10 +1534,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && e) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_EAST; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; } @@ -1545,10 +1557,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (s && w) { moveDirection = boolean_random() ? DIRECTION_SOUTH : DIRECTION_WEST; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; } @@ -1563,7 +1577,8 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio } return true; - } else if (offsetx <= -1 && offsety >= 1) { + } + if (offsetx <= -1 && offsety >= 1) { // player is NE // escape to SW, S, W [and some extra] bool w = canWalkTo(creaturePos, DIRECTION_WEST); @@ -1571,13 +1586,16 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && s) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_SOUTH; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; - } else if (canWalkTo(creaturePos, DIRECTION_SOUTHWEST)) { + } + if (canWalkTo(creaturePos, DIRECTION_SOUTHWEST)) { moveDirection = DIRECTION_SOUTHWEST; return true; } @@ -1590,10 +1608,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && e) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_EAST; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; } @@ -1627,10 +1647,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && e && offsetx == 0) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_EAST; return true; - } else if (w && offsetx <= 0) { + } + if (w && offsetx <= 0) { moveDirection = DIRECTION_WEST; return true; - } else if (e && offsetx >= 0) { + } + if (e && offsetx >= 0) { moveDirection = DIRECTION_EAST; return true; } @@ -1640,10 +1662,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && e) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_EAST; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; } @@ -1691,10 +1715,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && e && offsetx == 0) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_EAST; return true; - } else if (w && offsetx <= 0) { + } + if (w && offsetx <= 0) { moveDirection = DIRECTION_WEST; return true; - } else if (e && offsetx >= 0) { + } + if (e && offsetx >= 0) { moveDirection = DIRECTION_EAST; return true; } @@ -1704,10 +1730,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (w && e) { moveDirection = boolean_random() ? DIRECTION_WEST : DIRECTION_EAST; return true; - } else if (w) { + } + if (w) { moveDirection = DIRECTION_WEST; return true; - } else if (e) { + } + if (e) { moveDirection = DIRECTION_EAST; return true; } @@ -1761,10 +1789,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && s && offsety == 0) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_SOUTH; return true; - } else if (n && offsety <= 0) { + } + if (n && offsety <= 0) { moveDirection = DIRECTION_NORTH; return true; - } else if (s && offsety >= 0) { + } + if (s && offsety >= 0) { moveDirection = DIRECTION_SOUTH; return true; } @@ -1774,10 +1804,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && s) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_SOUTH; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; } @@ -1824,10 +1856,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && s && offsety == 0) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_SOUTH; return true; - } else if (n && offsety <= 0) { + } + if (n && offsety <= 0) { moveDirection = DIRECTION_NORTH; return true; - } else if (s && offsety >= 0) { + } + if (s && offsety >= 0) { moveDirection = DIRECTION_SOUTH; return true; } @@ -1837,10 +1871,12 @@ bool Monster::getDistanceStep(const Position &targetPos, Direction &moveDirectio if (n && s) { moveDirection = boolean_random() ? DIRECTION_NORTH : DIRECTION_SOUTH; return true; - } else if (n) { + } + if (n) { moveDirection = DIRECTION_NORTH; return true; - } else if (s) { + } + if (s) { moveDirection = DIRECTION_SOUTH; return true; } @@ -1983,11 +2019,11 @@ void Monster::updateLookDirection() { const Position &pos = getPosition(); const Position &attackedCreaturePos = attackedCreature->getPosition(); - int_fast32_t offsetx = Position::getOffsetX(attackedCreaturePos, pos); - int_fast32_t offsety = Position::getOffsetY(attackedCreaturePos, pos); + const int_fast32_t offsetx = Position::getOffsetX(attackedCreaturePos, pos); + const int_fast32_t offsety = Position::getOffsetY(attackedCreaturePos, pos); - int32_t dx = std::abs(offsetx); - int32_t dy = std::abs(offsety); + const int32_t dx = std::abs(offsetx); + const int32_t dy = std::abs(offsety); if (dx > dy) { // look EAST/WEST if (offsetx < 0) { @@ -2003,7 +2039,7 @@ void Monster::updateLookDirection() { newDir = DIRECTION_SOUTH; } } else { - Direction dir = getDirection(); + const Direction dir = getDirection(); if (offsetx < 0 && offsety < 0) { if (dir == DIRECTION_SOUTH) { newDir = DIRECTION_WEST; @@ -2036,13 +2072,13 @@ void Monster::updateLookDirection() { void Monster::dropLoot(const std::shared_ptr &corpse, std::shared_ptr) { if (corpse && lootDrop) { // Only fiendish drops sliver - if (ForgeClassifications_t classification = getMonsterForgeClassification(); + if (const ForgeClassifications_t classification = getMonsterForgeClassification(); // Condition classification == ForgeClassifications_t::FORGE_FIENDISH_MONSTER) { - auto minSlivers = g_configManager().getNumber(FORGE_MIN_SLIVERS, __FUNCTION__); - auto maxSlivers = g_configManager().getNumber(FORGE_MAX_SLIVERS, __FUNCTION__); + const auto minSlivers = g_configManager().getNumber(FORGE_MIN_SLIVERS, __FUNCTION__); + const auto maxSlivers = g_configManager().getNumber(FORGE_MAX_SLIVERS, __FUNCTION__); - auto sliverCount = static_cast(uniform_random(minSlivers, maxSlivers)); + const auto sliverCount = static_cast(uniform_random(minSlivers, maxSlivers)); const auto &sliver = Item::CreateItem(ITEM_FORGE_SLIVER, sliverCount); if (g_game().internalAddItem(corpse, sliver) != RETURNVALUE_NOERROR) { @@ -2075,7 +2111,7 @@ void Monster::drainHealth(const std::shared_ptr &attacker, int32_t dam void Monster::changeHealth(int32_t healthChange, bool sendHealthChange /* = true*/) { if (mType && !mType->info.soundVector.empty() && mType->info.soundChance >= static_cast(uniform_random(1, 100))) { - auto index = uniform_random(0, mType->info.soundVector.size() - 1); + const auto index = uniform_random(0, mType->info.soundVector.size() - 1); g_game().sendSingleSoundEffect(static_self_cast()->getPosition(), mType->info.soundVector[index], getMonster()); } @@ -2089,7 +2125,7 @@ bool Monster::challengeCreature(const std::shared_ptr &creature, int t return false; } - bool result = selectTarget(creature); + const bool result = selectTarget(creature); if (result) { challengeFocusDuration = targetChangeCooldown; targetChangeTicks = 0; @@ -2111,7 +2147,7 @@ bool Monster::changeTargetDistance(int32_t distance, uint32_t duration /* = 1200 return false; } - bool shouldUpdate = mType->info.targetDistance > distance ? true : false; + const bool shouldUpdate = mType->info.targetDistance > distance ? true : false; challengeMeleeDuration = duration; targetDistance = distance; @@ -2167,15 +2203,15 @@ void Monster::configureForgeSystem() { setIcon("forge", CreatureIcon(CreatureIconModifications_t::Fiendish, 0 /* don't show stacks on fiends */)); g_game().updateCreatureIcon(static_self_cast()); } else if (monsterForgeClassification == ForgeClassifications_t::FORGE_INFLUENCED_MONSTER) { - auto stack = static_cast(normal_random(1, 5)); + const auto stack = static_cast(normal_random(1, 5)); setForgeStack(stack); setIcon("forge", CreatureIcon(CreatureIconModifications_t::Influenced, stack)); g_game().updateCreatureIcon(static_self_cast()); } // Change health based in stacks - float percentToIncrement = static_cast((forgeStack * 6) + 100) / 100.f; - auto newHealth = static_cast(std::ceil(static_cast(healthMax) * percentToIncrement)); + const float percentToIncrement = static_cast((forgeStack * 6) + 100) / 100.f; + const auto newHealth = static_cast(std::ceil(static_cast(healthMax) * percentToIncrement)); healthMax = newHealth; health = newHealth; diff --git a/src/creatures/monsters/monster.hpp b/src/creatures/monsters/monster.hpp index be457c8804d..2367aa86321 100644 --- a/src/creatures/monsters/monster.hpp +++ b/src/creatures/monsters/monster.hpp @@ -90,7 +90,7 @@ class Monster final : public Creature { } bool isEnemyFaction(Faction_t faction) const { - auto master = getMaster(); + const auto &master = getMaster(); if (master && master->getMonster()) { return master->getMonster()->isEnemyFaction(faction); } @@ -336,14 +336,14 @@ class Monster final : public Creature { float getAttackMultiplier() const { float multiplier = mType->getAttackMultiplier(); - if (auto stacks = getForgeStack(); stacks > 0) { + if (const auto stacks = getForgeStack(); stacks > 0) { multiplier *= (1.35 + (stacks - 1) * 0.1); } return multiplier; } float getDefenseMultiplier() const { - float multiplier = mType->getDefenseMultiplier(); + const float multiplier = mType->getDefenseMultiplier(); return multiplier * std::pow(1.02f, getForgeStack()); } diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index 46a2f56a8e0..9d8a6f67f04 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -30,7 +30,7 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { } pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filemonstername.c_str()); + const pugi::xml_parse_result result = doc.load_file(filemonstername.c_str()); if (!result) { printXMLError(__FUNCTION__, filemonstername, result); return false; @@ -80,8 +80,8 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { dir = DIRECTION_NORTH; } - auto xOffset = pugi::cast(childMonsterNode.attribute("x").value()); - auto yOffset = pugi::cast(childMonsterNode.attribute("y").value()); + const auto xOffset = pugi::cast(childMonsterNode.attribute("x").value()); + const auto yOffset = pugi::cast(childMonsterNode.attribute("y").value()); Position pos( static_cast(centerPos.x + xOffset), static_cast(centerPos.y + yOffset), @@ -96,10 +96,16 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { uint32_t scheduleInterval = g_configManager().getNumber(DEFAULT_RESPAWN_TIME, __FUNCTION__); - try { - scheduleInterval = pugi::cast(childMonsterNode.attribute("spawntime").value()); - } catch (...) { - g_logger().warn("Failed to add schedule interval to monster: {}, interval: {}. Setting to default respawn time: {}", nameAttribute.value(), childMonsterNode.attribute("spawntime").value(), scheduleInterval); + pugi::xml_attribute spawnTimeAttr = childMonsterNode.attribute("spawntime"); + if (spawnTimeAttr) { + const auto xmlSpawnTime = pugi::cast(spawnTimeAttr.value()); + if (xmlSpawnTime > 0) { + scheduleInterval = xmlSpawnTime; + } else { + g_logger().warn("Invalid spawntime value '{}' for monster '{}'. Setting to default respawn time: {}", spawnTimeAttr.value(), nameAttribute.value(), scheduleInterval); + } + } else { + g_logger().warn("Missing spawntime attribute for monster '{}'. Setting to default respawn time: {}", nameAttribute.value(), scheduleInterval); } spawnMonster.addMonster(nameAttribute.as_string(), pos, dir, scheduleInterval * 1000, weight); @@ -163,7 +169,7 @@ bool SpawnMonster::findPlayer(const Position &pos) { }); } -bool SpawnMonster::isInSpawnMonsterZone(const Position &pos) { +bool SpawnMonster::isInSpawnMonsterZone(const Position &pos) const { return SpawnsMonster::isInZone(centerPos, radius, pos); } @@ -310,14 +316,14 @@ bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Dire return false; } - uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); - std::string boostedMonster = g_game().getBoostedMonsterName(); + const uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); + const std::string boostedMonster = g_game().getBoostedMonsterName(); int32_t boostedrate = 1; if (name == boostedMonster) { boostedrate = 2; } // eventschedule is a whole percentage, so we need to multiply by 100 to match the order of magnitude of the other values - scheduleInterval = scheduleInterval * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * boostedrate * eventschedule)); + scheduleInterval = scheduleInterval * 100 / std::max(static_cast(1), (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * boostedrate * eventschedule)); if (scheduleInterval < MONSTER_MINSPAWN_INTERVAL) { g_logger().warn("[SpawnsMonster::addMonster] - {} {} spawntime cannot be less than {} seconds, set to {} by default.", name, pos.toString(), MONSTER_MINSPAWN_INTERVAL / 1000, MONSTER_MINSPAWN_INTERVAL / 1000); scheduleInterval = MONSTER_MINSPAWN_INTERVAL; @@ -378,9 +384,9 @@ void SpawnMonster::removeMonsters() { } void SpawnMonster::setMonsterVariant(const std::string &variant) { - for (auto &it : spawnMonsterMap) { + for (auto &[fst, snd] : spawnMonsterMap) { std::unordered_map, uint32_t> monsterTypes; - for (const auto &[monsterType, weight] : it.second.monsterTypes) { + for (const auto &[monsterType, weight] : snd.monsterTypes) { if (!monsterType || monsterType->typeName.empty()) { continue; } @@ -390,7 +396,7 @@ void SpawnMonster::setMonsterVariant(const std::string &variant) { monsterTypes.emplace(variantType, weight); } } - it.second.monsterTypes = monsterTypes; + snd.monsterTypes = monsterTypes; } } @@ -421,7 +427,7 @@ std::shared_ptr spawnBlock_t::getMonsterType() const { uint32_t randomWeight = uniform_random(0, totalWeight - 1); // order monsters by weight DESC std::vector, uint32_t>> orderedMonsterTypes(monsterTypes.begin(), monsterTypes.end()); - std::sort(orderedMonsterTypes.begin(), orderedMonsterTypes.end(), [](const auto &a, const auto &b) { + std::ranges::sort(orderedMonsterTypes, [](const auto &a, const auto &b) { return a.second > b.second; }); for (const auto &[mType, weight] : orderedMonsterTypes) { diff --git a/src/creatures/monsters/spawns/spawn_monster.hpp b/src/creatures/monsters/spawns/spawn_monster.hpp index c1f4243a5b6..02f6477a264 100644 --- a/src/creatures/monsters/spawns/spawn_monster.hpp +++ b/src/creatures/monsters/spawns/spawn_monster.hpp @@ -66,7 +66,7 @@ class SpawnMonster { void startSpawnMonsterCheck(); void stopEvent(); - bool isInSpawnMonsterZone(const Position &pos); + bool isInSpawnMonsterZone(const Position &pos) const; void cleanup(); const Position &getCenterPos() const { diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 50f3f71155e..4ad59a0179a 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -2982,7 +2982,7 @@ void Player::despawn() { size_t i = 0; for (const auto &spectator : spectators) { if (const auto &player = spectator->getPlayer()) { - oldStackPosVector.push_back(player->canSeeCreature(static_self_cast()) ? tile->getStackposOfCreature(player, getPlayer()) : -1); + oldStackPosVector.emplace_back(player->canSeeCreature(static_self_cast()) ? tile->getStackposOfCreature(player, getPlayer()) : -1); } if (const auto &player = spectator->getPlayer()) { player->sendRemoveTileThing(tile->getPosition(), oldStackPosVector[i++]); @@ -3081,7 +3081,7 @@ void Player::autoCloseContainers(const std::shared_ptr &container) { auto tmpContainer = snd.container; while (tmpContainer) { if (tmpContainer->isRemoved() || tmpContainer == container) { - closeList.push_back(fst); + closeList.emplace_back(fst); break; } @@ -4060,7 +4060,7 @@ std::vector> Player::getEquippedAugmentItemsByType(Augment for (const auto &item : equippedAugmentItems) { for (const auto &augment : item->getAugments()) { if (augment->type == augmentType) { - equippedAugmentItemsByType.push_back(item); + equippedAugmentItemsByType.emplace_back(item); } } } @@ -4197,7 +4197,7 @@ void Player::postAddNotification(const std::shared_ptr &thing, const std: } if (!Position::areInRange<1, 1, 0>(container->getPosition(), getPosition())) { - containers.push_back(container); + containers.emplace_back(container); } } @@ -5793,12 +5793,12 @@ uint8_t Player::getRandomMountId() const { const auto mounts = g_game().mounts.getMounts(); for (const auto &mount : mounts) { if (hasMount(mount)) { - playerMounts.push_back(mount->id); + playerMounts.emplace_back(mount->id); } } - auto playerMountsSize = static_cast(playerMounts.size() - 1); - auto randomIndex = uniform_random(0, std::max(0, playerMountsSize)); + const auto playerMountsSize = static_cast(playerMounts.size() - 1); + const auto randomIndex = uniform_random(0, std::max(0, playerMountsSize)); return playerMounts.at(randomIndex); } diff --git a/src/game/game.cpp b/src/game/game.cpp index d2a2c5567ff..bb216f131c9 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -534,9 +534,9 @@ void Game::start(ServiceManager* manager) { ); } - g_dispatcher().cycleEvent( - 5000, [this] { teste(); }, "Calling GC" - ); + // g_dispatcher().cycleEvent( + // 5000, [this] { teste(); }, "Calling GC" + // ); } void Game::teste() const { diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index 81fbb18b138..9f4df0821ce 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -62,7 +62,7 @@ class Task { func = nullptr; } - [[nodiscard]] bool execute() const; + bool execute() const; private: static std::atomic_uint_fast64_t LAST_EVENT_ID; From 74e70b0bfc79a0f6e766b9d98789eede8aab800b Mon Sep 17 00:00:00 2001 From: Beats Date: Sun, 1 Sep 2024 19:43:10 -0400 Subject: [PATCH 21/34] fix exploit login --- src/account/account_repository.hpp | 2 ++ src/account/account_repository_db.cpp | 10 ++++++++++ src/account/account_repository_db.hpp | 2 ++ src/io/iologindata.cpp | 7 ++++++- src/io/iologindata.hpp | 2 +- src/server/network/protocol/protocolgame.cpp | 2 +- 6 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/account/account_repository.hpp b/src/account/account_repository.hpp index 0d4dcc7abcf..3c27a7bd8df 100644 --- a/src/account/account_repository.hpp +++ b/src/account/account_repository.hpp @@ -27,6 +27,8 @@ class AccountRepository { virtual bool loadBySession(const std::string &email, AccountInfo &acc) = 0; virtual bool save(const AccountInfo &accInfo) = 0; + virtual bool getCharacterByNameAndAccountId(const uint32_t &id, const std::string &name) = 0; + virtual bool getPassword(const uint32_t &id, std::string &password) = 0; virtual bool getCoins(const uint32_t &id, const uint8_t &type, uint32_t &coins) = 0; diff --git a/src/account/account_repository_db.cpp b/src/account/account_repository_db.cpp index cb9981e3e9b..cb0d6ac6060 100644 --- a/src/account/account_repository_db.cpp +++ b/src/account/account_repository_db.cpp @@ -63,6 +63,16 @@ bool AccountRepositoryDB::save(const AccountInfo &accInfo) { return successful; } +bool AccountRepositoryDB::getCharacterByNameAndAccountId(const uint32_t &id, const std::string &name) { + auto result = g_database().storeQuery(fmt::format("SELECT `id` FROM `players` WHERE `account_id` = {} AND `name` = {}", id, g_database().escapeString(name))); + if (!result) { + g_logger().error("Failed to get character: [{}] from account: [{}]!", name, id); + return false; + } + + return result->countResults() == 1; +} + bool AccountRepositoryDB::getPassword(const uint32_t &id, std::string &password) { const auto result = g_database().storeQuery(fmt::format("SELECT * FROM `accounts` WHERE `id` = {}", id)); if (!result) { diff --git a/src/account/account_repository_db.hpp b/src/account/account_repository_db.hpp index e79440d92eb..8556239ac2c 100644 --- a/src/account/account_repository_db.hpp +++ b/src/account/account_repository_db.hpp @@ -20,6 +20,8 @@ class AccountRepositoryDB final : public AccountRepository { bool loadBySession(const std::string &esseionKey, AccountInfo &acc) override; bool save(const AccountInfo &accInfo) override; + bool getCharacterByNameAndAccountId(const uint32_t &id, const std::string &name) override; + bool getPassword(const uint32_t &id, std::string &password) override; bool getCoins(const uint32_t &id, const uint8_t &type, uint32_t &coins) override; diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index 231e0980278..2b2ccdf47ec 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -21,7 +21,7 @@ #include "enums/account_type.hpp" #include "enums/account_errors.hpp" -bool IOLoginData::gameWorldAuthentication(const std::string &accountDescriptor, const std::string &password, std::string &characterName, uint32_t &accountId, bool oldProtocol) { +bool IOLoginData::gameWorldAuthentication(const std::string &accountDescriptor, const std::string &password, std::string &characterName, uint32_t &accountId, bool oldProtocol, const uint32_t ip) { Account account(accountDescriptor); account.setProtocolCompat(oldProtocol); @@ -40,6 +40,11 @@ bool IOLoginData::gameWorldAuthentication(const std::string &accountDescriptor, } } + if (!g_accountRepository().getCharacterByNameAndAccountId(account.getID(), characterName)) { + g_logger().warn("IP [{}] trying to connect into another account character", convertIPToString(ip)); + return false; + } + if (AccountErrors_t::Ok != enumFromValue(account.load())) { g_logger().error("Failed to load account [{}]", accountDescriptor); return false; diff --git a/src/io/iologindata.hpp b/src/io/iologindata.hpp index 230f7d5fa77..da18c4f8c01 100644 --- a/src/io/iologindata.hpp +++ b/src/io/iologindata.hpp @@ -17,7 +17,7 @@ using ItemBlockList = std::list>>; class IOLoginData { public: - static bool gameWorldAuthentication(const std::string &accountDescriptor, const std::string &sessionOrPassword, std::string &characterName, uint32_t &accountId, bool oldProcotol); + static bool gameWorldAuthentication(const std::string &accountDescriptor, const std::string &sessionOrPassword, std::string &characterName, uint32_t &accountId, bool oldProcotol, const uint32_t ip); static uint8_t getAccountType(uint32_t accountId); static void updateOnlineStatus(uint32_t guid, bool login); static bool loadPlayerById(const std::shared_ptr &player, uint32_t id, bool disableIrrelevantInfo = true); diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 5d0456546f1..0fe9509523a 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -842,7 +842,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { } uint32_t accountId; - if (!IOLoginData::gameWorldAuthentication(accountDescriptor, password, characterName, accountId, oldProtocol)) { + if (!IOLoginData::gameWorldAuthentication(accountDescriptor, password, characterName, accountId, oldProtocol, getIP())) { ss.str(std::string()); if (authType == "session") { ss << "Your session has expired. Please log in again."; From 335b943f7a30432f91d7dfab5dab69b2fb2f2af3 Mon Sep 17 00:00:00 2001 From: Beats Date: Mon, 2 Sep 2024 00:56:30 -0400 Subject: [PATCH 22/34] update --- src/creatures/combat/combat.cpp | 22 +- src/creatures/combat/condition.cpp | 6 +- src/creatures/creature.cpp | 220 +++++----- src/creatures/creature.hpp | 22 +- src/creatures/creatures_definitions.hpp | 2 +- src/creatures/monsters/monster.cpp | 4 +- src/creatures/monsters/monster.hpp | 4 +- src/creatures/monsters/monsters.cpp | 40 +- src/creatures/monsters/monsters.hpp | 10 +- .../monsters/spawns/spawn_monster.cpp | 2 +- src/creatures/npcs/npc.cpp | 58 +-- src/creatures/npcs/npc.hpp | 14 +- src/creatures/npcs/npcs.cpp | 18 +- src/creatures/npcs/npcs.hpp | 2 +- src/creatures/npcs/spawns/spawn_npc.cpp | 34 +- src/creatures/npcs/spawns/spawn_npc.hpp | 4 +- .../achievement/player_achievement.cpp | 18 +- .../achievement/player_achievement.hpp | 10 +- .../players/cyclopedia/player_badge.cpp | 18 +- .../players/cyclopedia/player_badge.hpp | 28 +- .../players/cyclopedia/player_cyclopedia.cpp | 40 +- .../players/cyclopedia/player_cyclopedia.hpp | 16 +- .../players/cyclopedia/player_title.cpp | 40 +- .../players/cyclopedia/player_title.hpp | 38 +- src/creatures/players/grouping/familiars.cpp | 10 +- src/creatures/players/grouping/groups.cpp | 12 +- src/creatures/players/grouping/guild.cpp | 4 +- src/creatures/players/grouping/guild.hpp | 4 +- src/creatures/players/grouping/party.cpp | 108 ++--- src/creatures/players/grouping/party.hpp | 14 +- .../players/grouping/team_finder.hpp | 6 +- .../players/imbuements/imbuements.cpp | 42 +- .../players/imbuements/imbuements.hpp | 4 +- src/creatures/players/management/ban.cpp | 14 +- src/creatures/players/management/ban.hpp | 12 +- src/creatures/players/management/waitlist.cpp | 38 +- src/creatures/players/management/waitlist.hpp | 10 +- src/creatures/players/player.cpp | 230 +++++------ src/creatures/players/player.hpp | 78 ++-- src/creatures/players/storages/storages.cpp | 4 +- src/creatures/players/vip/player_vip.cpp | 17 +- src/creatures/players/vip/player_vip.hpp | 9 +- src/creatures/players/vocations/vocation.cpp | 44 +- src/creatures/players/wheel/player_wheel.cpp | 384 ++++++++++-------- src/creatures/players/wheel/player_wheel.hpp | 42 +- src/creatures/players/wheel/wheel_gems.cpp | 318 +++++++-------- src/creatures/players/wheel/wheel_gems.hpp | 24 +- src/game/movement/teleport.cpp | 6 +- src/game/movement/teleport.hpp | 6 +- src/items/containers/container.cpp | 6 +- src/items/containers/container.hpp | 6 +- src/items/containers/depot/depotchest.cpp | 2 +- src/items/containers/depot/depotchest.hpp | 2 +- src/items/containers/depot/depotlocker.cpp | 2 +- src/items/containers/depot/depotlocker.hpp | 2 +- src/items/containers/inbox/inbox.cpp | 2 +- src/items/containers/inbox/inbox.hpp | 2 +- src/items/containers/mailbox/mailbox.cpp | 6 +- src/items/containers/mailbox/mailbox.hpp | 6 +- src/items/containers/rewards/reward.cpp | 2 +- src/items/containers/rewards/reward.hpp | 2 +- src/items/containers/rewards/rewardchest.cpp | 2 +- src/items/containers/rewards/rewardchest.hpp | 2 +- src/items/cylinder.hpp | 13 +- src/items/tile.cpp | 6 +- src/items/tile.hpp | 6 +- src/items/trashholder.cpp | 6 +- src/items/trashholder.hpp | 8 +- src/map/house/housetile.cpp | 6 +- src/map/house/housetile.hpp | 6 +- 70 files changed, 1134 insertions(+), 1071 deletions(-) diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 313a1dd8311..ba4432a33e7 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -1449,11 +1449,11 @@ std::vector>> Combat::pickChainTargets phmap::flat_hash_set visited; if (initialTarget && initialTarget != caster) { - targets.push_back(initialTarget); + targets.emplace_back(initialTarget); visited.insert(initialTarget->getID()); - resultMap.push_back({ caster->getPosition(), { initialTarget->getID() } }); + resultMap.emplace_back(caster->getPosition(), std::vector { initialTarget->getID() }); } else { - targets.push_back(caster); + targets.emplace_back(caster); maxTargets++; } @@ -1493,10 +1493,10 @@ std::vector>> Combat::pickChainTargets } } if (!found) { - resultMap.push_back({ currentTarget->getPosition(), { closestSpectator->getID() } }); + resultMap.emplace_back(currentTarget->getPosition(), std::vector { closestSpectator->getID() }); } - targets.push_back(closestSpectator); + targets.emplace_back(closestSpectator); visited.insert(closestSpectator->getID()); continue; } @@ -2010,11 +2010,11 @@ void AreaCombat::setupArea(int32_t length, int32_t spread) { for (int32_t x = 1; x <= cols; ++x) { if (y == rows && x == ((cols - (cols % 2)) / 2) + 1) { - list.push_back(3); + list.emplace_back(3); } else if (x >= mincol && x <= maxcol) { - list.push_back(1); + list.emplace_back(1); } else { - list.push_back(0); + list.emplace_back(0); } } @@ -2048,11 +2048,11 @@ void AreaCombat::setupArea(int32_t radius) { for (auto &row : area) { for (const int cell : row) { if (cell == 1) { - list.push_back(3); + list.emplace_back(3); } else if (cell > 0 && cell <= radius) { - list.push_back(1); + list.emplace_back(1); } else { - list.push_back(0); + list.emplace_back(0); } } } diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index bcc93ae5d51..70f80298cfe 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -1505,7 +1505,7 @@ bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream &propStre return false; } - damageList.push_back(damageInfo); + damageList.emplace_back(damageInfo); if (ticks != -1) { setTicks(ticks + damageInfo.interval); } @@ -1563,7 +1563,7 @@ bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) { damageInfo.timeLeft = time; damageInfo.value = value; - damageList.push_back(damageInfo); + damageList.emplace_back(damageInfo); if (ticks != -1) { setTicks(ticks + damageInfo.interval); @@ -1819,7 +1819,7 @@ void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::lis do { sum += i; - list.push_back(i); + list.emplace_back(i); x1 = std::fabs(1.0 - ((static_cast(sum)) + i) / med); x2 = std::fabs(1.0 - (static_cast(sum) / med)); diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 835200fecc8..02dda3cab2e 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -19,7 +19,7 @@ #include "lib/metrics/metrics.hpp" Creature::Creature() { - onIdleStatus(); + Creature::onIdleStatus(); } Creature::~Creature() { @@ -85,7 +85,7 @@ int32_t Creature::getWalkDelay(Direction dir) { } int32_t Creature::getWalkSize() { - auto ret = std::distance(listWalkDir.begin(), listWalkDir.end()); + const auto ret = std::distance(listWalkDir.begin(), listWalkDir.end()); return static_cast(ret); } @@ -96,13 +96,13 @@ void Creature::onThink(uint32_t interval) { updateMapCache(); } - auto followCreature = getFollowCreature(); - auto master = getMaster(); + const auto &followCreature = getFollowCreature(); + const auto &master = getMaster(); if (followCreature && master != followCreature && !canSeeCreature(followCreature)) { onCreatureDisappear(followCreature, false); } - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (attackedCreature && master != attackedCreature && !canSeeCreature(attackedCreature)) { onCreatureDisappear(attackedCreature, false); } @@ -140,7 +140,7 @@ void Creature::onThink(uint32_t interval) { } void Creature::onAttacking(uint32_t interval) { - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (!attackedCreature) { return; } @@ -166,7 +166,7 @@ void Creature::onCreatureWalk() { Direction dir; uint32_t flags = FLAG_IGNOREFIELDDAMAGE; if (getNextStep(dir, flags)) { - ReturnValue ret = g_game().internalMoveCreature(static_self_cast(), dir, flags); + const ReturnValue ret = g_game().internalMoveCreature(static_self_cast(), dir, flags); if (ret != RETURNVALUE_NOERROR) { if (const auto &player = getPlayer()) { player->sendCancelMessage(ret); @@ -298,8 +298,8 @@ void Creature::updateTileCache(const std::shared_ptr &newTile, int32_t dx, void Creature::updateTileCache(const std::shared_ptr &upTile, const Position &pos) { const Position &myPos = getPosition(); if (pos.z == myPos.z) { - int32_t dx = Position::getOffsetX(pos, myPos); - int32_t dy = Position::getOffsetY(pos, myPos); + const int32_t dx = Position::getOffsetX(pos, myPos); + const int32_t dy = Position::getOffsetY(pos, myPos); updateTileCache(upTile, dx, dy); } } @@ -319,9 +319,9 @@ int32_t Creature::getWalkCache(const Position &pos) { return 1; } - int32_t dx = Position::getOffsetX(pos, myPos); + const int32_t dx = Position::getOffsetX(pos, myPos); if (std::abs(dx) <= maxWalkCacheWidth) { - int32_t dy = Position::getOffsetY(pos, myPos); + const int32_t dy = Position::getOffsetY(pos, myPos); if (std::abs(dy) <= maxWalkCacheHeight) { return localMapCache[maxWalkCacheHeight + dy][maxWalkCacheWidth + dx]; } @@ -389,7 +389,7 @@ void Creature::onRemoveCreature(const std::shared_ptr &creature, bool) } // Update player from monster target list (avoid memory usage after clean) - if (auto monster = getMonster(); monster && monster->getAttackedCreature() == creature) { + if (const auto &monster = getMonster(); monster && monster->getAttackedCreature() == creature) { monster->setAttackedCreature(creature); monster->setFollowCreature(creature); } @@ -410,7 +410,7 @@ void Creature::onCreatureDisappear(const std::shared_ptr &creature, bo void Creature::onChangeZone(ZoneType_t zone) { metrics::method_latency measure(__METHOD_NAME__); - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (attackedCreature && zone == ZONE_PROTECTION) { onCreatureDisappear(attackedCreature, false); } @@ -419,7 +419,7 @@ void Creature::onChangeZone(ZoneType_t zone) { void Creature::onAttackedCreatureChangeZone(ZoneType_t zone) { metrics::method_latency measure(__METHOD_NAME__); if (zone == ZONE_PROTECTION) { - auto attackedCreature = getAttackedCreature(); + const auto &attackedCreature = getAttackedCreature(); if (attackedCreature) { onCreatureDisappear(attackedCreature, false); } @@ -434,11 +434,11 @@ void Creature::checkSummonMove(const Position &newPos, bool teleportSummon) { const auto &pos = summon->getPosition(); const auto &monster = summon->getMonster(); const auto &tile = getTile(); - bool protectionZoneCheck = tile ? tile->hasFlag(TILESTATE_PROTECTIONZONE) : false; + const bool protectionZoneCheck = tile ? tile->hasFlag(TILESTATE_PROTECTIONZONE) : false; // Check if any of our summons is out of range (+/- 0 floors or 15 tiles away) - bool checkSummonDist = Position::getDistanceZ(newPos, pos) > 0 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 15); + const bool checkSummonDist = Position::getDistanceZ(newPos, pos) > 0 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 15); // Check if any of our summons is out of range (+/- 2 floors or 30 tiles away) - bool checkRemoveDist = Position::getDistanceZ(newPos, pos) > 2 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 30); + const bool checkRemoveDist = Position::getDistanceZ(newPos, pos) > 2 || (std::max(Position::getDistanceX(newPos, pos), Position::getDistanceY(newPos, pos)) > 30); if ((monster && monster->isFamiliar() && checkSummonDist) || (teleportSummon && !protectionZoneCheck && checkSummonDist)) { const auto &creatureMaster = summon->getMaster(); @@ -457,7 +457,7 @@ void Creature::checkSummonMove(const Position &newPos, bool teleportSummon) { } if (monster && monster->isSummon() && !monster->isFamiliar() && !teleportSummon && checkRemoveDist) { - despawnMonsterList.push_back(summon); + despawnMonsterList.emplace_back(summon); } } @@ -485,7 +485,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s stopEventWalk(); } - bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS, __FUNCTION__); + const bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS, __FUNCTION__); checkSummonMove(newPos, configTeleportSummons); if (isLostSummon()) { handleLostSummon(configTeleportSummons); @@ -550,7 +550,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s // shift y west int32_t starty = 0; int32_t endy = mapWalkHeight - 1; - int32_t dy = Position::getDistanceY(oldPos, newPos); + const int32_t dy = Position::getDistanceY(oldPos, newPos); if (dy < 0) { endy += dy; @@ -573,7 +573,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s // shift y east int32_t starty = 0; int32_t endy = mapWalkHeight - 1; - int32_t dy = Position::getDistanceY(oldPos, newPos); + const int32_t dy = Position::getDistanceY(oldPos, newPos); if (dy < 0) { endy += dy; @@ -589,7 +589,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s // update 0 for (int32_t y = -maxWalkCacheHeight; y <= maxWalkCacheHeight; ++y) { - std::shared_ptr cacheTile = g_game().map.getTile(myPos.x - maxWalkCacheWidth, static_cast(myPos.y + y), myPos.z); + const auto &cacheTile = g_game().map.getTile(myPos.x - maxWalkCacheWidth, static_cast(myPos.y + y), myPos.z); updateTileCache(cacheTile, -maxWalkCacheWidth, y); } } @@ -644,7 +644,7 @@ void Creature::onDeath() { metrics::method_latency measure(__METHOD_NAME__); bool lastHitUnjustified = false; bool mostDamageUnjustified = false; - std::shared_ptr lastHitCreature = g_game().getCreatureByID(lastHitCreatureId); + const auto &lastHitCreature = g_game().getCreatureByID(lastHitCreatureId); std::shared_ptr lastHitCreatureMaster; if (lastHitCreature && getPlayer()) { /** @@ -664,21 +664,21 @@ void Creature::onDeath() { int32_t mostDamage = 0; std::map, uint64_t> experienceMap; std::unordered_set> killers; - for (const auto &it : damageMap) { - if (auto attacker = g_game().getCreatureByID(it.first)) { - CountBlock_t cb = it.second; - if ((cb.total > mostDamage && (timeNow - cb.ticks <= inFightTicks))) { - mostDamage = cb.total; + for (const auto &[fst, snd] : damageMap) { + if (auto attacker = g_game().getCreatureByID(fst)) { + const auto [total, ticks] = snd; + if ((total > mostDamage && (timeNow - ticks <= inFightTicks))) { + mostDamage = total; mostDamageCreature = attacker; } if (attacker != getCreature()) { - uint64_t gainExp = getGainedExperience(attacker); - auto attackerMaster = attacker->getMaster() ? attacker->getMaster() : attacker; + const uint64_t gainExp = getGainedExperience(attacker); + const auto &attackerMaster = attacker->getMaster() ? attacker->getMaster() : attacker; if (auto attackerPlayer = attackerMaster->getPlayer()) { attackerPlayer->removeAttacked(getPlayer()); - auto party = attackerPlayer->getParty(); + const auto &party = attackerPlayer->getParty(); killers.insert(attackerPlayer); if (party && party->getLeader() && party->isSharedExperienceActive() && party->isSharedExperienceEnabled()) { attacker = party->getLeader(); @@ -701,13 +701,13 @@ void Creature::onDeath() { } } - for (const auto &it : experienceMap) { - it.first->onGainExperience(it.second, getCreature()); + for (const auto &[fst, snd] : experienceMap) { + fst->onGainExperience(snd, getCreature()); } mostDamageCreature = mostDamageCreature && mostDamageCreature->getMaster() ? mostDamageCreature->getMaster() : mostDamageCreature; for (const auto &killer : killers) { - if (auto monster = getMonster()) { + if (const auto &monster = getMonster()) { killer->onKilledMonster(monster); } else if (const auto &player = getPlayer(); player && mostDamageCreature != killer) { killer->onKilledPlayer(player, false); @@ -717,14 +717,14 @@ void Creature::onDeath() { /** * @deprecated -- This is here to trigger the deprecated onKill events in lua */ - auto mostDamageCreatureMaster = mostDamageCreature ? mostDamageCreature->getMaster() : nullptr; + const auto &mostDamageCreatureMaster = mostDamageCreature ? mostDamageCreature->getMaster() : nullptr; if (mostDamageCreature && (mostDamageCreature != lastHitCreature || getMonster()) && mostDamageCreature != lastHitCreatureMaster) { if (lastHitCreature != mostDamageCreatureMaster && (lastHitCreatureMaster == nullptr || mostDamageCreatureMaster != lastHitCreatureMaster)) { mostDamageUnjustified = mostDamageCreature->deprecatedOnKilledCreature(getCreature(), false); } } - bool killedByPlayer = (mostDamageCreature && mostDamageCreature->getPlayer()) || (mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer()); + const bool killedByPlayer = (mostDamageCreature && mostDamageCreature->getPlayer()) || (mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer()); if (getPlayer()) { g_metrics().addCounter( "player_death", @@ -758,7 +758,7 @@ void Creature::onDeath() { ); } - bool droppedCorpse = dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); + const bool droppedCorpse = dropCorpse(lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); death(lastHitCreature); if (droppedCorpse && !getPlayer()) { @@ -802,27 +802,27 @@ bool Creature::dropCorpse(const std::shared_ptr &lastHitCreature, cons break; } - std::shared_ptr tile = getTile(); + const auto &tile = getTile(); if (tile && splash) { g_game().internalAddItem(tile, splash, INDEX_WHEREEVER, FLAG_NOLIMIT); splash->startDecaying(); } - std::shared_ptr corpse = getCorpse(lastHitCreature, mostDamageCreature); + const auto &corpse = getCorpse(lastHitCreature, mostDamageCreature); if (tile && corpse) { g_game().internalAddItem(tile, corpse, INDEX_WHEREEVER, FLAG_NOLIMIT); dropLoot(corpse->getContainer(), lastHitCreature); corpse->startDecaying(); - bool disallowedCorpses = corpse->isRewardCorpse() || (corpse->getID() == ITEM_MALE_CORPSE || corpse->getID() == ITEM_FEMALE_CORPSE); + const bool disallowedCorpses = corpse->isRewardCorpse() || (corpse->getID() == ITEM_MALE_CORPSE || corpse->getID() == ITEM_FEMALE_CORPSE); const auto &player = mostDamageCreature ? mostDamageCreature->getPlayer() : nullptr; - auto corpseContainer = corpse->getContainer(); + const auto &corpseContainer = corpse->getContainer(); if (corpseContainer && player && !disallowedCorpses) { - auto monster = getMonster(); + const auto &monster = getMonster(); if (monster && !monster->isRewardBoss()) { std::ostringstream lootMessage; - auto collorMessage = player->getProtocolVersion() > 1200 && player->getOperatingSystem() < CLIENTOS_OTCLIENT_LINUX; + const auto collorMessage = player->getProtocolVersion() > 1200 && player->getOperatingSystem() < CLIENTOS_OTCLIENT_LINUX; lootMessage << "Loot of " << getNameDescription() << ": " << corpseContainer->getContentDescription(collorMessage) << "."; - auto suffix = corpseContainer->getAttribute(ItemAttribute_t::LOOTMESSAGE_SUFFIX); + const auto suffix = corpseContainer->getAttribute(ItemAttribute_t::LOOTMESSAGE_SUFFIX); if (!suffix.empty()) { lootMessage << suffix; } @@ -837,7 +837,7 @@ bool Creature::dropCorpse(const std::shared_ptr &lastHitCreature, cons fpp.maxSearchDist = 0; std::vector dirList; - auto isReachable = g_game().map.getPathMatching(player->getPosition(), dirList, FrozenPathingConditionCall(corpse->getPosition()), fpp); + const auto isReachable = g_game().map.getPathMatching(player->getPosition(), dirList, FrozenPathingConditionCall(corpse->getPosition()), fpp); if (player->checkAutoLoot(monster->isRewardBoss()) && isReachable) { g_dispatcher().addEvent([player, corpseContainer, corpsePosition = corpse->getPosition()] { @@ -860,7 +860,7 @@ bool Creature::dropCorpse(const std::shared_ptr &lastHitCreature, cons } bool Creature::hasBeenAttacked(uint32_t attackerId) { - auto it = damageMap.find(attackerId); + const auto it = damageMap.find(attackerId); if (it == damageMap.end()) { return false; } @@ -875,7 +875,7 @@ std::shared_ptr Creature::getCorpse(const std::shared_ptr &, con } void Creature::changeHealth(int32_t healthChange, bool sendHealthChange /* = true*/) { - int32_t oldHealth = health; + const int32_t oldHealth = health; if (healthChange > 0) { health += std::min(healthChange, getMaxHealth() - health); @@ -914,7 +914,7 @@ void Creature::drainHealth(const std::shared_ptr &attacker, int32_t da } } -void Creature::drainMana(std::shared_ptr attacker, int32_t manaLoss) { +void Creature::drainMana(const std::shared_ptr &attacker, int32_t manaLoss) { onAttacked(); changeMana(-manaLoss); @@ -980,7 +980,7 @@ BlockType_t Creature::blockHit(const std::shared_ptr &attacker, const } if (checkDefense && hasDefense && canUseDefense) { - int32_t defense = getDefense(); + const int32_t defense = getDefense(); damage -= uniform_random(defense / 2, defense); if (damage <= 0) { damage = 0; @@ -990,7 +990,7 @@ BlockType_t Creature::blockHit(const std::shared_ptr &attacker, const } if (checkArmor) { - int32_t armor = getArmor(); + const int32_t armor = getArmor(); if (armor > 3) { damage -= uniform_random(armor / 2, armor - (armor % 2 + 1)); } else if (armor > 0) { @@ -1026,8 +1026,8 @@ BlockType_t Creature::blockHit(const std::shared_ptr &attacker, const bool Creature::setAttackedCreature(const std::shared_ptr &creature) { if (creature) { - auto monster = getMonster(); - auto tile = getTile(); + const auto &monster = getMonster(); + const auto &tile = getTile(); if (monster && monster->isFamiliar() && tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { return false; } @@ -1110,7 +1110,7 @@ void Creature::goToFollowCreature() { // if we can't get anything then let the A* calculate executeOnFollow = false; } else if (dir != DIRECTION_NONE) { - listDir.push_back(dir); + listDir.emplace_back(dir); hasFollowPath = true; } } @@ -1127,11 +1127,11 @@ void Creature::goToFollowCreature() { } bool Creature::canFollowMaster() const { - auto master = getMaster(); + const auto &master = getMaster(); if (!master) { return false; } - auto tile = master->getTile(); + const auto &tile = master->getTile(); return tile && !tile->hasFlag(TILESTATE_PROTECTIONZONE) && (canSeeInvisibility() || !master->isInvisible()); } @@ -1175,11 +1175,11 @@ double Creature::getDamageRatio(const std::shared_ptr &attacker) const uint32_t totalDamage = 0; uint32_t attackerDamage = 0; - for (const auto &it : damageMap) { - const CountBlock_t &cb = it.second; - totalDamage += cb.total; - if (it.first == attacker->getID()) { - attackerDamage += cb.total; + for (const auto &[fst, snd] : damageMap) { + const auto &[total, ticks] = snd; + totalDamage += total; + if (fst == attacker->getID()) { + attackerDamage += total; } } @@ -1199,9 +1199,9 @@ void Creature::addDamagePoints(const std::shared_ptr &attacker, int32_ return; } - uint32_t attackerId = attacker->id; + const uint32_t attackerId = attacker->id; - auto it = damageMap.find(attackerId); + const auto it = damageMap.find(attackerId); if (it == damageMap.end()) { CountBlock_t cb {}; cb.ticks = OTSYS_TIME(); @@ -1232,8 +1232,8 @@ void Creature::onEndCondition(const ConditionType_t &) { } void Creature::onTickCondition(ConditionType_t type, bool &bRemove) { - auto tile = getTile(); - std::shared_ptr field = tile ? tile->getFieldItem() : nullptr; + const auto &tile = getTile(); + const auto &field = tile ? tile->getFieldItem() : nullptr; if (!field) { return; } @@ -1283,14 +1283,14 @@ void Creature::onAttackedCreatureDrainHealth(const std::shared_ptr &ta void Creature::onAttackedCreatureKilled(const std::shared_ptr &target) { metrics::method_latency measure(__METHOD_NAME__); if (target != getCreature()) { - uint64_t gainExp = target->getGainedExperience(static_self_cast()); + const uint64_t gainExp = target->getGainedExperience(static_self_cast()); onGainExperience(gainExp, target); } } bool Creature::deprecatedOnKilledCreature(const std::shared_ptr &target, bool lastHit) { metrics::method_latency measure(__METHOD_NAME__); - auto master = getMaster(); + const auto &master = getMaster(); if (master) { master->deprecatedOnKilledCreature(target, lastHit); } @@ -1305,20 +1305,20 @@ bool Creature::deprecatedOnKilledCreature(const std::shared_ptr &targe void Creature::onGainExperience(uint64_t gainExp, const std::shared_ptr &target) { metrics::method_latency measure(__METHOD_NAME__); - auto master = getMaster(); + const auto &master = getMaster(); if (gainExp == 0 || !master) { return; } - std::shared_ptr m = getMonster(); + const auto &m = getMonster(); if (!m->isFamiliar()) { gainExp /= 2; } - master->onGainExperience(gainExp, std::move(target)); + master->onGainExperience(gainExp, target); if (!m->isFamiliar()) { - auto spectators = Spectators().find(position); + const auto spectators = Spectators().find(position); if (spectators.empty()) { return; } @@ -1338,7 +1338,7 @@ bool Creature::setMaster(const std::shared_ptr &newMaster, bool reload metrics::method_latency measure(__METHOD_NAME__); // Persists if this creature has ever been a summon this->summoned = true; - auto oldMaster = getMaster(); + const auto &oldMaster = getMaster(); if (!newMaster && !oldMaster) { return false; @@ -1375,14 +1375,14 @@ bool Creature::addCondition(const std::shared_ptr &condition, bool at if (isSuppress(condition->getType(), attackerPlayer)) { return false; } - std::shared_ptr prevCond = getCondition(condition->getType(), condition->getId(), condition->getSubId()); + const auto &prevCond = getCondition(condition->getType(), condition->getId(), condition->getSubId()); if (prevCond) { prevCond->addCondition(getCreature(), condition); return true; } if (condition->startCondition(getCreature())) { - conditions.push_back(condition); + conditions.emplace_back(condition); onAddCondition(condition->getType()); return true; } @@ -1392,7 +1392,7 @@ bool Creature::addCondition(const std::shared_ptr &condition, bool at bool Creature::addCombatCondition(const std::shared_ptr &condition, bool attackerPlayer /* = false*/) { // Caution: condition variable could be deleted after the call to addCondition - ConditionType_t type = condition->getType(); + const ConditionType_t type = condition->getType(); if (!addCondition(condition, attackerPlayer)) { return false; @@ -1404,9 +1404,10 @@ bool Creature::addCombatCondition(const std::shared_ptr &condition, b void Creature::removeCondition(ConditionType_t type) { metrics::method_latency measure(__METHOD_NAME__); - auto it = conditions.begin(), end = conditions.end(); + auto it = conditions.begin(); + const auto end = conditions.end(); while (it != end) { - std::shared_ptr condition = *it; + const auto &condition = *it; if (condition->getType() != type) { ++it; continue; @@ -1422,16 +1423,17 @@ void Creature::removeCondition(ConditionType_t type) { void Creature::removeCondition(ConditionType_t conditionType, ConditionId_t conditionId, bool force /* = false*/) { metrics::method_latency measure(__METHOD_NAME__); - auto it = conditions.begin(), end = conditions.end(); + auto it = conditions.begin(); + const auto end = conditions.end(); while (it != end) { - std::shared_ptr condition = *it; + const auto &condition = *it; if (condition->getType() != conditionType || condition->getId() != conditionId) { ++it; continue; } if (!force && conditionType == CONDITION_PARALYZE) { - int32_t walkDelay = getWalkDelay(); + const int32_t walkDelay = getWalkDelay(); if (walkDelay > 0) { g_dispatcher().scheduleEvent( walkDelay, [creatureId = getID(), conditionType, conditionId] { g_game().forceRemoveCondition(creatureId, conditionType, conditionId); }, "Game::forceRemoveCondition" @@ -1452,7 +1454,7 @@ void Creature::removeCombatCondition(ConditionType_t type) { std::vector> removeConditions; for (const auto &condition : conditions) { if (condition->getType() == type) { - removeConditions.push_back(condition); + removeConditions.emplace_back(condition); } } @@ -1496,7 +1498,7 @@ std::vector> Creature::getConditionsByType(ConditionT std::vector> conditionsVec; for (const auto &condition : conditions) { if (condition->getType() == type) { - conditionsVec.push_back(condition); + conditionsVec.emplace_back(condition); } } return conditionsVec; @@ -1504,9 +1506,10 @@ std::vector> Creature::getConditionsByType(ConditionT void Creature::executeConditions(uint32_t interval) { metrics::method_latency measure(__METHOD_NAME__); - auto it = conditions.begin(), end = conditions.end(); + auto it = conditions.begin(); + const auto end = conditions.end(); while (it != end) { - std::shared_ptr condition = *it; + const auto &condition = *it; if (!condition->executeCondition(getCreature(), interval)) { ConditionType_t type = condition->getType(); @@ -1527,7 +1530,7 @@ bool Creature::hasCondition(ConditionType_t type, uint32_t subId /* = 0*/) const return false; } - int64_t timeNow = OTSYS_TIME(); + const int64_t timeNow = OTSYS_TIME(); for (const auto &condition : conditions) { if (condition->getType() != type || condition->getSubId() != subId) { continue; @@ -1546,7 +1549,7 @@ uint16_t Creature::getStepDuration(Direction dir) { } if (walk.needRecache()) { - auto duration = std::floor(1000 * walk.groundSpeed / walk.calculatedStepSpeed); + const auto duration = std::floor(1000 * walk.groundSpeed / walk.calculatedStepSpeed); walk.duration = static_cast(std::ceil(duration / SERVER_BEAT) * SERVER_BEAT); } @@ -1582,7 +1585,7 @@ void Creature::setSpeed(int32_t varSpeedDelta) { return; } - int32_t oldSpeed = getSpeed(); + const int32_t oldSpeed = getSpeed(); varSpeed = varSpeedDelta; if (getSpeed() <= 0) { @@ -1604,12 +1607,12 @@ void Creature::setNormalCreatureLight() { } bool Creature::registerCreatureEvent(const std::string &name) { - const auto event = g_creatureEvents().getEventByName(name); + const auto &event = g_creatureEvents().getEventByName(name); if (!event) { return false; } - CreatureEventType_t type = event->getEventType(); + const CreatureEventType_t type = event->getEventType(); if (hasEventRegistered(type)) { for (const auto &creatureEventPtr : eventsList) { if (creatureEventPtr == event) { @@ -1620,26 +1623,27 @@ bool Creature::registerCreatureEvent(const std::string &name) { scriptEventsBitField |= static_cast(1) << type; } - eventsList.push_back(event); + eventsList.emplace_back(event); return true; } bool Creature::unregisterCreatureEvent(const std::string &name) { - const auto event = g_creatureEvents().getEventByName(name); + const auto &event = g_creatureEvents().getEventByName(name); if (!event) { return false; } - CreatureEventType_t type = event->getEventType(); + const CreatureEventType_t type = event->getEventType(); if (!hasEventRegistered(type)) { return false; } bool resetTypeBit = true; - auto it = eventsList.begin(), end = eventsList.end(); + auto it = eventsList.begin(); + const auto end = eventsList.end(); while (it != end) { - const auto curEvent = *it; + const auto &curEvent = *it; if (curEvent == event) { it = eventsList.erase(it); continue; @@ -1657,7 +1661,7 @@ bool Creature::unregisterCreatureEvent(const std::string &name) { return true; } -CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) { +CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) const { CreatureEventList tmpEventList; if (!hasEventRegistered(type)) { @@ -1666,7 +1670,7 @@ CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) { for (const auto &creatureEventPtr : eventsList) { if (creatureEventPtr->getEventType() == type) { - tmpEventList.push_back(creatureEventPtr); + tmpEventList.emplace_back(creatureEventPtr); } } @@ -1691,26 +1695,26 @@ bool FrozenPathingConditionCall::isInRange(const Position &startPos, const Posit return false; } } else { - int_fast32_t dx = Position::getOffsetX(startPos, targetPos); + const int_fast32_t dx = Position::getOffsetX(startPos, targetPos); - int32_t dxMax = (dx >= 0 ? fpp.maxTargetDist : 0); + const int32_t dxMax = (dx >= 0 ? fpp.maxTargetDist : 0); if (testPos.x > targetPos.x + dxMax) { return false; } - int32_t dxMin = (dx <= 0 ? fpp.maxTargetDist : 0); + const int32_t dxMin = (dx <= 0 ? fpp.maxTargetDist : 0); if (testPos.x < targetPos.x - dxMin) { return false; } - int_fast32_t dy = Position::getOffsetY(startPos, targetPos); + const int_fast32_t dy = Position::getOffsetY(startPos, targetPos); - int32_t dyMax = (dy >= 0 ? fpp.maxTargetDist : 0); + const int32_t dyMax = (dy >= 0 ? fpp.maxTargetDist : 0); if (testPos.y > targetPos.y + dyMax) { return false; } - int32_t dyMin = (dy <= 0 ? fpp.maxTargetDist : 0); + const int32_t dyMin = (dy <= 0 ? fpp.maxTargetDist : 0); if (testPos.y < targetPos.y - dyMin) { return false; } @@ -1726,20 +1730,22 @@ bool FrozenPathingConditionCall::operator()(const Position &startPos, const Posi return false; } - int32_t testDist = std::max(Position::getDistanceX(targetPos, testPos), Position::getDistanceY(targetPos, testPos)); + const int32_t testDist = std::max(Position::getDistanceX(targetPos, testPos), Position::getDistanceY(targetPos, testPos)); if (fpp.maxTargetDist == 1) { if (testDist < fpp.minTargetDist || testDist > fpp.maxTargetDist) { return false; } return true; - } else if (testDist <= fpp.maxTargetDist) { + } + if (testDist <= fpp.maxTargetDist) { if (testDist < fpp.minTargetDist) { return false; } if (testDist == fpp.maxTargetDist) { bestMatchDist = 0; return true; - } else if (testDist > bestMatchDist) { + } + if (testDist > bestMatchDist) { // not quite what we want, but the best so far bestMatchDist = testDist; return true; @@ -1749,7 +1755,7 @@ bool FrozenPathingConditionCall::operator()(const Position &startPos, const Posi } bool Creature::isInvisible() const { - return std::find_if(conditions.begin(), conditions.end(), [](const std::shared_ptr &condition) { + return std::ranges::find_if(conditions, [](const std::shared_ptr &condition) { return condition->getType() == CONDITION_INVISIBLE; }) != conditions.end(); @@ -1773,7 +1779,7 @@ bool Creature::getPathTo(const Position &targetPos, std::vector &dirL return getPathTo(targetPos, dirList, fpp); } -void Creature::turnToCreature(std::shared_ptr creature) { +void Creature::turnToCreature(const std::shared_ptr &creature) { const Position &creaturePos = creature->getPosition(); const auto dx = Position::getOffsetX(position, creaturePos); const auto dy = Position::getOffsetY(position, creaturePos); @@ -1912,7 +1918,7 @@ std::unordered_set> Creature::getZones() { } void Creature::iconChanged() { - auto tile = getTile(); + const auto &tile = getTile(); if (!tile) { return; } diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index 0a6bf68a8f4..a7b31ecec5d 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -125,7 +125,7 @@ class Creature : virtual public Thing, public SharedObject { virtual Skulls_t getSkull() const { return skull; } - virtual Skulls_t getSkullClient(std::shared_ptr creature) { + virtual Skulls_t getSkullClient(const std::shared_ptr &creature) { return creature->getSkull(); } void setSkull(Skulls_t newSkull); @@ -242,7 +242,7 @@ class Creature : virtual public Thing, public SharedObject { icons.reserve(creatureIcons.size()); for (const auto &[_, icon] : creatureIcons) { if (icon.isSet()) { - icons.push_back(icon); + icons.emplace_back(icon); } } return icons; @@ -275,14 +275,14 @@ class Creature : virtual public Thing, public SharedObject { Outfit_t getCurrentOutfit() const { return currentOutfit; } - void setCurrentOutfit(Outfit_t outfit) { + void setCurrentOutfit(const Outfit_t &outfit) { currentOutfit = outfit; } Outfit_t getDefaultOutfit() const { return defaultOutfit; } bool isWearingSupportOutfit() const { - auto outfit = currentOutfit.lookType; + const auto outfit = currentOutfit.lookType; return outfit == 75 || outfit == 266 || outfit == 302; } bool isInvisible() const; @@ -324,7 +324,7 @@ class Creature : virtual public Thing, public SharedObject { } // combat functions - std::shared_ptr getAttackedCreature() { + std::shared_ptr getAttackedCreature() const { return m_attackedCreature.lock(); } virtual bool setAttackedCreature(const std::shared_ptr &creature); @@ -426,7 +426,7 @@ class Creature : virtual public Thing, public SharedObject { void gainHealth(const std::shared_ptr &attacker, int32_t healthGain); virtual void drainHealth(const std::shared_ptr &attacker, int32_t damage); - virtual void drainMana(std::shared_ptr attacker, int32_t manaLoss); + virtual void drainMana(const std::shared_ptr &attacker, int32_t manaLoss); virtual bool challengeCreature(const std::shared_ptr &, [[maybe_unused]] int targetChangeCooldown) { return false; @@ -461,7 +461,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void onGainExperience(uint64_t gainExp, const std::shared_ptr &target); virtual void onAttackedCreatureBlockHit(const BlockType_t &) { } virtual void onBlockHit() { } - virtual void onTakeDamage(std::shared_ptr, int32_t) { } + virtual void onTakeDamage(const std::shared_ptr &, int32_t) { } virtual void onChangeZone(ZoneType_t zone); virtual void onAttackedCreatureChangeZone(ZoneType_t zone); virtual void onIdleStatus(); @@ -475,7 +475,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void onCreatureWalk(); virtual bool getNextStep(Direction &dir, uint32_t &flags); - virtual void turnToCreature(std::shared_ptr creature); + virtual void turnToCreature(const std::shared_ptr &creature); void onAddTileItem(const std::shared_ptr &tile, const Position &pos); virtual void onUpdateTileItem(const std::shared_ptr &tile, const Position &pos, const std::shared_ptr &oldItem, const ItemType &oldType, const std::shared_ptr &newItem, const ItemType &newType); @@ -801,7 +801,7 @@ class Creature : virtual public Thing, public SharedObject { bool hasEventRegistered(CreatureEventType_t event) const { return (0 != (scriptEventsBitField & (static_cast(1) << event))); } - CreatureEventList getCreatureEvents(CreatureEventType_t type); + CreatureEventList getCreatureEvents(CreatureEventType_t type) const; void updateMapCache(); void updateTileCache(const std::shared_ptr &tile, int32_t dx, int32_t dy); @@ -815,12 +815,12 @@ class Creature : virtual public Thing, public SharedObject { virtual uint64_t getLostExperience() const { return 0; } - virtual void dropLoot(const std::shared_ptr &, std::shared_ptr) { } + virtual void dropLoot(const std::shared_ptr &, const std::shared_ptr &) { } virtual uint16_t getLookCorpse() const { return 0; } virtual void getPathSearchParams(const std::shared_ptr &, FindPathParams &fpp); - virtual void death(std::shared_ptr) { } + virtual void death(const std::shared_ptr &) { } virtual bool dropCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified); virtual std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature); diff --git a/src/creatures/creatures_definitions.hpp b/src/creatures/creatures_definitions.hpp index 0eeeef7fc1d..4eeb355dd4f 100644 --- a/src/creatures/creatures_definitions.hpp +++ b/src/creatures/creatures_definitions.hpp @@ -1638,7 +1638,7 @@ struct ShopBlock { std::vector childShop; ShopBlock() : - itemId(0), itemName(""), itemSubType(0), itemBuyPrice(0), itemSellPrice(0), itemStorageKey(0), itemStorageValue(0) { } + itemId(0), itemSubType(0), itemBuyPrice(0), itemSellPrice(0), itemStorageKey(0), itemStorageValue(0) { } explicit ShopBlock(uint16_t newItemId, std::string newName = "", int32_t newSubType = 0, uint32_t newBuyPrice = 0, uint32_t newSellPrice = 0, int32_t newStorageKey = 0, int32_t newStorageValue = 0) : itemId(newItemId), itemName(std::move(newName)), itemSubType(newSubType), itemBuyPrice(newBuyPrice), itemSellPrice(newSellPrice), itemStorageKey(newStorageKey), itemStorageValue(newStorageValue) { } diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index 9892f29de42..834702fc160 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -1935,7 +1935,7 @@ bool Monster::canWalkTo(Position pos, Direction moveDirection) { return false; } -void Monster::death(std::shared_ptr) { +void Monster::death(const std::shared_ptr &) { if (monsterForgeClassification > ForgeClassifications_t::FORGE_NORMAL_MONSTER) { g_game().removeForgeMonster(getID(), monsterForgeClassification, true); } @@ -2069,7 +2069,7 @@ void Monster::updateLookDirection() { g_game().internalCreatureTurn(getMonster(), newDir); } -void Monster::dropLoot(const std::shared_ptr &corpse, std::shared_ptr) { +void Monster::dropLoot(const std::shared_ptr &corpse, const std::shared_ptr &) { if (corpse && lootDrop) { // Only fiendish drops sliver if (const ForgeClassifications_t classification = getMonsterForgeClassification(); diff --git a/src/creatures/monsters/monster.hpp b/src/creatures/monsters/monster.hpp index 2367aa86321..4ef95217ac5 100644 --- a/src/creatures/monsters/monster.hpp +++ b/src/creatures/monsters/monster.hpp @@ -413,7 +413,7 @@ class Monster final : public Creature { bool addTarget(const std::shared_ptr &creature, bool pushFront = false); bool removeTarget(const std::shared_ptr &creature); - void death(std::shared_ptr lastHitCreature) override; + void death(const std::shared_ptr &lastHitCreature) override; std::shared_ptr getCorpse(const std::shared_ptr &lastHitCreature, const std::shared_ptr &mostDamageCreature) override; void setIdle(bool idle); @@ -452,7 +452,7 @@ class Monster final : public Creature { uint16_t getLookCorpse() const override { return mType->info.lookcorpse; } - void dropLoot(const std::shared_ptr &corpse, std::shared_ptr lastHitCreature) override; + void dropLoot(const std::shared_ptr &corpse, const std::shared_ptr &lastHitCreature) override; void getPathSearchParams(const std::shared_ptr &creature, FindPathParams &fpp) override; bool useCacheMap() const override { // return !randomStepping; diff --git a/src/creatures/monsters/monsters.cpp b/src/creatures/monsters/monsters.cpp index eddde3ff749..56cc7a5fcce 100644 --- a/src/creatures/monsters/monsters.cpp +++ b/src/creatures/monsters/monsters.cpp @@ -16,23 +16,23 @@ #include "game/game.hpp" #include "items/weapons/weapons.hpp" -void MonsterType::loadLoot(const std::shared_ptr &monsterType, LootBlock lootBlock) { +void MonsterType::loadLoot(const std::shared_ptr &monsterType, LootBlock lootBlock) const { if (lootBlock.childLoot.empty()) { - bool isContainer = Item::items[lootBlock.id].isContainer(); + const bool isContainer = Item::items[lootBlock.id].isContainer(); if (isContainer) { for (const LootBlock &child : lootBlock.childLoot) { - lootBlock.childLoot.push_back(child); + lootBlock.childLoot.emplace_back(child); } } - monsterType->info.lootItems.push_back(lootBlock); + monsterType->info.lootItems.emplace_back(lootBlock); } else { - monsterType->info.lootItems.push_back(lootBlock); + monsterType->info.lootItems.emplace_back(lootBlock); } } bool MonsterType::canSpawn(const Position &pos) const { bool canSpawn = true; - bool isDay = g_game().gameIsDay(); + const bool isDay = g_game().gameIsDay(); if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { // It will ignore day and night if underground @@ -42,7 +42,7 @@ bool MonsterType::canSpawn(const Position &pos) const { return canSpawn; } -std::shared_ptr Monsters::getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) { +std::shared_ptr Monsters::getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) const { const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, 0, 0)->static_self_cast(); condition->setParam(CONDITION_PARAM_TICKINTERVAL, tickInterval); condition->setParam(CONDITION_PARAM_MINVALUE, minDamage); @@ -52,7 +52,7 @@ std::shared_ptr Monsters::getDamageCondition(ConditionType_t co return condition; } -bool Monsters::deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description) { +bool Monsters::deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description) const { if (!spell->scriptName.empty()) { spell->isScripted = true; } else if (!spell->name.empty()) { @@ -62,8 +62,8 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel } sb.speed = spell->interval; - sb.chance = std::min((int)spell->chance, 100); - sb.range = std::min((int)spell->range, MAP_MAX_VIEW_PORT_X * 2); + sb.chance = std::min(static_cast(spell->chance), 100); + sb.range = std::min(static_cast(spell->range), MAP_MAX_VIEW_PORT_X * 2); sb.minCombatValue = std::min(spell->minCombatValue, spell->maxCombatValue); sb.maxCombatValue = std::max(spell->minCombatValue, spell->maxCombatValue); sb.soundCastEffect = spell->soundCastEffect; @@ -96,7 +96,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel combatPtr->setArea(area); } - if (std::string spellName = asLowerCaseString(spell->name); + if (const std::string spellName = asLowerCaseString(spell->name); spellName == "melee") { sb.isMelee = true; @@ -144,7 +144,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel } const auto &condition = Condition::createCondition(CONDITIONID_COMBAT, conditionType, duration, 0)->static_self_cast(); - float multiplier = 1.0f + static_cast(speedChange) / 1000.0f; + const float multiplier = 1.0f + static_cast(speedChange) / 1000.0f; condition->setFormulaVars(multiplier / 2, 40, multiplier, 40); combatPtr->addCondition(condition); } else if (spellName == "outfit") { @@ -231,7 +231,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel // If a spell has a condition, it always applies, no matter what kind of spell it is if (spell->conditionType != CONDITION_NONE) { - int32_t minDamage = std::abs(spell->conditionMinDamage); + const int32_t minDamage = std::abs(spell->conditionMinDamage); int32_t maxDamage = std::abs(spell->conditionMaxDamage); int32_t startDamage = std::abs(spell->conditionStartDamage); uint32_t tickInterval = 2000; @@ -271,7 +271,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr &spell, spel } bool MonsterType::loadCallback(LuaScriptInterface* scriptInterface) { - int32_t id = scriptInterface->getEvent(); + const int32_t id = scriptInterface->getEvent(); if (id == -1) { g_logger().warn("[MonsterType::loadCallback] - Event not found"); return false; @@ -294,10 +294,10 @@ bool MonsterType::loadCallback(LuaScriptInterface* scriptInterface) { std::shared_ptr Monsters::getMonsterType(const std::string &name, bool silent /* = false*/) const { std::string lowerCaseName = asLowerCaseString(name); - if (auto it = monsters.find(lowerCaseName); + if (const auto &it = monsters.find(lowerCaseName); it != monsters.end() // We will only return the MonsterType if it match the exact name of the monster - && it->first.find(lowerCaseName) != it->first.npos) { + && it->first.find(lowerCaseName) != std::basic_string::npos) { return it->second; } if (!silent) { @@ -312,8 +312,8 @@ std::shared_ptr Monsters::getMonsterTypeByRaceId(uint16_t raceId, b return bossType; } - auto monster_race_map = g_game().getBestiaryList(); - auto it = monster_race_map.find(raceId); + const auto &monster_race_map = g_game().getBestiaryList(); + const auto &it = monster_race_map.find(raceId); if (it == monster_race_map.end()) { return nullptr; } @@ -322,8 +322,8 @@ std::shared_ptr Monsters::getMonsterTypeByRaceId(uint16_t raceId, b } bool Monsters::tryAddMonsterType(const std::string &name, const std::shared_ptr &mType) { - std::string lowerName = asLowerCaseString(name); - if (monsters.find(lowerName) != monsters.end()) { + const std::string lowerName = asLowerCaseString(name); + if (monsters.contains(lowerName)) { g_logger().debug("[{}] the monster with name '{}' already exist", __FUNCTION__, name); return false; } diff --git a/src/creatures/monsters/monsters.hpp b/src/creatures/monsters/monsters.hpp index fa6dedd41a8..a15717c2096 100644 --- a/src/creatures/monsters/monsters.hpp +++ b/src/creatures/monsters/monsters.hpp @@ -31,7 +31,7 @@ struct spellBlock_t { spellBlock_t(const spellBlock_t &other) = delete; spellBlock_t &operator=(const spellBlock_t &other) = delete; spellBlock_t(spellBlock_t &&other) noexcept : - spell(other.spell), + spell(std::move(other.spell)), chance(other.chance), speed(other.speed), range(other.range), @@ -164,7 +164,7 @@ class MonsterType { public: MonsterType() = default; explicit MonsterType(const std::string &initName) : - name(initName), typeName(initName), nameDescription(initName), variantName("") {}; + name(initName), typeName(initName), nameDescription(initName) { } // non-copyable MonsterType(const MonsterType &) = delete; @@ -203,7 +203,7 @@ class MonsterType { return !info.bosstiaryClass.empty(); } - void loadLoot(const std::shared_ptr &monsterType, LootBlock lootblock); + void loadLoot(const std::shared_ptr &monsterType, LootBlock lootblock) const; bool canSpawn(const Position &pos) const; }; @@ -274,13 +274,13 @@ class Monsters { std::shared_ptr getMonsterType(const std::string &name, bool silent = false) const; std::shared_ptr getMonsterTypeByRaceId(uint16_t raceId, bool isBoss = false) const; bool tryAddMonsterType(const std::string &name, const std::shared_ptr &mType); - bool deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description = ""); + bool deserializeSpell(const std::shared_ptr &spell, spellBlock_t &sb, const std::string &description = "") const; std::unique_ptr scriptInterface; std::map> monsters; private: - std::shared_ptr getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval); + std::shared_ptr getDamageCondition(ConditionType_t conditionType, int32_t maxDamage, int32_t minDamage, int32_t startDamage, uint32_t tickInterval) const; }; constexpr auto g_monsters = Monsters::getInstance; diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index 9d8a6f67f04..2730c7ec8ef 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -293,7 +293,7 @@ void SpawnMonster::cleanup() { std::vector removeList; for (const auto &[spawnMonsterId, monster] : spawnedMonsterMap) { if (monster == nullptr || monster->isRemoved()) { - removeList.push_back(spawnMonsterId); + removeList.emplace_back(spawnMonsterId); } } for (const auto &spawnMonsterId : removeList) { diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 958fa475c23..26592fb5237 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -37,7 +37,7 @@ Npc::Npc(const std::shared_ptr &npcType) : npcType(npcType) { defaultOutfit = npcType->info.outfit; currentOutfit = npcType->info.outfit; - float multiplier = g_configManager().getFloat(RATE_NPC_HEALTH, __FUNCTION__); + const float multiplier = g_configManager().getFloat(RATE_NPC_HEALTH, __FUNCTION__); health = npcType->info.health * multiplier; healthMax = npcType->info.healthMax * multiplier; baseSpeed = npcType->info.baseSpeed; @@ -75,7 +75,7 @@ void Npc::onCreatureAppear(const std::shared_ptr &creature, bool isLog } // onCreatureAppear(self, creature) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.creatureAppearEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(creature); @@ -90,7 +90,7 @@ void Npc::onRemoveCreature(const std::shared_ptr &creature, bool isLog Creature::onRemoveCreature(creature, isLogout); // onCreatureDisappear(self, creature) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.creatureDisappearEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(creature); @@ -114,7 +114,7 @@ void Npc::onCreatureMove(const std::shared_ptr &creature, const std::s Creature::onCreatureMove(creature, newTile, newPos, oldTile, oldPos, teleport); // onCreatureMove(self, creature, oldPosition, newPosition) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.creatureMoveEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(creature); @@ -168,7 +168,7 @@ void Npc::onCreatureSay(const std::shared_ptr &creature, SpeakClasses } // onCreatureSay(self, creature, type, message) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.creatureSayEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(creature); @@ -191,7 +191,7 @@ void Npc::onThinkSound(uint32_t interval) { soundTicks = 0; if (!npcType->info.soundVector.empty() && (npcType->info.soundChance >= static_cast(uniform_random(1, 100)))) { - auto index = uniform_random(0, npcType->info.soundVector.size() - 1); + const auto index = uniform_random(0, npcType->info.soundVector.size() - 1); g_game().sendSingleSoundEffect(static_self_cast()->getPosition(), npcType->info.soundVector[index], getNpc()); } } @@ -201,7 +201,7 @@ void Npc::onThink(uint32_t interval) { Creature::onThink(interval); // onThink(self, interval) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.thinkEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushNumber(interval); @@ -240,10 +240,10 @@ void Npc::onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemId return; } - uint32_t shoppingBagPrice = 20; - uint32_t shoppingBagSlots = 20; + constexpr uint32_t shoppingBagPrice = 20; + constexpr uint32_t shoppingBagSlots = 20; const ItemType &itemType = Item::items[itemId]; - if (std::shared_ptr tile = ignore ? player->getTile() : nullptr; tile) { + if (const std::shared_ptr &tile = ignore ? player->getTile() : nullptr; tile) { double slotsNedeed; if (itemType.stackable) { slotsNedeed = inBackpacks ? std::ceil(std::ceil(static_cast(amount) / itemType.stackSize) / shoppingBagSlots) : std::ceil(static_cast(amount) / itemType.stackSize); @@ -265,7 +265,7 @@ void Npc::onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemId } } - uint32_t totalCost = buyPrice * amount; + const uint32_t totalCost = buyPrice * amount; uint32_t bagsCost = 0; if (inBackpacks && itemType.stackable) { bagsCost = shoppingBagPrice * static_cast(std::ceil(std::ceil(static_cast(amount) / itemType.stackSize) / shoppingBagSlots)); @@ -285,7 +285,7 @@ void Npc::onPlayerBuyItem(const std::shared_ptr &player, uint16_t itemId } // npc:onBuyItem(player, itemId, subType, amount, ignore, inBackpacks, totalCost) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.playerBuyEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(player); @@ -391,7 +391,7 @@ void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemI continue; } - auto removeCount = std::min(toRemove, item->getItemCount()); + const auto removeCount = std::min(toRemove, item->getItemCount()); if (g_game().internalRemoveItem(item, removeCount) != RETURNVALUE_NOERROR) { g_logger().error("[Npc::onPlayerSellItem] - Player {} have a problem for sell item {} on shop for npc {}", player->getName(), item->getID(), getName()); @@ -404,8 +404,8 @@ void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemI } } - auto totalRemoved = amount - toRemove; - auto totalCost = static_cast(sellPrice * totalRemoved); + const auto totalRemoved = amount - toRemove; + const auto totalCost = sellPrice * totalRemoved; g_logger().debug("[Npc::onPlayerSellItem] - Removing items from player {} amount {} of items with id {} on shop for npc {}", player->getName(), toRemove, itemId, getName()); if (totalRemoved > 0 && totalCost > 0) { if (getCurrency() == ITEM_GOLD_COIN) { @@ -425,7 +425,7 @@ void Npc::onPlayerSellItem(const std::shared_ptr &player, uint16_t itemI } // npc:onSellItem(player, itemId, subType, amount, ignore, itemName, totalCost) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.playerSellEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(player); @@ -448,7 +448,7 @@ void Npc::onPlayerCheckItem(const std::shared_ptr &player, uint16_t item } // onPlayerCheckItem(self, player, itemId, subType) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.playerLookEvent)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(player); @@ -468,7 +468,7 @@ void Npc::onPlayerCloseChannel(const std::shared_ptr &creature) { } // onPlayerCloseChannel(npc, player) - CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); + auto callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.playerCloseChannel)) { callback.pushSpecificCreature(static_self_cast()); callback.pushCreature(player); @@ -491,13 +491,13 @@ void Npc::onThinkYell(uint32_t interval) { yellTicks = 0; if (!npcType->info.voiceVector.empty() && (npcType->info.yellChance >= static_cast(uniform_random(1, 100)))) { - uint32_t index = uniform_random(0, npcType->info.voiceVector.size() - 1); - const voiceBlock_t &vb = npcType->info.voiceVector[index]; + const uint32_t index = uniform_random(0, npcType->info.voiceVector.size() - 1); + const auto &[text, yellText] = npcType->info.voiceVector[index]; - if (vb.yellText) { - g_game().internalCreatureSay(static_self_cast(), TALKTYPE_YELL, vb.text, false); + if (yellText) { + g_game().internalCreatureSay(static_self_cast(), TALKTYPE_YELL, text, false); } else { - g_game().internalCreatureSay(static_self_cast(), TALKTYPE_SAY, vb.text, false); + g_game().internalCreatureSay(static_self_cast(), TALKTYPE_SAY, text, false); } } } @@ -539,7 +539,7 @@ void Npc::onPlacedCreature() { } void Npc::loadPlayerSpectators() { - auto spec = Spectators().find(position, true); + const auto &spec = Spectators().find(position, true); for (const auto &creature : spec) { if (!creature->getPlayer()->hasFlag(PlayerFlags_t::IgnoredByNpcs)) { playerSpectators.emplace(creature->getPlayer()); @@ -598,12 +598,12 @@ bool Npc::canWalkTo(const Position &fromPos, Direction dir) { return false; } - Position toPos = getNextPosition(dir, fromPos); + const Position toPos = getNextPosition(dir, fromPos); if (!SpawnsNpc::isInZone(masterPos, npcType->info.walkRadius, toPos)) { return false; } - std::shared_ptr toTile = g_game().map.getTile(toPos); + const auto &toTile = g_game().map.getTile(toPos); if (!toTile || toTile->queryAdd(0, getNpc(), 1, 0) != RETURNVALUE_NOERROR) { return false; } @@ -633,7 +633,7 @@ bool Npc::getRandomStep(Direction &moveDirection) { std::ranges::shuffle(directionvector, getRandomGenerator()); for (const Position &creaturePos = getPosition(); - Direction direction : directionvector) { + const Direction &direction : directionvector) { if (canWalkTo(creaturePos, direction)) { moveDirection = direction; return true; @@ -643,7 +643,7 @@ bool Npc::getRandomStep(Direction &moveDirection) { } bool Npc::isShopPlayer(uint32_t playerGUID) const { - return shopPlayers.find(playerGUID) != shopPlayers.end(); + return shopPlayers.contains(playerGUID); } void Npc::addShopPlayer(uint32_t playerGUID, const std::vector &shopItems) { @@ -655,7 +655,7 @@ void Npc::removeShopPlayer(uint32_t playerGUID) { } void Npc::closeAllShopWindows() { - for (const auto &[playerGUID, shopBlock] : shopPlayers) { + for (const auto &playerGUID : shopPlayers | std::views::keys) { const auto &player = g_game().getPlayerByGUID(playerGUID); if (player) { player->closeShopWindow(); diff --git a/src/creatures/npcs/npc.hpp b/src/creatures/npcs/npc.hpp index b6918eec0cd..1a1c73eeda8 100644 --- a/src/creatures/npcs/npc.hpp +++ b/src/creatures/npcs/npc.hpp @@ -66,7 +66,7 @@ class Npc final : public Creature { return strDescription + '.'; } - void setName(std::string newName) { + void setName(std::string newName) const { npcType->name = std::move(newName); } @@ -84,20 +84,20 @@ class Npc final : public Creature { uint8_t getSpeechBubble() const override { return npcType->info.speechBubble; } - void setSpeechBubble(const uint8_t bubble) { + void setSpeechBubble(const uint8_t bubble) const { npcType->info.speechBubble = bubble; } uint16_t getCurrency() const { return npcType->info.currencyId; } - void setCurrency(uint16_t currency) { + void setCurrency(uint16_t currency) const { npcType->info.currencyId = currency; } const std::vector &getShopItemVector(uint32_t playerGUID) const { if (playerGUID != 0) { - auto it = shopPlayers.find(playerGUID); + const auto &it = shopPlayers.find(playerGUID); if (it != shopPlayers.end() && !it->second.empty()) { return it->second; } @@ -129,15 +129,15 @@ class Npc final : public Creature { void removePlayerInteraction(const std::shared_ptr &player); void resetPlayerInteractions(); - bool isInteractingWithPlayer(uint32_t playerId) { - if (playerInteractions.find(playerId) == playerInteractions.end()) { + bool isInteractingWithPlayer(uint32_t playerId) const { + if (!playerInteractions.contains(playerId)) { return false; } return true; } bool isPlayerInteractingOnTopic(uint32_t playerId, uint16_t topicId) { - auto it = playerInteractions.find(playerId); + const auto &it = playerInteractions.find(playerId); if (it == playerInteractions.end()) { return false; } diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index 202c8d6a656..e46e183d893 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -19,7 +19,7 @@ bool NpcType::canSpawn(const Position &pos) const { bool canSpawn = true; - bool isDay = g_game().gameIsDay(); + const bool isDay = g_game().gameIsDay(); if ((isDay && info.respawnType.period == RESPAWNPERIOD_NIGHT) || (!isDay && info.respawnType.period == RESPAWNPERIOD_DAY)) { // It will ignore day and night if underground @@ -30,7 +30,7 @@ bool NpcType::canSpawn(const Position &pos) const { } bool NpcType::loadCallback(LuaScriptInterface* scriptInterface) { - int32_t id = scriptInterface->getEvent(); + const int32_t id = scriptInterface->getEvent(); if (id == -1) { g_logger().warn("[NpcType::loadCallback] - Event not found"); return false; @@ -91,25 +91,25 @@ void NpcType::loadShop(const std::shared_ptr &npcType, ShopBlock shopBl } if (shopBlock.childShop.empty()) { - bool isContainer = iType.isContainer(); + const bool &isContainer = iType.isContainer(); if (isContainer) { for (const ShopBlock &child : shopBlock.childShop) { - shopBlock.childShop.push_back(child); + shopBlock.childShop.emplace_back(child); } } } - npcType->info.shopItemVector.push_back(shopBlock); + npcType->info.shopItemVector.emplace_back(shopBlock); info.speechBubble = SPEECHBUBBLE_TRADE; } bool Npcs::load(bool loadLibs /* = true*/, bool loadNpcs /* = true*/, bool reloading /* = false*/) const { if (loadLibs) { - auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); + const auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); return g_luaEnvironment().loadFile(coreFolder + "/npclib/load.lua", "load.lua") == 0; } if (loadNpcs) { - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); + const auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); return g_scripts().loadScripts(datapackFolder + "/npc", false, reloading); } return false; @@ -132,8 +132,8 @@ bool Npcs::reload() { } std::shared_ptr Npcs::getNpcType(const std::string &name, bool create /* = false*/) { - std::string key = asLowerCaseString(name); - auto it = npcs.find(key); + const std::string key = asLowerCaseString(name); + const auto &it = npcs.find(key); if (it != npcs.end()) { return it->second; diff --git a/src/creatures/npcs/npcs.hpp b/src/creatures/npcs/npcs.hpp index d97ec6435e2..c12f6125bfe 100644 --- a/src/creatures/npcs/npcs.hpp +++ b/src/creatures/npcs/npcs.hpp @@ -23,7 +23,7 @@ class Shop { ShopBlock shopBlock; }; -class NpcType : public SharedObject { +class NpcType final : public SharedObject { struct NpcInfo { LuaScriptInterface* scriptInterface {}; diff --git a/src/creatures/npcs/spawns/spawn_npc.cpp b/src/creatures/npcs/spawns/spawn_npc.cpp index b2fc33e2cae..a3523645354 100644 --- a/src/creatures/npcs/spawns/spawn_npc.cpp +++ b/src/creatures/npcs/spawns/spawn_npc.cpp @@ -28,7 +28,7 @@ bool SpawnsNpc::loadFromXml(const std::string &fileNpcName) { } pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(fileNpcName.c_str()); + const pugi::xml_parse_result result = doc.load_file(fileNpcName.c_str()); if (!result) { printXMLError(__FUNCTION__, fileNpcName, result); return false; @@ -75,14 +75,14 @@ bool SpawnsNpc::loadFromXml(const std::string &fileNpcName) { dir = DIRECTION_NORTH; } - auto xOffset = pugi::cast(childNode.attribute("x").value()); - auto yOffset = pugi::cast(childNode.attribute("y").value()); + const auto xOffset = pugi::cast(childNode.attribute("x").value()); + const auto yOffset = pugi::cast(childNode.attribute("y").value()); Position pos( static_cast(centerPos.x + xOffset), static_cast(centerPos.y + yOffset), centerPos.z ); - int64_t interval = pugi::cast(childNode.attribute("spawntime").value()) * 1000; + const int64_t interval = pugi::cast(childNode.attribute("spawntime").value()) * 1000; if (interval >= MINSPAWN_INTERVAL && interval <= MAXSPAWN_INTERVAL) { spawnNpc->addNpc(nameAttribute.as_string(), pos, dir, static_cast(interval)); } else { @@ -138,8 +138,8 @@ void SpawnNpc::startSpawnNpcCheck() { } SpawnNpc::~SpawnNpc() { - for (const auto &it : spawnedNpcMap) { - auto npc = it.second; + for (const auto &[fst, snd] : spawnedNpcMap) { + const auto &npc = snd; npc->setSpawnNpc(nullptr); } } @@ -151,7 +151,7 @@ bool SpawnNpc::findPlayer(const Position &pos) { }); } -bool SpawnNpc::isInSpawnNpcZone(const Position &pos) { +bool SpawnNpc::isInSpawnNpcZone(const Position &pos) const { return SpawnsNpc::isInZone(centerPos, radius, pos); } @@ -181,10 +181,10 @@ bool SpawnNpc::spawnNpc(uint32_t spawnId, const std::shared_ptr &npcTyp } void SpawnNpc::startup() { - for (const auto &it : spawnNpcMap) { - uint32_t spawnId = it.first; - const spawnBlockNpc_t &sb = it.second; - spawnNpc(spawnId, sb.npcType, sb.pos, sb.direction, true); + for (const auto &[fst, snd] : spawnNpcMap) { + const uint32_t spawnId = fst; + const auto &[pos, npcType, lastSpawnNpc, interval, direction] = snd; + spawnNpc(spawnId, npcType, pos, direction, true); } } @@ -193,13 +193,13 @@ void SpawnNpc::checkSpawnNpc() { cleanup(); - for (auto &it : spawnNpcMap) { - uint32_t spawnId = it.first; - if (spawnedNpcMap.find(spawnId) != spawnedNpcMap.end()) { + for (auto &[fst, snd] : spawnNpcMap) { + uint32_t spawnId = fst; + if (spawnedNpcMap.contains(spawnId)) { continue; } - spawnBlockNpc_t &sb = it.second; + spawnBlockNpc_t &sb = snd; if (!sb.npcType->canSpawn(sb.pos)) { sb.lastSpawnNpc = OTSYS_TIME(); continue; @@ -237,7 +237,7 @@ void SpawnNpc::cleanup() { auto it = spawnedNpcMap.begin(); while (it != spawnedNpcMap.end()) { uint32_t spawnId = it->first; - auto npc = it->second; + const auto &npc = it->second; if (npc->isRemoved()) { spawnNpcMap[spawnId].lastSpawnNpc = OTSYS_TIME(); it = spawnedNpcMap.erase(it); @@ -263,7 +263,7 @@ bool SpawnNpc::addNpc(const std::string &name, const Position &pos, Direction di sb.interval = scheduleInterval; sb.lastSpawnNpc = 0; - uint32_t spawnId = spawnNpcMap.size() + 1; + const uint32_t spawnId = spawnNpcMap.size() + 1; spawnNpcMap[spawnId] = sb; return true; } diff --git a/src/creatures/npcs/spawns/spawn_npc.hpp b/src/creatures/npcs/spawns/spawn_npc.hpp index 8b2b7c7e591..96c9597559f 100644 --- a/src/creatures/npcs/spawns/spawn_npc.hpp +++ b/src/creatures/npcs/spawns/spawn_npc.hpp @@ -23,7 +23,7 @@ struct spawnBlockNpc_t { Direction direction; }; -class SpawnNpc : public SharedObject { +class SpawnNpc final : public SharedObject { public: SpawnNpc(Position initPos, int32_t initRadius) : centerPos(initPos), radius(initRadius) { } @@ -44,7 +44,7 @@ class SpawnNpc : public SharedObject { void startSpawnNpcCheck(); void stopEvent(); - bool isInSpawnNpcZone(const Position &pos); + bool isInSpawnNpcZone(const Position &pos) const; void cleanup(); private: diff --git a/src/creatures/players/achievement/player_achievement.cpp b/src/creatures/players/achievement/player_achievement.cpp index cad3c9b2820..bdb6638a29d 100644 --- a/src/creatures/players/achievement/player_achievement.cpp +++ b/src/creatures/players/achievement/player_achievement.cpp @@ -45,12 +45,12 @@ bool PlayerAchievement::remove(uint16_t id) { return false; } - auto achievement = g_game().getAchievementById(id); + const auto achievement = g_game().getAchievementById(id); if (achievement.id == 0) { return false; } - if (auto it = std::find_if(m_achievementsUnlocked.begin(), m_achievementsUnlocked.end(), [id](auto achievement_it) { + if (const auto &it = std::ranges::find_if(m_achievementsUnlocked, [id](auto achievement_it) { return achievement_it.first == id; }); it != m_achievementsUnlocked.end()) { @@ -69,7 +69,7 @@ bool PlayerAchievement::isUnlocked(uint16_t id) const { return false; } - if (auto it = std::find_if(m_achievementsUnlocked.begin(), m_achievementsUnlocked.end(), [id](auto achievement_it) { + if (const auto &it = std::ranges::find_if(m_achievementsUnlocked, [id](auto achievement_it) { return achievement_it.first == id; }); it != m_achievementsUnlocked.end()) { @@ -80,17 +80,17 @@ bool PlayerAchievement::isUnlocked(uint16_t id) const { } uint16_t PlayerAchievement::getPoints() const { - auto kvScoped = m_player.kv()->scoped("achievements")->get("points"); + const auto kvScoped = m_player.kv()->scoped("achievements")->get("points"); return kvScoped ? static_cast(kvScoped->getNumber()) : 0; } -void PlayerAchievement::addPoints(uint16_t toAddPoints) { - auto oldPoints = getPoints(); +void PlayerAchievement::addPoints(uint16_t toAddPoints) const { + const auto oldPoints = getPoints(); m_player.kv()->scoped("achievements")->set("points", oldPoints + toAddPoints); } -void PlayerAchievement::removePoints(uint16_t points) { - auto oldPoints = getPoints(); +void PlayerAchievement::removePoints(uint16_t points) const { + const auto oldPoints = getPoints(); m_player.kv()->scoped("achievements")->set("points", oldPoints - std::min(oldPoints, points)); } @@ -114,7 +114,7 @@ void PlayerAchievement::loadUnlockedAchievements() { } } -void PlayerAchievement::sendUnlockedSecretAchievements() { +void PlayerAchievement::sendUnlockedSecretAchievements() const { std::vector> achievementsUnlocked; uint16_t unlockedSecret = 0; for (const auto &[achievId, achievCreatedTime] : getUnlockedAchievements()) { diff --git a/src/creatures/players/achievement/player_achievement.hpp b/src/creatures/players/achievement/player_achievement.hpp index e0c027e5808..946be626e0e 100644 --- a/src/creatures/players/achievement/player_achievement.hpp +++ b/src/creatures/players/achievement/player_achievement.hpp @@ -15,8 +15,8 @@ class KV; struct Achievement { Achievement() = default; - std::string name; - std::string description; + std::string name {}; + std::string description {}; bool secret = false; @@ -33,11 +33,11 @@ class PlayerAchievement { bool remove(uint16_t id); [[nodiscard]] bool isUnlocked(uint16_t id) const; [[nodiscard]] uint16_t getPoints() const; - void addPoints(uint16_t toAddPoints); - void removePoints(uint16_t toRemovePoints); + void addPoints(uint16_t toAddPoints) const; + void removePoints(uint16_t toRemovePoints) const; [[nodiscard]] std::vector> getUnlockedAchievements() const; void loadUnlockedAchievements(); - void sendUnlockedSecretAchievements(); + void sendUnlockedSecretAchievements() const; const std::shared_ptr &getUnlockedKV(); private: diff --git a/src/creatures/players/cyclopedia/player_badge.cpp b/src/creatures/players/cyclopedia/player_badge.cpp index ba557317921..e5b4cbdac4a 100644 --- a/src/creatures/players/cyclopedia/player_badge.cpp +++ b/src/creatures/players/cyclopedia/player_badge.cpp @@ -23,7 +23,7 @@ bool PlayerBadge::hasBadge(uint8_t id) const { return false; } - if (auto it = std::find_if(m_badgesUnlocked.begin(), m_badgesUnlocked.end(), [id](auto badge_it) { + if (const auto &it = std::ranges::find_if(m_badgesUnlocked, [id](auto badge_it) { return badge_it.first.m_id == id; }); it != m_badgesUnlocked.end()) { @@ -107,30 +107,30 @@ const std::shared_ptr &PlayerBadge::getUnlockedKV() { } // Badge Calculate Functions -bool PlayerBadge::accountAge(uint8_t amount) { +bool PlayerBadge::accountAge(uint8_t amount) const { return std::floor(m_player.getLoyaltyPoints() / 365) >= amount; } -bool PlayerBadge::loyalty(uint8_t amount) { +bool PlayerBadge::loyalty(uint8_t amount) const { return m_player.getLoyaltyPoints() >= amount; } -bool PlayerBadge::accountAllLevel(uint8_t amount) { +bool PlayerBadge::accountAllLevel(uint8_t amount) const { const auto &players = g_game().getPlayersByAccount(m_player.getAccount(), true); - uint16_t total = std::accumulate(players.begin(), players.end(), 0, [](uint16_t sum, const std::shared_ptr &player) { + const uint16_t total = std::accumulate(players.begin(), players.end(), 0, [](uint16_t sum, const std::shared_ptr &player) { return sum + player->getLevel(); }); return total >= amount; } -bool PlayerBadge::accountAllVocations(uint8_t amount) { +bool PlayerBadge::accountAllVocations(uint8_t amount) const { auto knight = false; auto paladin = false; auto druid = false; auto sorcerer = false; for (const auto &player : g_game().getPlayersByAccount(m_player.getAccount(), true)) { if (player->getLevel() >= amount) { - auto vocationEnum = player->getPlayerVocationEnum(); + const auto &vocationEnum = player->getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { knight = true; } else if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { @@ -145,12 +145,12 @@ bool PlayerBadge::accountAllVocations(uint8_t amount) { return knight && paladin && druid && sorcerer; } -bool PlayerBadge::tournamentParticipation(uint8_t skill) { +bool PlayerBadge::tournamentParticipation(uint8_t skill) const { // todo check if is used return false; } -bool PlayerBadge::tournamentPoints(uint8_t race) { +bool PlayerBadge::tournamentPoints(uint8_t race) const { // todo check if is used return false; } diff --git a/src/creatures/players/cyclopedia/player_badge.hpp b/src/creatures/players/cyclopedia/player_badge.hpp index b0973e10b67..c4326c53c75 100644 --- a/src/creatures/players/cyclopedia/player_badge.hpp +++ b/src/creatures/players/cyclopedia/player_badge.hpp @@ -17,7 +17,7 @@ enum class CyclopediaBadge_t : uint8_t; struct Badge { uint8_t m_id = 0; CyclopediaBadge_t m_type {}; - std::string m_name; + std::string m_name {}; uint16_t m_amount = 0; Badge() = default; @@ -30,14 +30,12 @@ struct Badge { } }; -namespace std { - template <> - struct hash { - std::size_t operator()(const Badge &b) const { - return hash()(b.m_id); - } - }; -} +template <> +struct std::hash { + std::size_t operator()(const Badge &b) const noexcept { + return hash()(b.m_id); + } +}; class PlayerBadge { public: @@ -50,12 +48,12 @@ class PlayerBadge { const std::shared_ptr &getUnlockedKV(); // Badge Calculate Functions - bool accountAge(uint8_t amount); - bool loyalty(uint8_t amount); - bool accountAllLevel(uint8_t amount); - bool accountAllVocations(uint8_t amount); - [[nodiscard]] bool tournamentParticipation(uint8_t skill); - [[nodiscard]] bool tournamentPoints(uint8_t race); + bool accountAge(uint8_t amount) const; + bool loyalty(uint8_t amount) const; + bool accountAllLevel(uint8_t amount) const; + bool accountAllVocations(uint8_t amount) const; + [[nodiscard]] bool tournamentParticipation(uint8_t skill) const; + [[nodiscard]] bool tournamentPoints(uint8_t race) const; private: // {badge ID, time when it was unlocked} diff --git a/src/creatures/players/cyclopedia/player_cyclopedia.cpp b/src/creatures/players/cyclopedia/player_cyclopedia.cpp index 6f94b5d46b1..abd29ba84fa 100644 --- a/src/creatures/players/cyclopedia/player_cyclopedia.cpp +++ b/src/creatures/players/cyclopedia/player_cyclopedia.cpp @@ -21,27 +21,27 @@ PlayerCyclopedia::PlayerCyclopedia(Player &player) : m_player(player) { } -Summary PlayerCyclopedia::getSummary() { +Summary PlayerCyclopedia::getSummary() const { return { getAmount(Summary_t::PREY_CARDS), getAmount(Summary_t::INSTANT_REWARDS), getAmount(Summary_t::HIRELINGS) }; } -void PlayerCyclopedia::loadSummaryData() { - DBResult_ptr result = g_database().storeQuery(fmt::format("SELECT COUNT(*) as `count` FROM `player_hirelings` WHERE `player_id` = {}", m_player.getGUID())); - auto kvScoped = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(static_cast(Summary_t::HIRELINGS))); +void PlayerCyclopedia::loadSummaryData() const { + const DBResult_ptr result = g_database().storeQuery(fmt::format("SELECT COUNT(*) as `count` FROM `player_hirelings` WHERE `player_id` = {}", m_player.getGUID())); + const auto kvScoped = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(static_cast(Summary_t::HIRELINGS))); if (result && !kvScoped->get("amount").has_value()) { kvScoped->set("amount", result->getNumber("count")); } } -void PlayerCyclopedia::loadDeathHistory(uint16_t page, uint16_t entriesPerPage) { +void PlayerCyclopedia::loadDeathHistory(uint16_t page, uint16_t entriesPerPage) const { Benchmark bm_check; uint32_t offset = static_cast(page - 1) * entriesPerPage; - auto query = fmt::format("SELECT `time`, `level`, `killed_by`, `mostdamage_by`, (select count(*) FROM `player_deaths` WHERE `player_id` = {}) as `entries` FROM `player_deaths` WHERE `player_id` = {} AND `time` >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) ORDER BY `time` DESC LIMIT {}, {}", m_player.getGUID(), m_player.getGUID(), offset, entriesPerPage); + const auto query = fmt::format("SELECT `time`, `level`, `killed_by`, `mostdamage_by`, (select count(*) FROM `player_deaths` WHERE `player_id` = {}) as `entries` FROM `player_deaths` WHERE `player_id` = {} AND `time` >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 DAY)) ORDER BY `time` DESC LIMIT {}, {}", m_player.getGUID(), m_player.getGUID(), offset, entriesPerPage); uint32_t playerID = m_player.getID(); - std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { + const std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { const auto &player = g_game().getPlayerByID(playerID); if (!player) { return; @@ -83,15 +83,15 @@ void PlayerCyclopedia::loadDeathHistory(uint16_t page, uint16_t entriesPerPage) g_logger().debug("Loading death history from the player {} took {} milliseconds.", m_player.getName(), bm_check.duration()); } -void PlayerCyclopedia::loadRecentKills(uint16_t page, uint16_t entriesPerPage) { +void PlayerCyclopedia::loadRecentKills(uint16_t page, uint16_t entriesPerPage) const { Benchmark bm_check; const std::string &escapedName = g_database().escapeString(m_player.getName()); uint32_t offset = static_cast(page - 1) * entriesPerPage; - auto query = fmt::format("SELECT `d`.`time`, `d`.`killed_by`, `d`.`mostdamage_by`, `d`.`unjustified`, `d`.`mostdamage_unjustified`, `p`.`name`, (select count(*) FROM `player_deaths` WHERE ((`killed_by` = {} AND `is_player` = 1) OR (`mostdamage_by` = {} AND `mostdamage_is_player` = 1))) as `entries` FROM `player_deaths` AS `d` INNER JOIN `players` AS `p` ON `d`.`player_id` = `p`.`id` WHERE ((`d`.`killed_by` = {} AND `d`.`is_player` = 1) OR (`d`.`mostdamage_by` = {} AND `d`.`mostdamage_is_player` = 1)) AND `time` >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 70 DAY)) ORDER BY `time` DESC LIMIT {}, {}", escapedName, escapedName, escapedName, escapedName, offset, entriesPerPage); + const auto query = fmt::format("SELECT `d`.`time`, `d`.`killed_by`, `d`.`mostdamage_by`, `d`.`unjustified`, `d`.`mostdamage_unjustified`, `p`.`name`, (select count(*) FROM `player_deaths` WHERE ((`killed_by` = {} AND `is_player` = 1) OR (`mostdamage_by` = {} AND `mostdamage_is_player` = 1))) as `entries` FROM `player_deaths` AS `d` INNER JOIN `players` AS `p` ON `d`.`player_id` = `p`.`id` WHERE ((`d`.`killed_by` = {} AND `d`.`is_player` = 1) OR (`d`.`mostdamage_by` = {} AND `d`.`mostdamage_is_player` = 1)) AND `time` >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 70 DAY)) ORDER BY `time` DESC LIMIT {}, {}", escapedName, escapedName, escapedName, escapedName, offset, entriesPerPage); uint32_t playerID = m_player.getID(); - std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { + const std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { const auto &player = g_game().getPlayerByID(playerID); if (!player) { return; @@ -135,7 +135,7 @@ void PlayerCyclopedia::loadRecentKills(uint16_t page, uint16_t entriesPerPage) { g_logger().debug("Loading recent kills from the player {} took {} milliseconds.", m_player.getName(), bm_check.duration()); } -void PlayerCyclopedia::updateStoreSummary(uint8_t type, uint16_t amount, const std::string &id) { +void PlayerCyclopedia::updateStoreSummary(uint8_t type, uint16_t amount, const std::string &id) const { switch (type) { case Summary_t::HOUSE_ITEMS: case Summary_t::BLESSINGS: @@ -152,35 +152,35 @@ void PlayerCyclopedia::updateStoreSummary(uint8_t type, uint16_t amount, const s } } -uint16_t PlayerCyclopedia::getAmount(uint8_t type) { - auto kvScope = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type))->get("amount"); +uint16_t PlayerCyclopedia::getAmount(uint8_t type) const { + const auto kvScope = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type))->get("amount"); return static_cast(kvScope ? kvScope->getNumber() : 0); } -void PlayerCyclopedia::updateAmount(uint8_t type, uint16_t amount) { - auto oldAmount = getAmount(type); +void PlayerCyclopedia::updateAmount(uint8_t type, uint16_t amount) const { + const auto oldAmount = getAmount(type); m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type))->set("amount", oldAmount + amount); } std::map PlayerCyclopedia::getResult(uint8_t type) const { - auto kvScope = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type)); + const auto kvScope = m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type)); std::map result; // ID, amount for (const auto &scope : kvScope->keys()) { - size_t pos = scope.find('.'); + const size_t &pos = scope.find('.'); if (pos == std::string::npos) { g_logger().error("[{}] Invalid key format: {}", __FUNCTION__, scope); continue; } std::string id = scope.substr(0, pos); - auto amount = kvScope->scoped(id)->get("amount"); + const auto amount = kvScope->scoped(id)->get("amount"); result.emplace(std::stoll(id), static_cast(amount ? amount->getNumber() : 0)); } return result; } -void PlayerCyclopedia::insertValue(uint8_t type, uint16_t amount, const std::string &id) { +void PlayerCyclopedia::insertValue(uint8_t type, uint16_t amount, const std::string &id) const { auto result = getResult(type); - auto it = result.find(std::stoll(id)); + const auto it = result.find(std::stoll(id)); auto oldAmount = (it != result.end() ? it->second : 0); auto newAmount = oldAmount + amount; m_player.kv()->scoped("summary")->scoped(g_game().getSummaryKeyByType(type))->scoped(id)->set("amount", newAmount); diff --git a/src/creatures/players/cyclopedia/player_cyclopedia.hpp b/src/creatures/players/cyclopedia/player_cyclopedia.hpp index 01c7fa7967c..0f399af03b2 100644 --- a/src/creatures/players/cyclopedia/player_cyclopedia.hpp +++ b/src/creatures/players/cyclopedia/player_cyclopedia.hpp @@ -25,18 +25,18 @@ class PlayerCyclopedia { public: explicit PlayerCyclopedia(Player &player); - Summary getSummary(); + Summary getSummary() const; - void loadSummaryData(); - void loadDeathHistory(uint16_t page, uint16_t entriesPerPage); - void loadRecentKills(uint16_t page, uint16_t entriesPerPage); + void loadSummaryData() const; + void loadDeathHistory(uint16_t page, uint16_t entriesPerPage) const; + void loadRecentKills(uint16_t page, uint16_t entriesPerPage) const; - void updateStoreSummary(uint8_t type, uint16_t amount = 1, const std::string &id = ""); - uint16_t getAmount(uint8_t type); - void updateAmount(uint8_t type, uint16_t amount = 1); + void updateStoreSummary(uint8_t type, uint16_t amount = 1, const std::string &id = "") const; + uint16_t getAmount(uint8_t type) const; + void updateAmount(uint8_t type, uint16_t amount = 1) const; [[nodiscard]] std::map getResult(uint8_t type) const; - void insertValue(uint8_t type, uint16_t amount = 1, const std::string &id = ""); + void insertValue(uint8_t type, uint16_t amount = 1, const std::string &id = "") const; private: Player &m_player; diff --git a/src/creatures/players/cyclopedia/player_title.cpp b/src/creatures/players/cyclopedia/player_title.cpp index 7c348cbf79d..716d69e4ddd 100644 --- a/src/creatures/players/cyclopedia/player_title.cpp +++ b/src/creatures/players/cyclopedia/player_title.cpp @@ -23,7 +23,7 @@ bool PlayerTitle::isTitleUnlocked(uint8_t id) const { return false; } - if (auto it = std::find_if(m_titlesUnlocked.begin(), m_titlesUnlocked.end(), [id](auto title_it) { + if (const auto &it = std::ranges::find_if(m_titlesUnlocked, [id](auto title_it) { return title_it.first.m_id == id; }); it != m_titlesUnlocked.end()) { @@ -65,7 +65,7 @@ void PlayerTitle::remove(const Title &title) { return; } - auto it = std::find_if(m_titlesUnlocked.begin(), m_titlesUnlocked.end(), [id](auto title_it) { + const auto &it = std::ranges::find_if(m_titlesUnlocked, [id](auto title_it) { return title_it.first.m_id == id; }); @@ -84,21 +84,21 @@ const std::vector> &PlayerTitle::getUnlockedTitles() } uint8_t PlayerTitle::getCurrentTitle() const { - auto title = m_player.kv()->scoped("titles")->get("current-title"); + const auto title = m_player.kv()->scoped("titles")->get("current-title"); return title ? static_cast(title->getNumber()) : 0; } -void PlayerTitle::setCurrentTitle(uint8_t id) { +void PlayerTitle::setCurrentTitle(uint8_t id) const { m_player.kv()->scoped("titles")->set("current-title", id != 0 && isTitleUnlocked(id) ? id : 0); } -std::string PlayerTitle::getCurrentTitleName() { - auto currentTitle = getCurrentTitle(); +std::string PlayerTitle::getCurrentTitleName() const { + const auto currentTitle = getCurrentTitle(); if (currentTitle == 0) { return ""; } - auto title = g_game().getTitleById(currentTitle); + const auto &title = g_game().getTitleById(currentTitle); if (title.m_id == 0) { return ""; } @@ -178,11 +178,11 @@ const std::shared_ptr &PlayerTitle::getUnlockedKV() { } // Title Calculate Functions -bool PlayerTitle::checkGold(uint32_t amount) { +bool PlayerTitle::checkGold(uint32_t amount) const { return m_player.getBankBalance() >= amount; } -bool PlayerTitle::checkMount(uint32_t amount) { +bool PlayerTitle::checkMount(uint32_t amount) const { uint8_t total = 0; for (const auto &mount : g_game().mounts.getMounts()) { if (m_player.hasMount(mount)) { @@ -192,15 +192,15 @@ bool PlayerTitle::checkMount(uint32_t amount) { return total >= amount; } -bool PlayerTitle::checkOutfit(uint32_t amount) { +bool PlayerTitle::checkOutfit(uint32_t amount) const { return m_player.outfits.size() >= amount; } -bool PlayerTitle::checkLevel(uint32_t amount) { +bool PlayerTitle::checkLevel(uint32_t amount) const { return m_player.getLevel() >= amount; } -bool PlayerTitle::checkHighscore(uint8_t skill) { +bool PlayerTitle::checkHighscore(uint8_t skill) const { Database &db = Database::getInstance(); std::string query; std::string fieldCheck = "id"; @@ -228,7 +228,7 @@ bool PlayerTitle::checkHighscore(uint8_t skill) { break; } - DBResult_ptr result = db.storeQuery(query); + const DBResult_ptr result = db.storeQuery(query); if (!result) { return false; } @@ -239,7 +239,7 @@ bool PlayerTitle::checkHighscore(uint8_t skill) { return resultValue == m_player.getGUID(); } -bool PlayerTitle::checkBestiary(const std::string &name, uint16_t race, bool isBoss /* = false*/, uint32_t amount) { +bool PlayerTitle::checkBestiary(const std::string &name, uint16_t race, bool isBoss /* = false*/, uint32_t amount) const { if (race == 0) { if (name == "Executioner") { // todo check if player has unlocked all bestiary @@ -255,23 +255,23 @@ bool PlayerTitle::checkBestiary(const std::string &name, uint16_t race, bool isB return m_player.isCreatureUnlockedOnTaskHunting(g_monsters().getMonsterTypeByRaceId(race, isBoss)); } -bool PlayerTitle::checkLoginStreak(uint32_t amount) { - auto streakKV = m_player.kv()->scoped("daily-reward")->get("streak"); +bool PlayerTitle::checkLoginStreak(uint32_t amount) const { + const auto streakKV = m_player.kv()->scoped("daily-reward")->get("streak"); return streakKV && streakKV.has_value() && static_cast(streakKV->getNumber()) >= amount; } -bool PlayerTitle::checkTask(uint32_t amount) { +bool PlayerTitle::checkTask(uint32_t amount) const { return m_player.getTaskHuntingPoints() >= amount; } -bool PlayerTitle::checkMap(uint32_t amount) { +bool PlayerTitle::checkMap(uint32_t amount) const { // todo cyclopledia return false; } -bool PlayerTitle::checkOther(const std::string &name) { +bool PlayerTitle::checkOther(const std::string &name) const { if (name == "Guild Leader") { - auto rank = m_player.getGuildRank(); + const auto &rank = m_player.getGuildRank(); return rank && rank->level == 3; } else if (name == "Proconsul of Iksupan") { // Win Ancient Aucar Outfits complete so fight with Atab and be teleported to the arena. diff --git a/src/creatures/players/cyclopedia/player_title.hpp b/src/creatures/players/cyclopedia/player_title.hpp index 5a18ce94c81..58ac098c882 100644 --- a/src/creatures/players/cyclopedia/player_title.hpp +++ b/src/creatures/players/cyclopedia/player_title.hpp @@ -56,14 +56,12 @@ struct Title { } }; -namespace std { - template <> - struct hash { - std::size_t operator()(const Title &t) const { - return hash<uint8_t>()(t.m_id); - } - }; -} +template <> +struct std::hash<Title> { + std::size_t operator()(const Title &t) const noexcept { + return hash<uint8_t>()(t.m_id); + } +}; class PlayerTitle { public: @@ -74,24 +72,24 @@ class PlayerTitle { void remove(const Title &title); const std::vector<std::pair<Title, uint32_t>> &getUnlockedTitles(); [[nodiscard]] uint8_t getCurrentTitle() const; - void setCurrentTitle(uint8_t id); - std::string getCurrentTitleName(); + void setCurrentTitle(uint8_t id) const; + std::string getCurrentTitleName() const; static const std::string &getNameBySex(PlayerSex_t sex, const std::string &male, const std::string &female); void checkAndUpdateNewTitles(); void loadUnlockedTitles(); const std::shared_ptr<KV> &getUnlockedKV(); // Title Calculate Functions - bool checkGold(uint32_t amount); - bool checkMount(uint32_t amount); - bool checkOutfit(uint32_t amount); - bool checkLevel(uint32_t amount); - bool checkHighscore(uint8_t skill); - bool checkBestiary(const std::string &name, uint16_t race, bool isBoss = false, uint32_t amount = 0); - bool checkLoginStreak(uint32_t amount); - bool checkTask(uint32_t amount); - bool checkMap(uint32_t amount); - bool checkOther(const std::string &name); + bool checkGold(uint32_t amount) const; + bool checkMount(uint32_t amount) const; + bool checkOutfit(uint32_t amount) const; + bool checkLevel(uint32_t amount) const; + bool checkHighscore(uint8_t skill) const; + bool checkBestiary(const std::string &name, uint16_t race, bool isBoss = false, uint32_t amount = 0) const; + bool checkLoginStreak(uint32_t amount) const; + bool checkTask(uint32_t amount) const; + bool checkMap(uint32_t amount) const; + bool checkOther(const std::string &name) const; private: // {title ID, time when it was unlocked} diff --git a/src/creatures/players/grouping/familiars.cpp b/src/creatures/players/grouping/familiars.cpp index 47780dcf07d..022d4a35f99 100644 --- a/src/creatures/players/grouping/familiars.cpp +++ b/src/creatures/players/grouping/familiars.cpp @@ -26,8 +26,8 @@ bool Familiars::reload() { bool Familiars::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/familiars.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/familiars.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { g_logger().error("Failed to load Familiars"); printXMLError(__FUNCTION__, folder, result); @@ -36,11 +36,11 @@ bool Familiars::loadFromXml() { for (const auto &familiarsNode : doc.child("familiars").children()) { pugi::xml_attribute attr; - if ((attr = familiarsNode.attribute("enabled")) && !attr.as_bool()) { + if ((attr = familiarsNode.attribute("enabled") && !attr.as_bool())) { continue; } - if (!(attr = familiarsNode.attribute("vocation"))) { + if (!((attr = familiarsNode.attribute("vocation")))) { g_logger().warn("[Familiars::loadFromXml] - Missing familiar vocation."); continue; } @@ -72,7 +72,7 @@ bool Familiars::loadFromXml() { } std::shared_ptr<Familiar> Familiars::getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const { - if (auto it = std::find_if(familiars[vocation].begin(), familiars[vocation].end(), [lookType](const auto &familiar_it) { + if (const auto &it = std::ranges::find_if(familiars[vocation], [lookType](const auto &familiar_it) { return familiar_it->lookType == lookType; }); it != familiars[vocation].end()) { diff --git a/src/creatures/players/grouping/groups.cpp b/src/creatures/players/grouping/groups.cpp index 13ee3e2e17d..b0d89794b59 100644 --- a/src/creatures/players/grouping/groups.cpp +++ b/src/creatures/players/grouping/groups.cpp @@ -48,7 +48,7 @@ bool Groups::reload() { } void parseGroupFlags(Group &group, const pugi::xml_node &groupNode) { - if (pugi::xml_node node = groupNode.child("flags")) { + if (const pugi::xml_node node = groupNode.child("flags")) { for (const auto &flagNode : node.children()) { pugi::xml_attribute attr = flagNode.first_attribute(); if (!attr || !attr.as_bool()) { @@ -67,8 +67,8 @@ void parseGroupFlags(Group &group, const pugi::xml_node &groupNode) { bool Groups::load() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/groups.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/groups.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -81,10 +81,10 @@ bool Groups::load() { group.access = groupNode.attribute("access").as_bool(); group.maxDepotItems = pugi::cast<uint32_t>(groupNode.attribute("maxdepotitems").value()); group.maxVipEntries = pugi::cast<uint32_t>(groupNode.attribute("maxvipentries").value()); - auto flagsInt = static_cast<uint8_t>(groupNode.attribute("flags").as_uint()); + const auto flagsInt = static_cast<uint8_t>(groupNode.attribute("flags").as_uint()); std::bitset<magic_enum::enum_integer(PlayerFlags_t::FlagLast)> flags(flagsInt); for (uint8_t i = 0; i < getFlagNumber(PlayerFlags_t::FlagLast); i++) { - PlayerFlags_t flag = getFlagFromNumber(i); + const PlayerFlags_t flag = getFlagFromNumber(i); group.flags[i] = flags[Groups::getFlagNumber(flag)]; } @@ -98,7 +98,7 @@ bool Groups::load() { } std::shared_ptr<Group> Groups::getGroup(uint16_t id) const { - if (auto it = std::find_if(groups_vector.begin(), groups_vector.end(), [id](auto group_it) { + if (const auto &it = std::ranges::find_if(groups_vector, [id](auto group_it) { return group_it->id == id; }); it != groups_vector.end()) { diff --git a/src/creatures/players/grouping/guild.cpp b/src/creatures/players/grouping/guild.cpp index c7fde5979a4..f9319b2a929 100644 --- a/src/creatures/players/grouping/guild.cpp +++ b/src/creatures/players/grouping/guild.cpp @@ -13,7 +13,7 @@ #include "game/game.hpp" void Guild::addMember(const std::shared_ptr<Player> &player) { - membersOnline.push_back(player); + membersOnline.emplace_back(player); for (const auto &member : getMembersOnline()) { g_game().updatePlayerHelpers(member); } @@ -32,7 +32,7 @@ void Guild::removeMember(const std::shared_ptr<Player> &player) { } } -GuildRank_ptr Guild::getRankById(uint32_t rankId) { +GuildRank_ptr Guild::getRankById(uint32_t rankId) const { for (const auto &rank : ranks) { if (rank->id == rankId) { return rank; diff --git a/src/creatures/players/grouping/guild.hpp b/src/creatures/players/grouping/guild.hpp index 82b0a7367ea..f4c3f605ac6 100644 --- a/src/creatures/players/grouping/guild.hpp +++ b/src/creatures/players/grouping/guild.hpp @@ -24,7 +24,7 @@ struct GuildRank { using GuildRank_ptr = std::shared_ptr<GuildRank>; -class Guild : public Bankable { +class Guild final : public Bankable { public: Guild(uint32_t initId, std::string initName) : name(std::move(initName)), id(initId) { } @@ -72,7 +72,7 @@ class Guild : public Bankable { return ranks; } - GuildRank_ptr getRankById(uint32_t id); + GuildRank_ptr getRankById(uint32_t id) const; GuildRank_ptr getRankByName(const std::string &name) const; GuildRank_ptr getRankByLevel(uint8_t level) const; void addRank(uint32_t id, const std::string &name, uint8_t level); diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index 242fff7d1ae..99d9d686e22 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -34,7 +34,7 @@ void Party::disband() { return; } - auto currentLeader = getLeader(); + const auto ¤tLeader = getLeader(); if (!currentLeader) { return; } @@ -53,7 +53,7 @@ void Party::disband() { } inviteList.clear(); - auto members = getMembers(); + const auto &members = getMembers(); for (const auto &member : members) { member->setParty(nullptr); member->sendClosePrivate(CHANNEL_PARTY); @@ -80,7 +80,7 @@ bool Party::leaveParty(const std::shared_ptr<Player> &player) { return false; } - auto leader = getLeader(); + const auto &leader = getLeader(); if (!leader) { return false; } @@ -122,7 +122,7 @@ bool Party::leaveParty(const std::shared_ptr<Player> &player) { } // since we already passed the leadership, we remove the player from the list - auto it = std::find(memberList.begin(), memberList.end(), player); + const auto &it = std::ranges::find(memberList, player); if (it != memberList.end()) { memberList.erase(it); } @@ -168,7 +168,7 @@ bool Party::passPartyLeadership(const std::shared_ptr<Player> &player) { } // Remove it before to broadcast the message correctly - auto it = std::find(memberList.begin(), memberList.end(), player); + const auto &it = std::ranges::find(memberList, player); if (it != memberList.end()) { memberList.erase(it); } @@ -216,7 +216,7 @@ bool Party::joinParty(const std::shared_ptr<Player> &player) { return false; } - auto it = std::find(inviteList.begin(), inviteList.end(), player); + const auto &it = std::ranges::find(inviteList, player); if (it == inviteList.end()) { return false; } @@ -242,7 +242,7 @@ bool Party::joinParty(const std::shared_ptr<Player> &player) { leader->sendPlayerPartyIcons(player); player->sendPlayerPartyIcons(leader); - memberList.push_back(player); + memberList.emplace_back(player); g_game().updatePlayerHelpers(player); @@ -265,7 +265,7 @@ bool Party::removeInvite(const std::shared_ptr<Player> &player, bool removeFromP return false; } - auto it = std::find(inviteList.begin(), inviteList.end(), player); + const auto &it = std::ranges::find(inviteList, player); if (it == inviteList.end()) { return false; } @@ -330,7 +330,7 @@ bool Party::invitePlayer(const std::shared_ptr<Player> &player) { leader->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, ss.str()); - inviteList.push_back(player); + inviteList.emplace_back(player); for (const auto &member : getMembers()) { g_game().updatePlayerHelpers(member); @@ -350,7 +350,7 @@ bool Party::invitePlayer(const std::shared_ptr<Player> &player) { } bool Party::isPlayerInvited(const std::shared_ptr<Player> &player) const { - return std::find(inviteList.begin(), inviteList.end(), player) != inviteList.end(); + return std::ranges::find(inviteList, player) != inviteList.end(); } void Party::updateAllPartyIcons() { @@ -391,7 +391,7 @@ void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string &ms void Party::updateSharedExperience() { if (sharedExpActive) { - bool result = getSharedExperienceStatus() == SHAREDEXP_OK; + const bool result = getSharedExperienceStatus() == SHAREDEXP_OK; if (result != sharedExpEnabled) { sharedExpEnabled = result; updateAllPartyIcons(); @@ -399,7 +399,7 @@ void Party::updateSharedExperience() { } } -const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) { +const char* Party::getSharedExpReturnMessage(SharedExpStatus_t value) const { switch (value) { case SHAREDEXP_OK: return "Shared Experience is now active."; @@ -429,7 +429,7 @@ bool Party::setSharedExperience(const std::shared_ptr<Player> &player, bool newS this->sharedExpActive = newSharedExpActive; if (newSharedExpActive) { - SharedExpStatus_t sharedExpStatus = getSharedExperienceStatus(); + const SharedExpStatus_t &sharedExpStatus = getSharedExperienceStatus(); this->sharedExpEnabled = sharedExpStatus == SHAREDEXP_OK; if (!silent) { leader->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, getSharedExpReturnMessage(sharedExpStatus)); @@ -473,7 +473,7 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(const std::shared_ptr<P return SHAREDEXP_EMPTYPARTY; } - uint32_t minLevel = getMinLevel(); + const uint32_t minLevel = getMinLevel(); if (player->getLevel() < minLevel) { return SHAREDEXP_LEVELDIFFTOOLARGE; } @@ -532,11 +532,11 @@ uint32_t Party::getMaxLevel() { } bool Party::isPlayerActive(const std::shared_ptr<Player> &player) { - auto it = ticksMap.find(player->getID()); + const auto &it = ticksMap.find(player->getID()); if (it == ticksMap.end()) { return false; } - uint64_t timeDiff = OTSYS_TIME() - it->second; + const uint64_t timeDiff = OTSYS_TIME() - it->second; return timeDiff <= 2 * 60 * 1000; } @@ -545,13 +545,13 @@ SharedExpStatus_t Party::getSharedExperienceStatus() { if (!leader) { return SHAREDEXP_EMPTYPARTY; } - SharedExpStatus_t leaderStatus = getMemberSharedExperienceStatus(leader); + const SharedExpStatus_t &leaderStatus = getMemberSharedExperienceStatus(leader); if (leaderStatus != SHAREDEXP_OK) { return leaderStatus; } for (const auto &member : getMembers()) { - SharedExpStatus_t memberStatus = getMemberSharedExperienceStatus(member); + const SharedExpStatus_t &memberStatus = getMemberSharedExperienceStatus(member); if (memberStatus != SHAREDEXP_OK) { return memberStatus; } @@ -567,7 +567,7 @@ void Party::updatePlayerTicks(const std::shared_ptr<Player> &player, uint32_t po } void Party::clearPlayerPoints(const std::shared_ptr<Player> &player) { - auto it = ticksMap.find(player->getID()); + const auto &it = ticksMap.find(player->getID()); if (it != ticksMap.end()) { ticksMap.erase(it); updateSharedExperience(); @@ -586,7 +586,7 @@ bool Party::canOpenCorpse(uint32_t ownerId) const { return false; } -void Party::showPlayerStatus(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &member, bool showStatus) { +void Party::showPlayerStatus(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &member, bool showStatus) const { player->sendPartyCreatureShowStatus(member, showStatus); member->sendPartyCreatureShowStatus(player, showStatus); if (showStatus) { @@ -618,16 +618,16 @@ void Party::updatePlayerStatus(const std::shared_ptr<Player> &player) { return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); + const int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (const auto &member : getMembers()) { - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { showPlayerStatus(player, member, true); } else { showPlayerStatus(player, member, false); } } - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); if (condition) { showPlayerStatus(player, leader, true); } else { @@ -641,11 +641,11 @@ void Party::updatePlayerStatus(const std::shared_ptr<Player> &player, const Posi return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); + const int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); if (maxDistance != 0) { for (const auto &member : getMembers()) { - bool condition1 = (Position::getDistanceX(oldPos, member->getPosition()) <= maxDistance && Position::getDistanceY(oldPos, member->getPosition()) <= maxDistance); - bool condition2 = (Position::getDistanceX(newPos, member->getPosition()) <= maxDistance && Position::getDistanceY(newPos, member->getPosition()) <= maxDistance); + const bool condition1 = Position::getDistanceX(oldPos, member->getPosition()) <= maxDistance && Position::getDistanceY(oldPos, member->getPosition()) <= maxDistance; + const bool condition2 = Position::getDistanceX(newPos, member->getPosition()) <= maxDistance && Position::getDistanceY(newPos, member->getPosition()) <= maxDistance; if (condition1 && !condition2) { showPlayerStatus(player, member, false); } else if (!condition1 && condition2) { @@ -653,8 +653,8 @@ void Party::updatePlayerStatus(const std::shared_ptr<Player> &player, const Posi } } - bool condition1 = (Position::getDistanceX(oldPos, leader->getPosition()) <= maxDistance && Position::getDistanceY(oldPos, leader->getPosition()) <= maxDistance); - bool condition2 = (Position::getDistanceX(newPos, leader->getPosition()) <= maxDistance && Position::getDistanceY(newPos, leader->getPosition()) <= maxDistance); + const bool condition1 = Position::getDistanceX(oldPos, leader->getPosition()) <= maxDistance && Position::getDistanceY(oldPos, leader->getPosition()) <= maxDistance; + const bool condition2 = Position::getDistanceX(newPos, leader->getPosition()) <= maxDistance && Position::getDistanceY(newPos, leader->getPosition()) <= maxDistance; if (condition1 && !condition2) { showPlayerStatus(player, leader, false); } else if (!condition1 && condition2) { @@ -669,17 +669,17 @@ void Party::updatePlayerHealth(const std::shared_ptr<Player> &player, const std: return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); - auto playerPosition = player->getPosition(); - auto leaderPosition = leader->getPosition(); + const int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); + const auto playerPosition = player->getPosition(); + const auto leaderPosition = leader->getPosition(); for (const auto &member : getMembers()) { auto memberPosition = member->getPosition(); - bool condition = (maxDistance == 0 || (Position::getDistanceX(playerPosition, memberPosition) <= maxDistance && Position::getDistanceY(playerPosition, memberPosition) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(playerPosition, memberPosition) <= maxDistance && Position::getDistanceY(playerPosition, memberPosition) <= maxDistance)); if (condition) { member->sendPartyCreatureHealth(target, healthPercent); } } - bool condition = (maxDistance == 0 || (Position::getDistanceX(playerPosition, leaderPosition) <= maxDistance && Position::getDistanceY(playerPosition, leaderPosition) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(playerPosition, leaderPosition) <= maxDistance && Position::getDistanceY(playerPosition, leaderPosition) <= maxDistance)); if (condition) { leader->sendPartyCreatureHealth(target, healthPercent); } @@ -691,14 +691,14 @@ void Party::updatePlayerMana(const std::shared_ptr<Player> &player, uint8_t mana return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); + const int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (const auto &member : getMembers()) { - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { member->sendPartyPlayerMana(player, manaPercent); } } - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); if (condition) { leader->sendPartyPlayerMana(player, manaPercent); } @@ -710,14 +710,14 @@ void Party::updatePlayerVocation(const std::shared_ptr<Player> &player) { return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); + const int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (const auto &member : getMembers()) { - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { member->sendPartyPlayerVocation(player); } } - bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); + const bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), leader->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), leader->getPosition()) <= maxDistance)); if (condition) { leader->sendPartyPlayerVocation(player); } @@ -745,12 +745,12 @@ void Party::addPlayerLoot(const std::shared_ptr<Player> &player, const std::shar auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared<PartyAnalyzer>(player->getID(), player->getName()); - membersData.push_back(playerAnalyzer); + membersData.emplace_back(playerAnalyzer); } uint32_t count = std::max<uint32_t>(1, item->getItemCount()); - if (auto it = playerAnalyzer->lootMap.find(item->getID()); it != playerAnalyzer->lootMap.end()) { - (*it).second += count; + if (const auto &it = playerAnalyzer->lootMap.find(item->getID()); it != playerAnalyzer->lootMap.end()) { + it->second += count; } else { playerAnalyzer->lootMap.insert({ item->getID(), count }); } @@ -758,7 +758,7 @@ void Party::addPlayerLoot(const std::shared_ptr<Player> &player, const std::shar if (priceType == LEADER_PRICE) { playerAnalyzer->lootPrice += leader->getItemCustomPrice(item->getID()) * count; } else { - std::map<uint16_t, uint64_t> itemMap { { item->getID(), count } }; + const std::map<uint16_t, uint64_t> itemMap { { item->getID(), count } }; playerAnalyzer->lootPrice += g_game().getItemMarketPrice(itemMap, false); } updateTrackerAnalyzer(); @@ -773,11 +773,11 @@ void Party::addPlayerSupply(const std::shared_ptr<Player> &player, const std::sh auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared<PartyAnalyzer>(player->getID(), player->getName()); - membersData.push_back(playerAnalyzer); + membersData.emplace_back(playerAnalyzer); } - if (auto it = playerAnalyzer->supplyMap.find(item->getID()); it != playerAnalyzer->supplyMap.end()) { - (*it).second += 1; + if (const auto &it = playerAnalyzer->supplyMap.find(item->getID()); it != playerAnalyzer->supplyMap.end()) { + it->second += 1; } else { playerAnalyzer->supplyMap.insert({ item->getID(), 1 }); } @@ -785,7 +785,7 @@ void Party::addPlayerSupply(const std::shared_ptr<Player> &player, const std::sh if (priceType == LEADER_PRICE) { playerAnalyzer->supplyPrice += leader->getItemCustomPrice(item->getID(), true); } else { - std::map<uint16_t, uint64_t> itemMap { { item->getID(), 1 } }; + const std::map<uint16_t, uint64_t> itemMap { { item->getID(), 1 } }; playerAnalyzer->supplyPrice += g_game().getItemMarketPrice(itemMap, true); } updateTrackerAnalyzer(); @@ -795,7 +795,7 @@ void Party::addPlayerDamage(const std::shared_ptr<Player> &player, uint64_t amou auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared<PartyAnalyzer>(player->getID(), player->getName()); - membersData.push_back(playerAnalyzer); + membersData.emplace_back(playerAnalyzer); } playerAnalyzer->damage += amount; @@ -806,7 +806,7 @@ void Party::addPlayerHealing(const std::shared_ptr<Player> &player, uint64_t amo auto playerAnalyzer = getPlayerPartyAnalyzerStruct(player->getID()); if (!playerAnalyzer) { playerAnalyzer = std::make_shared<PartyAnalyzer>(player->getID(), player->getName()); - membersData.push_back(playerAnalyzer); + membersData.emplace_back(playerAnalyzer); } playerAnalyzer->healing += amount; @@ -830,7 +830,7 @@ void Party::resetAnalyzer() { updateTrackerAnalyzer(); } -void Party::reloadPrices() { +void Party::reloadPrices() const { const auto &leader = getLeader(); if (!leader) { return; @@ -844,13 +844,13 @@ void Party::reloadPrices() { } analyzer->lootPrice = 0; - for (const auto &it : analyzer->lootMap) { - analyzer->lootPrice += leader->getItemCustomPrice(it.first) * it.second; + for (const auto &[fst, snd] : analyzer->lootMap) { + analyzer->lootPrice += leader->getItemCustomPrice(fst) * snd; } analyzer->supplyPrice = 0; - for (const auto &it : analyzer->supplyMap) { - analyzer->supplyPrice += leader->getItemCustomPrice(it.first, true) * it.second; + for (const auto &[fst, snd] : analyzer->supplyMap) { + analyzer->supplyPrice += leader->getItemCustomPrice(fst, true) * snd; } } } diff --git a/src/creatures/players/grouping/party.hpp b/src/creatures/players/grouping/party.hpp index f0b9a0c1e10..96c2ab45666 100644 --- a/src/creatures/players/grouping/party.hpp +++ b/src/creatures/players/grouping/party.hpp @@ -24,7 +24,7 @@ enum SharedExpStatus_t : uint8_t { class Player; class Party; -class Party : public SharedObject { +class Party final : public SharedObject { public: static std::shared_ptr<Party> create(const std::shared_ptr<Player> &leader); @@ -38,9 +38,9 @@ class Party : public SharedObject { std::vector<std::shared_ptr<Player>> getPlayers() const { std::vector<std::shared_ptr<Player>> players; for (auto &member : memberList) { - players.push_back(member); + players.emplace_back(member); } - players.push_back(getLeader()); + players.emplace_back(getLeader()); return players; } std::vector<std::shared_ptr<Player>> getMembers() { @@ -88,7 +88,7 @@ class Party : public SharedObject { void updatePlayerTicks(const std::shared_ptr<Player> &player, uint32_t points); void clearPlayerPoints(const std::shared_ptr<Player> &player); - void showPlayerStatus(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &member, bool showStatus); + void showPlayerStatus(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &member, bool showStatus) const; void updatePlayerStatus(const std::shared_ptr<Player> &player); void updatePlayerStatus(const std::shared_ptr<Player> &player, const Position &oldPos, const Position &newPos); void updatePlayerHealth(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, uint8_t healthPercent); @@ -102,10 +102,10 @@ class Party : public SharedObject { void addPlayerHealing(const std::shared_ptr<Player> &player, uint64_t amount); void switchAnalyzerPriceType(); void resetAnalyzer(); - void reloadPrices(); + void reloadPrices() const; std::shared_ptr<PartyAnalyzer> getPlayerPartyAnalyzerStruct(uint32_t playerId) const { - if (auto it = std::find_if(membersData.begin(), membersData.end(), [playerId](const std::shared_ptr<PartyAnalyzer> &preyIt) { + if (const auto &it = std::ranges::find_if(membersData, [playerId](const std::shared_ptr<PartyAnalyzer> &preyIt) { return preyIt->id == playerId; }); it != membersData.end()) { @@ -126,7 +126,7 @@ class Party : public SharedObject { std::vector<std::shared_ptr<PartyAnalyzer>> membersData; private: - const char* getSharedExpReturnMessage(SharedExpStatus_t value); + const char* getSharedExpReturnMessage(SharedExpStatus_t value) const; bool isPlayerActive(const std::shared_ptr<Player> &player); SharedExpStatus_t getSharedExperienceStatus(); uint32_t getHighestLevel(); diff --git a/src/creatures/players/grouping/team_finder.hpp b/src/creatures/players/grouping/team_finder.hpp index 9fafbd03227..e46217560b6 100644 --- a/src/creatures/players/grouping/team_finder.hpp +++ b/src/creatures/players/grouping/team_finder.hpp @@ -1,5 +1,3 @@ -#include <utility> - /** * Canary - A free and open-source MMORPG server emulator * Copyright (©) 2019-2024 OpenTibiaBR <opentibiabr@outlook.com> @@ -16,7 +14,7 @@ * This class is responsible control and manage the team finder feature. **/ -class TeamFinder { +class TeamFinder final { public: TeamFinder() = default; TeamFinder(uint16_t initMinLevel, uint16_t initMaxLevel, uint8_t initVocationIDs, uint16_t initTeamSlots, uint16_t initFreeSlots, bool initPartyBool, uint32_t initTimestamp, uint8_t initTeamType, uint16_t initBossID, uint16_t initHunt_type, uint16_t initHunt_area, uint16_t initQuestID, uint32_t initLeaderGuid, std::map<uint32_t, uint8_t> initMembersMap) : @@ -34,7 +32,7 @@ class TeamFinder { questID(initQuestID), leaderGuid(initLeaderGuid), membersMap(std::move(initMembersMap)) { } - virtual ~TeamFinder() = default; + ~TeamFinder() = default; uint16_t minLevel = 0; uint16_t maxLevel = 0; diff --git a/src/creatures/players/imbuements/imbuements.cpp b/src/creatures/players/imbuements/imbuements.cpp index c8073304369..e5504ca7dba 100644 --- a/src/creatures/players/imbuements/imbuements.cpp +++ b/src/creatures/players/imbuements/imbuements.cpp @@ -17,7 +17,7 @@ Imbuement* Imbuements::getImbuement(uint16_t id) { return nullptr; } - auto it = imbuementMap.find(id); + const auto &it = imbuementMap.find(id); if (it == imbuementMap.end()) { g_logger().warn("Imbuement {} not found", id); return nullptr; @@ -27,8 +27,8 @@ Imbuement* Imbuements::getImbuement(uint16_t id) { bool Imbuements::loadFromXml(bool /* reloading */) { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/imbuements.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/imbuements.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -83,14 +83,14 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - auto imbuements = imbuementMap.emplace(std::piecewise_construct, std::forward_as_tuple(runningid), std::forward_as_tuple(runningid, baseid)); + auto [fst, snd] = imbuementMap.emplace(std::piecewise_construct, std::forward_as_tuple(runningid), std::forward_as_tuple(runningid, baseid)); - if (!imbuements.second) { + if (!snd) { g_logger().warn("Duplicate imbuement of Base ID: '{}' ignored", baseid); continue; } - Imbuement &imbuement = imbuements.first->second; + Imbuement &imbuement = fst->second; pugi::xml_attribute iconBase = baseNode.attribute("iconid"); if (!iconBase) { @@ -140,14 +140,14 @@ bool Imbuements::loadFromXml(bool /* reloading */) { imbuement.name = nameBase.value(); for (const auto &childNode : baseNode.children()) { - if (!(attr = childNode.attribute("key"))) { + if (!((attr = childNode.attribute("key")))) { g_logger().warn("Missing key attribute in imbuement id: {}", runningid); continue; } std::string type = attr.as_string(); if (strcasecmp(type.c_str(), "item") == 0) { - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing item ID for imbuement name '{}'", imbuement.name); continue; } @@ -158,7 +158,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { count = pugi::cast<uint16_t>(childNode.attribute("count").value()); } - auto it2 = std::find_if(imbuement.items.begin(), imbuement.items.end(), [sourceId](const std::pair<uint16_t, uint16_t> &source) -> bool { + const auto &it2 = std::ranges::find_if(imbuement.items, [sourceId](const std::pair<uint16_t, uint16_t> &source) -> bool { return source.first == sourceId; }); @@ -178,7 +178,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { imbuement.description = description; } else if (strcasecmp(type.c_str(), "effect") == 0) { // Effects - if (!(attr = childNode.attribute("type"))) { + if (!((attr = childNode.attribute("type")))) { g_logger().warn("Missing effect type for imbuement name: {}", imbuement.name); continue; } @@ -186,7 +186,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { std::string effecttype = attr.as_string(); if (strcasecmp(effecttype.c_str(), "skill") == 0) { - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing effect value for imbuement name {}", imbuement.name); continue; } @@ -226,7 +226,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - if (!(attr = childNode.attribute("bonus"))) { + if (!((attr = childNode.attribute("bonus")))) { g_logger().warn("Missing skill bonus for imbuement name {}", imbuement.name); continue; } @@ -246,7 +246,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { imbuement.skills[skillId - 1] = chance; } } else if (strcasecmp(effecttype.c_str(), "damage") == 0) { - if (!(attr = childNode.attribute("combat"))) { + if (!((attr = childNode.attribute("combat")))) { g_logger().warn("Missing combat for imbuement name {}", imbuement.name); continue; } @@ -257,7 +257,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing damage reduction percentage for imbuement name {}", imbuement.name); continue; } @@ -267,7 +267,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { imbuement.combatType = combatType; imbuement.elementDamage = std::min<int16_t>(100, percent); } else if (strcasecmp(effecttype.c_str(), "reduction") == 0) { - if (!(attr = childNode.attribute("combat"))) { + if (!((attr = childNode.attribute("combat")))) { g_logger().warn("Missing combat for imbuement name {}", imbuement.name); continue; } @@ -278,7 +278,7 @@ bool Imbuements::loadFromXml(bool /* reloading */) { continue; } - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing damage reduction percentage for imbuement name {}", imbuement.name); continue; } @@ -287,14 +287,14 @@ bool Imbuements::loadFromXml(bool /* reloading */) { imbuement.absorbPercent[combatTypeToIndex(combatType)] = percent; } else if (strcasecmp(effecttype.c_str(), "speed") == 0) { - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing speed value for imbuement name {}", imbuement.name); continue; } imbuement.speed = pugi::cast<uint32_t>(attr.value()); } else if (strcasecmp(effecttype.c_str(), "capacity") == 0) { - if (!(attr = childNode.attribute("value"))) { + if (!((attr = childNode.attribute("value")))) { g_logger().warn("Missing cap value for imbuement name {}", imbuement.name); continue; } @@ -321,7 +321,7 @@ bool Imbuements::reload() { } BaseImbuement* Imbuements::getBaseByID(uint16_t id) { - auto baseImbuements = std::find_if(basesImbuement.begin(), basesImbuement.end(), [id](const BaseImbuement &groupImbuement) { + const auto &baseImbuements = std::ranges::find_if(basesImbuement, [id](const BaseImbuement &groupImbuement) { return groupImbuement.id == id; }); @@ -329,7 +329,7 @@ BaseImbuement* Imbuements::getBaseByID(uint16_t id) { } CategoryImbuement* Imbuements::getCategoryByID(uint16_t id) { - auto categoryImbuements = std::find_if(categoriesImbuement.begin(), categoriesImbuement.end(), [id](const CategoryImbuement &categoryImbuement) { + const auto &categoryImbuements = std::ranges::find_if(categoriesImbuement, [id](const CategoryImbuement &categoryImbuement) { return categoryImbuement.id == id; }); @@ -364,7 +364,7 @@ std::vector<Imbuement*> Imbuements::getImbuements(const std::shared_ptr<Player> continue; } - imbuements.push_back(imbuement); + imbuements.emplace_back(imbuement); } return imbuements; diff --git a/src/creatures/players/imbuements/imbuements.hpp b/src/creatures/players/imbuements/imbuements.hpp index 27868c99cc3..111d12d8024 100644 --- a/src/creatures/players/imbuements/imbuements.hpp +++ b/src/creatures/players/imbuements/imbuements.hpp @@ -18,6 +18,8 @@ class Item; class Imbuement; +constexpr int32_t maxSkillOrStatId = std::max<int32_t>(STAT_LAST, SKILL_LAST); + struct BaseImbuement { BaseImbuement(uint16_t initId, std::string initName, uint32_t initPrice, uint32_t initProtectionPrice, uint32_t initRemoveCost, uint32_t initDuration, uint8_t initPercent) : id(initId), name(std::move(initName)), price(initPrice), protectionPrice(initProtectionPrice), removeCost(initRemoveCost), duration(initDuration), percent(initPercent) { } @@ -120,7 +122,7 @@ class Imbuement { } uint16_t icon = 1; - int32_t stats[STAT_LAST + 1] = {}; + int32_t stats[maxSkillOrStatId + 1] = {}; int32_t skills[SKILL_LAST + 1] = {}; int32_t speed = 0; uint32_t capacity = 0; diff --git a/src/creatures/players/management/ban.cpp b/src/creatures/players/management/ban.cpp index 70b9a80dd2d..83bad724664 100644 --- a/src/creatures/players/management/ban.cpp +++ b/src/creatures/players/management/ban.cpp @@ -17,9 +17,9 @@ bool Ban::acceptConnection(uint32_t clientIP) { std::scoped_lock<std::recursive_mutex> lockClass(lock); - uint64_t currentTime = OTSYS_TIME(); + const uint64_t currentTime = OTSYS_TIME(); - auto it = ipConnectMap.find(clientIP); + const auto &it = ipConnectMap.find(clientIP); if (it == ipConnectMap.end()) { ipConnectMap.emplace(clientIP, ConnectBlock(currentTime, 0, 1)); return true; @@ -31,7 +31,7 @@ bool Ban::acceptConnection(uint32_t clientIP) { return false; } - int64_t timeDiff = currentTime - connectBlock.lastAttempt; + const int64_t timeDiff = currentTime - connectBlock.lastAttempt; connectBlock.lastAttempt = currentTime; if (timeDiff <= 5000) { if (++connectBlock.count > 5) { @@ -53,12 +53,12 @@ bool IOBan::isAccountBanned(uint32_t accountId, BanInfo &banInfo) { std::ostringstream query; query << "SELECT `reason`, `expires_at`, `banned_at`, `banned_by`, (SELECT `name` FROM `players` WHERE `id` = `banned_by`) AS `name` FROM `account_bans` WHERE `account_id` = " << accountId; - DBResult_ptr result = db.storeQuery(query.str()); + const DBResult_ptr result = db.storeQuery(query.str()); if (!result) { return false; } - auto expiresAt = result->getNumber<int64_t>("expires_at"); + const auto expiresAt = result->getNumber<int64_t>("expires_at"); if (expiresAt != 0 && time(nullptr) > expiresAt) { // Move the ban to history if it has expired query.str(std::string()); @@ -87,12 +87,12 @@ bool IOBan::isIpBanned(uint32_t clientIP, BanInfo &banInfo) { std::ostringstream query; query << "SELECT `reason`, `expires_at`, (SELECT `name` FROM `players` WHERE `id` = `banned_by`) AS `name` FROM `ip_bans` WHERE `ip` = " << clientIP; - DBResult_ptr result = db.storeQuery(query.str()); + const DBResult_ptr result = db.storeQuery(query.str()); if (!result) { return false; } - auto expiresAt = result->getNumber<int64_t>("expires_at"); + const auto expiresAt = result->getNumber<int64_t>("expires_at"); if (expiresAt != 0 && time(nullptr) > expiresAt) { query.str(std::string()); query << "DELETE FROM `ip_bans` WHERE `ip` = " << clientIP; diff --git a/src/creatures/players/management/ban.hpp b/src/creatures/players/management/ban.hpp index 6fdb94296df..3e9b3f07f58 100644 --- a/src/creatures/players/management/ban.hpp +++ b/src/creatures/players/management/ban.hpp @@ -10,18 +10,18 @@ #pragma once struct BanInfo { - std::string bannedBy; - std::string reason; - time_t expiresAt; + std::string bannedBy {}; + std::string reason {}; + time_t expiresAt {}; }; struct ConnectBlock { constexpr ConnectBlock(uint64_t lastAttempt, uint64_t blockTime, uint32_t count) : lastAttempt(lastAttempt), blockTime(blockTime), count(count) { } - uint64_t lastAttempt; - uint64_t blockTime; - uint32_t count; + uint64_t lastAttempt {}; + uint64_t blockTime {}; + uint32_t count {}; }; using IpConnectMap = std::map<uint32_t, ConnectBlock>; diff --git a/src/creatures/players/management/waitlist.cpp b/src/creatures/players/management/waitlist.cpp index 59c6fc84ab3..5edeb23d4c2 100644 --- a/src/creatures/players/management/waitlist.cpp +++ b/src/creatures/players/management/waitlist.cpp @@ -27,13 +27,13 @@ WaitingList &WaitingList::getInstance() { return inject<WaitingList>(); } -void WaitingList::cleanupList(WaitList &list) { - int64_t time = OTSYS_TIME(); +void WaitingList::cleanupList(WaitList &list) const { + const int64_t time = OTSYS_TIME(); auto it = list.begin(); while (it != list.end()) { - auto timeout = static_cast<int64_t>(it->timeout); - g_logger().warn("time: {}", timeout - time); + const auto timeout = static_cast<int64_t>(it->timeout); + g_logger().debug("time: {}", timeout - time); if ((timeout - time) <= 0) { info->playerReferences.erase(it->playerGUID); it = list.erase(it); @@ -43,30 +43,32 @@ void WaitingList::cleanupList(WaitList &list) { } } -std::size_t WaitingList::getTimeout(std::size_t slot) { +std::size_t WaitingList::getTimeout(std::size_t slot) const { return WaitingList::getTime(slot) + TIMEOUT_EXTRA; } std::size_t WaitingList::getTime(std::size_t slot) { if (slot < SLOT_LIMIT_ONE) { return 5; - } else if (slot < SLOT_LIMIT_TWO) { + } + if (slot < SLOT_LIMIT_TWO) { return 10; - } else if (slot < SLOT_LIMIT_THREE) { + } + if (slot < SLOT_LIMIT_THREE) { return 20; - } else if (slot < SLOT_LIMIT_FOUR) { + } + if (slot < SLOT_LIMIT_FOUR) { return 60; - } else { - return 120; } + return 120; } -bool WaitingList::clientLogin(const std::shared_ptr<Player> &player) { +bool WaitingList::clientLogin(const std::shared_ptr<Player> &player) const { if (player->hasFlag(PlayerFlags_t::CanAlwaysLogin) || player->getAccountType() >= ACCOUNT_TYPE_GAMEMASTER) { return true; } - auto maxPlayers = static_cast<uint32_t>(g_configManager().getNumber(MAX_PLAYERS, __FUNCTION__)); + const auto maxPlayers = static_cast<uint32_t>(g_configManager().getNumber(MAX_PLAYERS, __FUNCTION__)); if (maxPlayers == 0 || (info->priorityWaitList.empty() && info->waitList.empty() && g_game().getPlayersOnline() < maxPlayers)) { return true; } @@ -76,8 +78,8 @@ bool WaitingList::clientLogin(const std::shared_ptr<Player> &player) { addPlayerToList(player); - auto it = info->playerReferences.find(player->getGUID()); - std::size_t slot = it->second.second; + const auto &it = info->playerReferences.find(player->getGUID()); + const std::size_t slot = it->second.second; if ((g_game().getPlayersOnline() + slot) <= maxPlayers) { // should be able to login now info->waitList.erase(it->second.first); @@ -87,8 +89,8 @@ bool WaitingList::clientLogin(const std::shared_ptr<Player> &player) { return false; } -void WaitingList::addPlayerToList(const std::shared_ptr<Player> &player) { - auto it = info->playerReferences.find(player->getGUID()); +void WaitingList::addPlayerToList(const std::shared_ptr<Player> &player) const { + const auto &it = info->playerReferences.find(player->getGUID()); if (it != info->playerReferences.end()) { std::size_t slot; if (player->isPremium()) { @@ -113,8 +115,8 @@ void WaitingList::addPlayerToList(const std::shared_ptr<Player> &player) { } } -std::size_t WaitingList::getClientSlot(const std::shared_ptr<Player> &player) { - auto it = info->playerReferences.find(player->getGUID()); +std::size_t WaitingList::getClientSlot(const std::shared_ptr<Player> &player) const { + const auto &it = info->playerReferences.find(player->getGUID()); if (it == info->playerReferences.end()) { return 0; } diff --git a/src/creatures/players/management/waitlist.hpp b/src/creatures/players/management/waitlist.hpp index dfe34122196..28a21b4a4b1 100644 --- a/src/creatures/players/management/waitlist.hpp +++ b/src/creatures/players/management/waitlist.hpp @@ -34,13 +34,13 @@ class WaitingList { public: WaitingList(); static WaitingList &getInstance(); - bool clientLogin(const std::shared_ptr<Player> &player); - std::size_t getClientSlot(const std::shared_ptr<Player> &player); + bool clientLogin(const std::shared_ptr<Player> &player) const; + std::size_t getClientSlot(const std::shared_ptr<Player> &player) const; static std::size_t getTime(std::size_t slot); private: - void cleanupList(WaitList &list); - std::size_t getTimeout(std::size_t slot); - void addPlayerToList(const std::shared_ptr<Player> &player); + void cleanupList(WaitList &list) const; + std::size_t getTimeout(std::size_t slot) const; + void addPlayerToList(const std::shared_ptr<Player> &player) const; std::unique_ptr<WaitListInfo> info; }; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 4ad59a0179a..b1ea534f65a 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -124,7 +124,7 @@ std::string Player::getDescription(int32_t lookDistance) { std::ostringstream s; std::string subjectPronoun = getSubjectPronoun(); capitalizeWords(subjectPronoun); - auto playerTitle = title()->getCurrentTitle() == 0 ? "" : (", " + title()->getCurrentTitleName()); + const auto playerTitle = title()->getCurrentTitle() == 0 ? "" : (", " + title()->getCurrentTitleName()); if (lookDistance == -1) { s << "yourself" << playerTitle << "."; @@ -180,14 +180,14 @@ std::string Player::getDescription(int32_t lookDistance) { s << " " << subjectPronoun << " " << getSubjectVerb() << " in a party with "; } - size_t memberCount = m_party->getMemberCount() + 1; + const size_t memberCount = m_party->getMemberCount() + 1; if (memberCount == 1) { s << "1 member and "; } else { s << memberCount << " members and "; } - size_t invitationCount = m_party->getInvitationCount(); + const size_t invitationCount = m_party->getInvitationCount(); if (invitationCount == 1) { s << "1 pending invitation."; } else { @@ -196,7 +196,7 @@ std::string Player::getDescription(int32_t lookDistance) { } if (guild && guildRank) { - size_t memberCount = guild->getMemberCount(); + const size_t memberCount = guild->getMemberCount(); if (memberCount >= 1000) { s << ""; return s.str(); @@ -270,7 +270,7 @@ std::shared_ptr<Item> Player::getWeapon(Slots_t slot, bool ignoreAmmo) const { } bool Player::hasQuiverEquipped() const { - std::shared_ptr<Item> quiver = inventory[CONST_SLOT_RIGHT]; + const auto &quiver = inventory[CONST_SLOT_RIGHT]; return quiver && quiver->isQuiver() && quiver->getContainer(); } @@ -649,7 +649,7 @@ uint16_t Player::getLoyaltySkill(skills_t skill) const { } absl::uint128 tries = skills[skill].tries; - absl::uint128 totalTries = vocation->getTotalSkillTries(skill, skills[skill].level) + tries; + const absl::uint128 totalTries = vocation->getTotalSkillTries(skill, skills[skill].level) + tries; absl::uint128 loyaltyTries = (totalTries * getLoyaltyBonus()) / 100; while ((tries + loyaltyTries) >= nextReqTries) { loyaltyTries -= nextReqTries - tries; @@ -800,7 +800,7 @@ void Player::closeContainer(uint8_t cid) { return; } - OpenContainer openContainer = it->second; + const OpenContainer &openContainer = it->second; const auto &container = openContainer.container; if (container && container->isAnyKindOfRewardChest() && !hasOtherRewardContainerOpen(container)) { @@ -1104,7 +1104,7 @@ std::shared_ptr<Container> Player::getManagedContainer(ObjectCategory_t category category = OBJECTCATEGORY_DEFAULT; } - auto it = m_managedContainers.find(category); + const auto it = m_managedContainers.find(category); std::shared_ptr<Container> container = nullptr; if (it != m_managedContainers.end()) { container = isLootContainer ? it->second.first : it->second.second; @@ -1275,7 +1275,7 @@ std::shared_ptr<DepotLocker> Player::getDepotLocker(uint32_t depotId) { } const auto &depotChest = Item::CreateItemAsContainer(ITEM_DEPOT, static_cast<uint16_t>(g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__))); for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__); i > 0; i--) { - std::shared_ptr<DepotChest> depotBox = getDepotChest(i, true); + const auto &depotBox = getDepotChest(i, true); depotChest->internalAddThing(depotBox); depotBox->setParent(depotChest); } @@ -1350,7 +1350,7 @@ void Player::sendStats() { void Player::updateSupplyTracker(const std::shared_ptr<Item> &item) { const auto &iType = Item::items.getItemType(item->getID()); - auto value = iType.buyPrice; + const auto value = iType.buyPrice; g_metrics().addCounter("player_supply", value, { { "player", getName() } }); if (client) { @@ -1369,7 +1369,7 @@ void Player::updateImpactTracker(CombatType_t type, int32_t amount) const { } void Player::sendPing() { - int64_t timeNow = OTSYS_TIME(); + const int64_t timeNow = OTSYS_TIME(); bool hasLostConnection = false; if ((timeNow - lastPing) >= 5000) { @@ -1381,7 +1381,7 @@ void Player::sendPing() { } } - int64_t noPongTime = timeNow - lastPong; + const int64_t noPongTime = timeNow - lastPong; const auto &attackedCreature = getAttackedCreature(); if ((hasLostConnection || noPongTime >= 7000) && attackedCreature && attackedCreature->getPlayer()) { setAttackedCreature(nullptr); @@ -1425,9 +1425,9 @@ std::shared_ptr<House> Player::getEditHouse(uint32_t &retWindowTextId, uint32_t return editHouse; } -void Player::setEditHouse(std::shared_ptr<House> house, uint32_t listId /*= 0*/) { +void Player::setEditHouse(const std::shared_ptr<House> &house, uint32_t listId /*= 0*/) { windowTextId++; - editHouse = std::move(house); + editHouse = house; editListId = listId; } @@ -1472,7 +1472,7 @@ void Player::onApplyImbuement(const Imbuement* imbuement, const std::shared_ptr< price += protectionCharm ? baseImbuement->protectionPrice : 0; if (!g_game().removeMoney(static_self_cast<Player>(), price, 0, true)) { - std::string message = fmt::format("You don't have {} gold coins.", price); + const std::string message = fmt::format("You don't have {} gold coins.", price); g_logger().error("[Player::onApplyImbuement] - An error occurred while player with name {} try to apply imbuement, player do not have money", this->getName()); sendImbuementResult(message); @@ -1484,7 +1484,7 @@ void Player::onApplyImbuement(const Imbuement* imbuement, const std::shared_ptr< for (auto &[key, value] : items) { std::stringstream withdrawItemMessage; - uint32_t inventoryItemCount = getItemTypeCount(key); + const uint32_t inventoryItemCount = getItemTypeCount(key); if (inventoryItemCount >= value) { removeItemOfType(key, value, -1, true); continue; @@ -1536,7 +1536,7 @@ void Player::onClearImbuement(const std::shared_ptr<Item> &item, uint8_t slot) { } if (!g_game().removeMoney(static_self_cast<Player>(), baseImbuement->removeCost, 0, true)) { - std::string message = fmt::format("You don't have {} gold coins.", baseImbuement->removeCost); + const std::string message = fmt::format("You don't have {} gold coins.", baseImbuement->removeCost); g_logger().error("[Player::onClearImbuement] - An error occurred while player with name {} try to apply imbuement, player do not have money", this->getName()); this->sendImbuementResult(message); @@ -1604,8 +1604,8 @@ void Player::sendAddContainerItem(const std::shared_ptr<Container> &container, s uint16_t slot = openContainer.index; if (container->getID() == ITEM_BROWSEFIELD) { - uint16_t containerSize = container->size() - 1; - uint16_t pageEnd = openContainer.index + container->capacity() - 1; + const uint16_t containerSize = container->size() - 1; + const uint16_t pageEnd = openContainer.index + container->capacity() - 1; if (containerSize > pageEnd) { slot = pageEnd; item = container->getItemByIndex(pageEnd); @@ -1634,7 +1634,7 @@ void Player::sendUpdateContainerItem(const std::shared_ptr<Container> &container continue; } - uint16_t pageEnd = openContainer.index + container->capacity(); + const uint16_t pageEnd = openContainer.index + container->capacity(); if (slot >= pageEnd) { continue; } @@ -1792,7 +1792,7 @@ void Player::onChangeZone(ZoneType_t zone) { wasMounted = true; } } else { - int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY, __FUNCTION__); + const int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY, __FUNCTION__); if (ticks > 0) { if (const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks, 0)) { addCondition(condition); @@ -1966,7 +1966,7 @@ void Player::onCreatureMove(const std::shared_ptr<Creature> &creature, const std // close modal windows if (!modalWindows.empty()) { // TODO: This shouldn't be hardcoded - for (uint32_t modalWindowId : modalWindows) { + for (const uint32_t modalWindowId : modalWindows) { if (modalWindowId == std::numeric_limits<uint32_t>::max()) { sendTextMessage(MESSAGE_EVENT_ADVANCE, "Offline training aborted."); break; @@ -2060,7 +2060,7 @@ void Player::onSendContainer(const std::shared_ptr<Container> &container) { return; } - bool hasParent = container->hasParent(); + const bool hasParent = container->hasParent(); for (const auto &[fst, snd] : openContainers) { const auto &openContainer = snd; if (openContainer.container == container) { @@ -2243,7 +2243,7 @@ uint32_t Player::isMuted() const { } int32_t muteTicks = 0; - for (const std::shared_ptr<Condition> &condition : conditions) { + for (const auto &condition : conditions) { if (condition->getType() == CONDITION_MUTED && condition->getTicks() > muteTicks) { muteTicks = condition->getTicks(); } @@ -2271,7 +2271,7 @@ void Player::removeMessageBuffer() { muteCount = it->second; } - uint32_t muteTime = 5 * muteCount * muteCount; + const uint32_t muteTime = 5 * muteCount * muteCount; muteCountMap[guid] = muteCount + 1; const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_MUTED, muteTime * 1000, 0); addCondition(condition); @@ -2292,7 +2292,7 @@ void Player::drainHealth(const std::shared_ptr<Creature> &attacker, int32_t dama sendStats(); } -void Player::drainMana(const std::shared_ptr<Creature> attacker, int32_t manaLoss) { +void Player::drainMana(const std::shared_ptr<Creature> &attacker, int32_t manaLoss) { Creature::drainMana(attacker, manaLoss); sendStats(); } @@ -2375,8 +2375,8 @@ void Player::addExperience(const std::shared_ptr<Creature> &target, uint64_t exp return; } - auto rate = exp / rawExp; - std::map<std::string, std::string> attrs({ { "player", getName() }, { "level", std::to_string(getLevel()) }, { "rate", std::to_string(rate) } }); + const auto rate = exp / rawExp; + const std::map<std::string, std::string> attrs({ { "player", getName() }, { "level", std::to_string(getLevel()) }, { "rate", std::to_string(rate) } }); if (sendText) { g_metrics().addCounter("player_experience_raw", rawExp, attrs); g_metrics().addCounter("player_experience_actual", exp, attrs); @@ -2420,7 +2420,7 @@ void Player::addExperience(const std::shared_ptr<Creature> &target, uint64_t exp } } - uint32_t prevLevel = level; + const uint32_t prevLevel = level; while (experience >= nextLevelExp) { ++level; // Player stats gain for vocations level <= 8 @@ -2495,7 +2495,7 @@ void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { if (sendText) { lostExp -= experience; - std::string expString = fmt::format("You lost {} experience point{}.", lostExp, (lostExp != 1 ? "s" : "")); + const std::string expString = fmt::format("You lost {} experience point{}.", lostExp, (lostExp != 1 ? "s" : "")); TextMessage message(MESSAGE_EXPERIENCE, expString); message.position = position; @@ -2514,7 +2514,7 @@ void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { } } - uint32_t oldLevel = level; + const uint32_t oldLevel = level; uint64_t currLevelExp = Player::getExpForLevel(level); while (level > 1 && experience < currLevelExp) { @@ -2553,7 +2553,7 @@ void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { sendTextMessage(MESSAGE_EVENT_ADVANCE, ss.str()); } - uint64_t nextLevelExp = Player::getExpForLevel(level + 1); + const uint64_t nextLevelExp = Player::getExpForLevel(level + 1); if (nextLevelExp > currLevelExp) { levelPercent = Player::getPercentLevel(experience - currLevelExp, nextLevelExp - currLevelExp); } else { @@ -2568,7 +2568,7 @@ double_t Player::getPercentLevel(uint64_t count, uint64_t nextLevelCount) { return 0; } - double_t result = round(((count * 100.) / nextLevelCount) * 100.) / 100.; + const double_t result = round(((count * 100.) / nextLevelCount) * 100.) / 100.; if (result > 100) { return 0; } @@ -2585,7 +2585,7 @@ void Player::onBlockHit() { } } -void Player::onTakeDamage(std::shared_ptr<Creature> attacker, int32_t damage) { +void Player::onTakeDamage(const std::shared_ptr<Creature> &attacker, int32_t damage) { // nothing here yet } @@ -2701,7 +2701,7 @@ BlockType_t Player::blockHit(const std::shared_ptr<Creature> &attacker, const Co return blockType; } -void Player::death(std::shared_ptr<Creature> lastHitCreature) { +void Player::death(const std::shared_ptr<Creature> &lastHitCreature) { if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ, __FUNCTION__) && isMounted()) { dismount(); g_game().internalCreatureChangeOutfit(getPlayer(), defaultOutfit); @@ -2717,9 +2717,9 @@ void Player::death(std::shared_ptr<Creature> lastHitCreature) { uint32_t sumLevels = 0; uint32_t inFightTicks = 5 * 60 * 1000; for (const auto &[fst, snd] : damageMap) { - auto [total, ticks] = snd; + const auto &[total, ticks] = snd; if ((OTSYS_TIME() - ticks) <= inFightTicks) { - std::shared_ptr<Player> damageDealer = g_game().getPlayerByID(fst); + const auto &damageDealer = g_game().getPlayerByID(fst); if (damageDealer) { playerDmg += total; sumLevels += damageDealer->getLevel(); @@ -3113,7 +3113,7 @@ bool Player::hasCapacity(const std::shared_ptr<Item> &item, uint32_t count) cons return itemWeight <= getFreeCapacity(); } -ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature>) { +ReturnValue Player::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &) { const auto &item = thing->getItem(); if (item == nullptr) { g_logger().error("[Player::queryAdd] - Item is nullptr"); @@ -3359,7 +3359,7 @@ ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr<Thing> &t } } } else if (inventoryItem->isStackable() && item->equals(inventoryItem) && inventoryItem->getItemCount() < inventoryItem->getStackSize()) { - uint32_t remainder = (inventoryItem->getStackSize() - inventoryItem->getItemCount()); + const uint32_t remainder = (inventoryItem->getStackSize() - inventoryItem->getItemCount()); if (queryAdd(slotIndex, item, remainder, flags) == RETURNVALUE_NOERROR) { n += remainder; @@ -3406,8 +3406,8 @@ ReturnValue Player::queryMaxCount(int32_t index, const std::shared_ptr<Thing> &t return RETURNVALUE_NOERROR; } -ReturnValue Player::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> /*= nullptr*/) { - int32_t index = getThingIndex(thing); +ReturnValue Player::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> & /*= nullptr */) { + const int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; } @@ -3557,7 +3557,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh return getPlayer(); } -void Player::addThing(int32_t index, const std::shared_ptr<Thing> thing) { +void Player::addThing(int32_t index, const std::shared_ptr<Thing> &thing) { if (!thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -3647,7 +3647,7 @@ void Player::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { item->resetParent(); inventory[index] = nullptr; } else { - uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, item->getItemCount() - count)); + const uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, item->getItemCount() - count)); item->setItemCount(newCount); // send change to client @@ -3957,7 +3957,7 @@ void Player::updateDamageReductionFromItemImbuement( for (uint8_t imbueSlotId = 0; imbueSlotId < item->getImbuementSlot(); imbueSlotId++) { ImbuementInfo imbuementInfo; if (item->getImbuementInfo(imbueSlotId, &imbuementInfo) && imbuementInfo.imbuement) { - int16_t imbuementAbsorption = imbuementInfo.imbuement->absorbPercent[combatTypeIndex]; + const int16_t imbuementAbsorption = imbuementInfo.imbuement->absorbPercent[combatTypeIndex]; if (imbuementAbsorption != 0) { combatReductionArray[combatTypeIndex] = calculateDamageReduction(combatReductionArray[combatTypeIndex], imbuementAbsorption); } @@ -3974,7 +3974,7 @@ void Player::updateDamageReductionFromItemAbility( const ItemType &itemType = Item::items[item->getID()]; if (itemType.abilities) { - int16_t elementReduction = itemType.abilities->absorbPercent[combatTypeIndex]; + const int16_t elementReduction = itemType.abilities->absorbPercent[combatTypeIndex]; if (elementReduction != 0) { combatReductionArray[combatTypeIndex] = calculateDamageReduction(combatReductionArray[combatTypeIndex], elementReduction); } @@ -4125,7 +4125,7 @@ std::map<uint16_t, uint16_t> &Player::getAllSaleItemIdAndCount(std::map<uint16_t void Player::getAllItemTypeCountAndSubtype(std::map<uint32_t, uint32_t> &countMap) const { for (const auto &item : getAllInventoryItems()) { - uint16_t itemId = item->getID(); + const uint16_t itemId = item->getID(); if (Item::items[itemId].isFluidContainer()) { countMap[static_cast<uint32_t>(itemId) | (item->getAttribute<uint32_t>(ItemAttribute_t::FLUIDTYPE)) << 16] += item->getItemCount(); } else { @@ -4395,7 +4395,7 @@ void Player::doAttacking(uint32_t) { const auto &tool = getWeapon(); const auto &weapon = g_weapons().getWeapon(tool); uint32_t delay = getAttackSpeed(); - bool classicSpeed = g_configManager().getBoolean(CLASSIC_ATTACK_SPEED, __FUNCTION__); + const bool classicSpeed = g_configManager().getBoolean(CLASSIC_ATTACK_SPEED, __FUNCTION__); if (weapon) { if (!weapon->interruptSwing()) { @@ -4446,7 +4446,7 @@ void Player::onFollowCreature(const std::shared_ptr<Creature> &creature) { } void Player::setChaseMode(bool mode) { - bool prevChaseMode = chaseMode; + const bool prevChaseMode = chaseMode; chaseMode = mode; const auto &attackedCreature = getAttackedCreature(); const auto &followCreature = getFollowCreature(); @@ -4785,7 +4785,7 @@ void Player::addHuntingTaskKill(const std::shared_ptr<MonsterType> &mType) { taskSlot->currentKills += 1; if ((taskSlot->upgrade && taskSlot->currentKills >= option->secondKills) || (!taskSlot->upgrade && taskSlot->currentKills >= option->firstKills)) { taskSlot->state = PreyTaskDataState_Completed; - std::string message = "You succesfully finished your hunting task. Your reward is ready to be claimed!"; + const std::string message = "You succesfully finished your hunting task. Your reward is ready to be claimed!"; sendTextMessage(MESSAGE_STATUS, message); } reloadTaskSlot(taskSlot->id); @@ -5070,7 +5070,7 @@ void Player::addFamiliar(uint16_t lookType) { } bool Player::removeFamiliar(uint16_t lookType) { - auto initialSize = familiars.size(); + const auto initialSize = familiars.size(); std::erase_if(familiars, [&](const FamiliarEntry &entry) { return entry.lookType == lookType; }); @@ -5114,7 +5114,7 @@ Skulls_t Player::getSkull() const { return skull; } -Skulls_t Player::getSkullClient(std::shared_ptr<Creature> creature) { +Skulls_t Player::getSkullClient(const std::shared_ptr<Creature> &creature) { if (!creature || g_game().getWorldType() != WORLD_TYPE_PVP) { return SKULL_NONE; } @@ -5220,7 +5220,7 @@ void Player::addUnjustifiedDead(const std::shared_ptr<Player> &attacked) { } void Player::checkSkullTicks(int64_t ticks) { - int64_t newTicks = skullTicks - ticks; + const int64_t newTicks = skullTicks - ticks; if (newTicks < 0) { skullTicks = 0; } else { @@ -5233,13 +5233,13 @@ void Player::checkSkullTicks(int64_t ticks) { } bool Player::isPromoted() const { - uint16_t promotedVocation = g_vocations().getPromotedVocation(vocation->getId()); + const uint16_t promotedVocation = g_vocations().getPromotedVocation(vocation->getId()); return promotedVocation == VOCATION_NONE && vocation->getId() != promotedVocation; } double Player::getLostPercent() const { int32_t blessingCount = 0; - uint8_t maxBlessing = (operatingSystem == CLIENTOS_NEW_WINDOWS || operatingSystem == CLIENTOS_NEW_MAC) ? 8 : 6; + const uint8_t maxBlessing = (operatingSystem == CLIENTOS_NEW_WINDOWS || operatingSystem == CLIENTOS_NEW_MAC) ? 8 : 6; for (int i = 2; i <= maxBlessing; i++) { if (hasBlessing(i)) { blessingCount++; @@ -5258,7 +5258,7 @@ double Player::getLostPercent() const { double lossPercent; if (level >= 24) { - double tmpLevel = level + (levelPercent / 100.); + const double tmpLevel = level + (levelPercent / 100.); lossPercent = ((tmpLevel + 50) * 50 * ((tmpLevel * tmpLevel) - (5 * tmpLevel) + 8)) / experience; } else { lossPercent = 5; @@ -5332,7 +5332,7 @@ uint32_t Player::getLoyaltyMagicLevel() const { } absl::uint128 spent = manaSpent; - absl::uint128 totalMana = vocation->getTotalMana(level) + spent; + const absl::uint128 totalMana = vocation->getTotalMana(level) + spent; absl::uint128 loyaltyMana = (totalMana * getLoyaltyBonus()) / 100; while ((spent + loyaltyMana) >= nextReqMana) { loyaltyMana -= nextReqMana - spent; @@ -5371,7 +5371,7 @@ uint16_t Player::getSkillLevel(skills_t skill) const { auto skillLevel = getLoyaltySkill(skill); skillLevel = std::max<int32_t>(0, skillLevel + varSkills[skill]); - if (auto it = maxValuePerSkill.find(skill); + if (const auto it = maxValuePerSkill.find(skill); it != maxValuePerSkill.end()) { skillLevel = std::min<int32_t>(it->second, skillLevel); } @@ -5399,7 +5399,7 @@ uint16_t Player::getSkillLevel(skills_t skill) const { skillLevel += m_wheelPlayer->checkAvatarSkill(WheelAvatarSkill_t::CRITICAL_DAMAGE); } - int32_t avatarCritChance = m_wheelPlayer->checkAvatarSkill(WheelAvatarSkill_t::CRITICAL_CHANCE); + const int32_t avatarCritChance = m_wheelPlayer->checkAvatarSkill(WheelAvatarSkill_t::CRITICAL_CHANCE); if (skill == SKILL_CRITICAL_HIT_CHANCE && avatarCritChance > 0) { skillLevel = avatarCritChance; // 100% } @@ -5450,7 +5450,7 @@ int32_t Player::getCleavePercent(bool useCharges) const { const int32_t &cleave_percent = it.abilities->cleavePercent; if (cleave_percent != 0) { result += cleave_percent; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5479,7 +5479,7 @@ int32_t Player::getPerfectShotDamage(uint8_t range, bool useCharges) const { if (itemType.abilities->perfectShotRange == range) { result += itemType.abilities->perfectShotDamage; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5497,10 +5497,10 @@ int32_t Player::getSpecializedMagicLevel(CombatType_t combat, bool useCharges) c continue; } - int32_t specialized_magic_level = itemType.abilities->specializedMagicLevel[combatTypeToIndex(combat)]; + const int32_t specialized_magic_level = itemType.abilities->specializedMagicLevel[combatTypeToIndex(combat)]; if (specialized_magic_level > 0) { result += specialized_magic_level; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5518,10 +5518,10 @@ int32_t Player::getMagicShieldCapacityFlat(bool useCharges) const { continue; } - int32_t magicCapacity = itemType.abilities->magicShieldCapacityFlat; + const int32_t magicCapacity = itemType.abilities->magicShieldCapacityFlat; if (magicCapacity != 0) { result += magicCapacity; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5539,10 +5539,10 @@ int32_t Player::getMagicShieldCapacityPercent(bool useCharges) const { continue; } - int32_t magicPercent = itemType.abilities->magicShieldCapacityPercent; + const int32_t magicPercent = itemType.abilities->magicShieldCapacityPercent; if (magicPercent != 0) { result += magicPercent; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5560,10 +5560,10 @@ int32_t Player::getReflectPercent(CombatType_t combat, bool useCharges) const { continue; } - int32_t reflectPercent = itemType.abilities->reflectPercent[combatTypeToIndex(combat)]; + const int32_t reflectPercent = itemType.abilities->reflectPercent[combatTypeToIndex(combat)]; if (reflectPercent != 0) { result += reflectPercent; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5581,10 +5581,10 @@ int32_t Player::getReflectFlat(CombatType_t combat, bool useCharges) const { continue; } - int32_t reflectFlat = itemType.abilities->reflectFlat[combatTypeToIndex(combat)]; + const int32_t reflectFlat = itemType.abilities->reflectFlat[combatTypeToIndex(combat)]; if (reflectFlat != 0) { result += reflectFlat; - uint16_t charges = item->getCharges(); + const uint16_t charges = item->getCharges(); if (useCharges && charges != 0) { g_game().transformItem(item, item->getID(), charges - 1); } @@ -5744,15 +5744,15 @@ void Player::sendUnjustifiedPoints() const { } } - bool isRed = getSkull() == SKULL_RED; + const bool isRed = getSkull() == SKULL_RED; - auto dayMax = ((isRed ? 2 : 1) * g_configManager().getNumber(DAY_KILLS_TO_RED, __FUNCTION__)); - auto weekMax = ((isRed ? 2 : 1) * g_configManager().getNumber(WEEK_KILLS_TO_RED, __FUNCTION__)); - auto monthMax = ((isRed ? 2 : 1) * g_configManager().getNumber(MONTH_KILLS_TO_RED, __FUNCTION__)); + const auto dayMax = ((isRed ? 2 : 1) * g_configManager().getNumber(DAY_KILLS_TO_RED, __FUNCTION__)); + const auto weekMax = ((isRed ? 2 : 1) * g_configManager().getNumber(WEEK_KILLS_TO_RED, __FUNCTION__)); + const auto monthMax = ((isRed ? 2 : 1) * g_configManager().getNumber(MONTH_KILLS_TO_RED, __FUNCTION__)); - uint8_t dayProgress = std::min(std::round(dayKills / dayMax * 100), 100.0); - uint8_t weekProgress = std::min(std::round(weekKills / weekMax * 100), 100.0); - uint8_t monthProgress = std::min(std::round(monthKills / monthMax * 100), 100.0); + const uint8_t dayProgress = std::min(std::round(dayKills / dayMax * 100), 100.0); + const uint8_t weekProgress = std::min(std::round(weekKills / weekMax * 100), 100.0); + const uint8_t monthProgress = std::min(std::round(monthKills / monthMax * 100), 100.0); uint8_t skullDuration = 0; if (skullTicks != 0) { skullDuration = std::floor<uint8_t>(skullTicks / (24 * 60 * 60 * 1000)); @@ -5762,7 +5762,7 @@ void Player::sendUnjustifiedPoints() const { } uint8_t Player::getLastMount() const { - int32_t value = getStorageValue(PSTRG_MOUNTS_CURRENTMOUNT); + const int32_t value = getStorageValue(PSTRG_MOUNTS_CURRENTMOUNT); if (value > 0) { return value; } @@ -5770,7 +5770,7 @@ uint8_t Player::getLastMount() const { } uint8_t Player::getCurrentMount() const { - int32_t value = getStorageValue(PSTRG_MOUNTS_CURRENTMOUNT); + const int32_t value = getStorageValue(PSTRG_MOUNTS_CURRENTMOUNT); if (value > 0) { return value; } @@ -5939,7 +5939,7 @@ bool Player::hasMount(const std::shared_ptr<Mount> &mount) const { const uint8_t tmpMountId = mount->id - 1; - int32_t value = getStorageValue(PSTRG_MOUNTS_RANGE_START + (tmpMountId / 31)); + const int32_t value = getStorageValue(PSTRG_MOUNTS_RANGE_START + (tmpMountId / 31)); if (value == -1) { return false; } @@ -6225,7 +6225,7 @@ uint64_t Player::getMoney() const { continue; } - std::shared_ptr<Container> container = item->getContainer(); + const auto &container = item->getContainer(); if (container) { containers.emplace_back(container); } else { @@ -6236,7 +6236,7 @@ uint64_t Player::getMoney() const { size_t i = 0; while (i < containers.size()) { const auto &container = containers[i++]; - for (const std::shared_ptr<Item> &item : container->getItemList()) { + for (const auto &item : container->getItemList()) { const auto &tmpContainer = item->getContainer(); if (tmpContainer) { containers.emplace_back(tmpContainer); @@ -6359,7 +6359,7 @@ void Player::setImmuneFear() { } bool Player::isImmuneFear() const { - uint64_t timenow = OTSYS_TIME(); + const uint64_t timenow = OTSYS_TIME(); return (m_fearCondition.first == CONDITION_FEARED) && (timenow <= m_fearCondition.second); } @@ -6369,7 +6369,7 @@ uint64_t Player::getItemCustomPrice(uint16_t itemId, bool buyPrice /* = false*/) return it->second; } - std::map<uint16_t, uint64_t> itemMap { { itemId, 1 } }; + const std::map<uint16_t, uint64_t> itemMap { { itemId, 1 } }; return g_game().getItemMarketPrice(itemMap, buyPrice); } @@ -6384,7 +6384,7 @@ uint16_t Player::getFreeBackpackSlots() const { return 0; } - uint16_t counter = std::max<uint16_t>(0, backpack->getFreeSlots()); + const uint16_t counter = std::max<uint16_t>(0, backpack->getFreeSlots()); return counter; } @@ -6470,12 +6470,12 @@ void Player::updateImbuementTrackerStats() const { } bool Player::addItemFromStash(uint16_t itemId, uint32_t itemCount) { - uint32_t stackCount = 100u; + const uint32_t stackCount = 100u; while (itemCount > 0) { - auto addValue = itemCount > stackCount ? stackCount : itemCount; + const auto addValue = itemCount > stackCount ? stackCount : itemCount; itemCount -= addValue; - std::shared_ptr<Item> newItem = Item::CreateItem(itemId, addValue); + const auto &newItem = Item::CreateItem(itemId, addValue); if (!g_game().tryRetrieveStashItems(static_self_cast<Player>(), newItem)) { g_game().internalPlayerAddItem(static_self_cast<Player>(), newItem, true); @@ -6541,8 +6541,8 @@ void Player::stowItem(const std::shared_ptr<Item> &item, uint32_t count, bool al } else if (item->getContainer()) { itemDict = item->getContainer()->getStowableItems(); for (const auto &containerItem : item->getContainer()->getItems(true)) { - uint32_t depotChest = g_configManager().getNumber(DEPOTCHEST, __FUNCTION__); - bool validDepot = depotChest > 0 && depotChest < 21; + const uint32_t depotChest = g_configManager().getNumber(DEPOTCHEST, __FUNCTION__); + const bool validDepot = depotChest > 0 && depotChest < 21; if (g_configManager().getBoolean(STASH_MOVING, __FUNCTION__) && containerItem && !containerItem->isStackable() && validDepot) { g_game().internalMoveItem(containerItem->getParent(), getDepotChest(depotChest, true), INDEX_WHEREEVER, containerItem, containerItem->getItemCount(), nullptr); movedItems++; @@ -6577,7 +6577,7 @@ void Player::openPlayerContainers() { openContainersList.emplace_back(cid, itemContainer); } for (ContainerIterator it = itemContainer->iterator(); it.hasNext(); it.advance()) { - std::shared_ptr<Container> subContainer = (*it)->getContainer(); + const auto &subContainer = (*it)->getContainer(); if (subContainer) { const auto &subcid = (*it)->getAttribute<uint8_t>(ItemAttribute_t::OPENCONTAINER); if (subcid > 0) { @@ -6688,19 +6688,19 @@ void Player::triggerMomentum() { return; } - double_t chance = item->getMomentumChance(); - double_t randomChance = uniform_random(0, 10000) / 100.; + const double_t chance = item->getMomentumChance(); + const double_t randomChance = uniform_random(0, 10000) / 100.; if (getZoneType() != ZONE_PROTECTION && hasCondition(CONDITION_INFIGHT) && ((OTSYS_TIME() / 1000) % 2) == 0 && chance > 0 && randomChance < chance) { bool triggered = false; auto it = conditions.begin(); while (it != conditions.end()) { - auto condItem = *it; - ConditionType_t type = condItem->getType(); - auto maxu16 = std::numeric_limits<uint16_t>::max(); - auto checkSpellId = condItem->getSubId(); + const auto condItem = *it; + const ConditionType_t type = condItem->getType(); + constexpr auto maxu16 = std::numeric_limits<uint16_t>::max(); + const auto checkSpellId = condItem->getSubId(); auto spellId = checkSpellId > maxu16 ? 0u : static_cast<uint16_t>(checkSpellId); - int32_t ticks = condItem->getTicks(); - int32_t newTicks = (ticks <= 2000) ? 0 : ticks - 2000; + const int32_t ticks = condItem->getTicks(); + const int32_t newTicks = (ticks <= 2000) ? 0 : ticks - 2000; triggered = true; if (type == CONDITION_SPELLCOOLDOWN || (type == CONDITION_SPELLGROUPCOOLDOWN && spellId > SPELLGROUP_SUPPORT)) { condItem->setTicks(newTicks); @@ -6719,9 +6719,9 @@ void Player::clearCooldowns() { auto it = conditions.begin(); while (it != conditions.end()) { const auto &condItem = *it; - ConditionType_t type = condItem->getType(); - auto maxu16 = std::numeric_limits<uint16_t>::max(); - auto checkSpellId = condItem->getSubId(); + const ConditionType_t type = condItem->getType(); + constexpr auto maxu16 = std::numeric_limits<uint16_t>::max(); + const auto checkSpellId = condItem->getSubId(); auto spellId = checkSpellId > maxu16 ? 0u : static_cast<uint16_t>(checkSpellId); if (type == CONDITION_SPELLCOOLDOWN || type == CONDITION_SPELLGROUPCOOLDOWN) { condItem->setTicks(0); @@ -6741,11 +6741,11 @@ void Player::triggerTranscendance() { return; } - double_t chance = item->getTranscendenceChance(); - double_t randomChance = uniform_random(0, 10000) / 100.; + const double_t chance = item->getTranscendenceChance(); + const double_t randomChance = uniform_random(0, 10000) / 100.; if (getZoneType() != ZONE_PROTECTION && checkLastAggressiveActionWithin(2000) && ((OTSYS_TIME() / 1000) % 2) == 0 && chance > 0 && randomChance < chance) { - int64_t duration = g_configManager().getNumber(TRANSCENDANCE_AVATAR_DURATION, __FUNCTION__); - auto outfitCondition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)->static_self_cast<ConditionOutfit>(); + const int64_t duration = g_configManager().getNumber(TRANSCENDANCE_AVATAR_DURATION, __FUNCTION__); + const auto outfitCondition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)->static_self_cast<ConditionOutfit>(); Outfit_t outfit; outfit.lookType = getVocation()->getAvatarLookType(); outfitCondition->setOutfit(outfit); @@ -7499,8 +7499,8 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { ReturnValue returnValue = RETURNVALUE_NOERROR; if (actionType == ForgeAction_t::DUSTTOSLIVERS) { - auto dusts = getForgeDusts(); - auto cost = static_cast<uint16_t>(g_configManager().getNumber(FORGE_COST_ONE_SLIVER, __FUNCTION__) * g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); + const auto dusts = getForgeDusts(); + const auto cost = static_cast<uint16_t>(g_configManager().getNumber(FORGE_COST_ONE_SLIVER, __FUNCTION__) * g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); if (cost > dusts) { g_logger().error("[{}] Not enough dust", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7548,15 +7548,15 @@ void Player::forgeResourceConversion(ForgeAction_t actionType) { history.cost = cost; history.gained = 1; } else { - auto dustLevel = getForgeDustLevel(); + const auto dustLevel = getForgeDustLevel(); if (dustLevel >= g_configManager().getNumber(FORGE_MAX_DUST, __FUNCTION__)) { g_logger().error("[{}] Maximum level reached", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto upgradeCost = dustLevel - 75; - if (auto dusts = getForgeDusts(); + const auto upgradeCost = dustLevel - 75; + if (const auto dusts = getForgeDusts(); upgradeCost > dusts) { g_logger().error("[{}] Not enough dust", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7930,8 +7930,8 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, const std::shared } uint16_t stage = 0; - auto chance = static_cast<uint16_t>(normal_random(1, 10000)); - auto critChance = g_configManager().getNumber(HAZARD_CRITICAL_CHANCE, __FUNCTION__); + const auto chance = static_cast<uint16_t>(normal_random(1, 10000)); + const auto critChance = g_configManager().getNumber(HAZARD_CRITICAL_CHANCE, __FUNCTION__); // Critical chance if (monster->getHazardSystemCrit() && (lastHazardSystemCriticalHit + g_configManager().getNumber(HAZARD_CRITICAL_INTERVAL, __FUNCTION__)) <= OTSYS_TIME() && chance <= critChance && !damage.critical) { damage.critical = true; @@ -7992,7 +7992,7 @@ void Player::parseAttackDealtHazardSystem(CombatDamage &damage, const std::share uint16_t stage; if (monster->getHazardSystemDodge()) { stage = points * g_configManager().getNumber(HAZARD_DODGE_MULTIPLIER, __FUNCTION__); - auto chance = static_cast<uint16_t>(normal_random(1, 10000)); + const auto chance = static_cast<uint16_t>(normal_random(1, 10000)); if (chance <= stage) { damage.primary.value = 0; damage.secondary.value = 0; @@ -8154,7 +8154,7 @@ uint16_t Player::getDodgeChance() const { void Player::checkAndShowBlessingMessage() { auto adventurerBlessingLevel = g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL, __FUNCTION__); - auto willNotLoseBless = getLevel() < adventurerBlessingLevel && getVocationId() > VOCATION_NONE; + const auto willNotLoseBless = getLevel() < adventurerBlessingLevel && getVocationId() > VOCATION_NONE; std::string bless = getBlessingsName(); std::ostringstream blessOutput; diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 4c448da90e0..866f639494f 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -206,13 +206,13 @@ class Player final : public Creature, public Cylinder, public Bankable { } } void addBestiaryKillCount(uint16_t raceid, uint32_t amount) { - uint32_t oldCount = getBestiaryKillCount(raceid); - uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; + const uint32_t oldCount = getBestiaryKillCount(raceid); + const uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; addStorageValue(key, static_cast<int32_t>(oldCount + amount), true); } uint32_t getBestiaryKillCount(uint16_t raceid) const { - uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; - auto value = getStorageValue(key); + const uint32_t key = STORAGEVALUE_BESTIARYKILLCOUNT + raceid; + const auto value = getStorageValue(key); return value > 0 ? static_cast<uint32_t>(value) : 0; } @@ -391,7 +391,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void setPerfectShotDamage(uint8_t range, int32_t damage) { int32_t actualDamage = getPerfectShotDamage(range); - bool aboveZero = (actualDamage != 0); + const bool aboveZero = (actualDamage != 0); actualDamage += damage; if (actualDamage == 0 && aboveZero) { perfectShot.erase(range); @@ -489,7 +489,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return 0; } } - auto amount = kv()->scoped("summary")->scoped("blessings")->scoped(fmt::format("{}", index))->get("amount"); + const auto amount = kv()->scoped("summary")->scoped("blessings")->scoped(fmt::format("{}", index))->get("amount"); return amount ? static_cast<uint8_t>(amount->getNumber()) : 0; } std::string getBlessingsName() const; @@ -714,7 +714,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool removeItemCountById(uint16_t itemId, uint32_t itemAmount, bool removeFromStash = true); void addItemOnStash(uint16_t itemId, uint32_t amount) { - auto it = stashItems.find(itemId); + const auto it = stashItems.find(itemId); if (it != stashItems.end()) { stashItems[itemId] += amount; return; @@ -723,14 +723,14 @@ class Player final : public Creature, public Cylinder, public Bankable { stashItems[itemId] = amount; } uint32_t getStashItemCount(uint16_t itemId) const { - auto it = stashItems.find(itemId); + const auto it = stashItems.find(itemId); if (it != stashItems.end()) { return it->second; } return 0; } bool withdrawItem(uint16_t itemId, uint32_t amount) { - auto it = stashItems.find(itemId); + const auto it = stashItems.find(itemId); if (it != stashItems.end()) { if (it->second > amount) { stashItems[itemId] -= amount; @@ -750,7 +750,8 @@ class Player final : public Creature, public Cylinder, public Bankable { uint32_t getBaseCapacity() const { if (hasFlag(PlayerFlags_t::CannotPickupItem)) { return 0; - } else if (hasFlag(PlayerFlags_t::HasInfiniteCapacity)) { + } + if (hasFlag(PlayerFlags_t::HasInfiniteCapacity)) { return std::numeric_limits<uint32_t>::max(); } return capacity; @@ -936,7 +937,7 @@ class Player final : public Creature, public Cylinder, public Bankable { if (!lastConditionTime.contains(static_cast<uint8_t>(type))) { return false; } - auto last = lastConditionTime.at(static_cast<uint8_t>(type)); + const auto last = lastConditionTime.at(static_cast<uint8_t>(type)); return last > 0 && ((OTSYS_TIME() - last) < interval); } @@ -975,7 +976,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void getShieldAndWeapon(std::shared_ptr<Item> &shield, std::shared_ptr<Item> &weapon) const; void drainHealth(const std::shared_ptr<Creature> &attacker, int32_t damage) override; - void drainMana(std::shared_ptr<Creature> attacker, int32_t manaLoss) override; + void drainMana(const std::shared_ptr<Creature> &attacker, int32_t manaLoss) override; void addManaSpent(uint64_t amount); void addSkillAdvance(skills_t skill, uint64_t count); @@ -1004,7 +1005,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void onGainSharedExperience(uint64_t gainExp, const std::shared_ptr<Creature> &target); void onAttackedCreatureBlockHit(const BlockType_t &blockType) override; void onBlockHit() override; - void onTakeDamage(std::shared_ptr<Creature> attacker, int32_t damage) override; + void onTakeDamage(const std::shared_ptr<Creature> &attacker, int32_t damage) override; void onChangeZone(ZoneType_t zone) override; void onAttackedCreatureChangeZone(ZoneType_t zone) override; void onIdleStatus() override; @@ -1013,7 +1014,7 @@ class Player final : public Creature, public Cylinder, public Bankable { LightInfo getCreatureLight() const override; Skulls_t getSkull() const override; - Skulls_t getSkullClient(std::shared_ptr<Creature> creature) override; + Skulls_t getSkullClient(const std::shared_ptr<Creature> &creature) override; int64_t getSkullTicks() const { return skullTicks; } @@ -1062,7 +1063,7 @@ class Player final : public Creature, public Cylinder, public Bankable { // send methods void sendAddTileItem(const std::shared_ptr<Tile> &itemTile, const Position &pos, const std::shared_ptr<Item> &item) { if (client) { - int32_t stackpos = itemTile->getStackposOfItem(static_self_cast<Player>(), item); + const int32_t stackpos = itemTile->getStackposOfItem(static_self_cast<Player>(), item); if (stackpos != -1) { client->sendAddTileItem(pos, stackpos, item); } @@ -1070,7 +1071,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } void sendUpdateTileItem(const std::shared_ptr<Tile> &updateTile, const Position &pos, const std::shared_ptr<Item> &item) { if (client) { - int32_t stackpos = updateTile->getStackposOfItem(static_self_cast<Player>(), item); + const int32_t stackpos = updateTile->getStackposOfItem(static_self_cast<Player>(), item); if (stackpos != -1) { client->sendUpdateTileItem(pos, stackpos, item); } @@ -1107,7 +1108,7 @@ class Player final : public Creature, public Cylinder, public Bankable { return; } - auto tile = creature->getTile(); + const auto tile = creature->getTile(); if (!tile) { return; } @@ -1126,13 +1127,13 @@ class Player final : public Creature, public Cylinder, public Bankable { return; } - auto tile = creature->getTile(); + const auto tile = creature->getTile(); if (!tile) { return; } if (client && canSeeCreature(creature)) { - int32_t stackpos = tile->getStackposOfCreature(static_self_cast<Player>(), creature); + const int32_t stackpos = tile->getStackposOfCreature(static_self_cast<Player>(), creature); if (stackpos != -1) { client->sendCreatureTurn(creature, stackpos); } @@ -1178,11 +1179,11 @@ class Player final : public Creature, public Cylinder, public Bankable { } else if (canSeeInvisibility()) { client->sendCreatureOutfit(creature, creature->getCurrentOutfit()); } else { - auto tile = creature->getTile(); + const auto tile = creature->getTile(); if (!tile) { return; } - int32_t stackpos = tile->getStackposOfCreature(static_self_cast<Player>(), creature); + const int32_t stackpos = tile->getStackposOfCreature(static_self_cast<Player>(), creature); if (stackpos == -1) { return; } @@ -1777,7 +1778,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void setWriteItem(const std::shared_ptr<Item> &item, uint16_t maxWriteLen = 0); std::shared_ptr<House> getEditHouse(uint32_t &windowTextId, uint32_t &listId); - void setEditHouse(std::shared_ptr<House> house, uint32_t listId = 0); + void setEditHouse(const std::shared_ptr<House> &house, uint32_t listId = 0); void learnInstantSpell(const std::string &spellName); void forgetInstantSpell(const std::string &spellName); @@ -1961,7 +1962,7 @@ class Player final : public Creature, public Cylinder, public Bankable { cleanseCondition.second = OTSYS_TIME() + 10000; } bool isImmuneCleanse(ConditionType_t conditiontype) const { - uint64_t timenow = OTSYS_TIME(); + const uint64_t timenow = OTSYS_TIME(); if ((cleanseCondition.first == conditiontype) && (timenow <= cleanseCondition.second)) { return true; @@ -2209,10 +2210,10 @@ class Player final : public Creature, public Cylinder, public Bankable { for (const std::unique_ptr<PreySlot> &slot : preys) { if (slot) { if (slot->isOccupied()) { - rt.push_back(slot->selectedRaceId); + rt.emplace_back(slot->selectedRaceId); } for (uint16_t raceId : slot->raceIdList) { - rt.push_back(raceId); + rt.emplace_back(raceId); } } } @@ -2459,7 +2460,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } void setForgeHistory(const ForgeHistory &history) { - forgeHistoryVector.push_back(history); + forgeHistoryVector.emplace_back(history); } void registerForgeHistoryDescription(ForgeHistory history); @@ -2559,11 +2560,11 @@ class Player final : public Creature, public Cylinder, public Bankable { return activeConcoctions; } bool isConcoctionActive(Concoction_t concotion) const { - auto itemId = static_cast<uint16_t>(concotion); + const auto itemId = static_cast<uint16_t>(concotion); if (!activeConcoctions.contains(itemId)) { return false; } - auto timeLeft = activeConcoctions.at(itemId); + const auto timeLeft = activeConcoctions.at(itemId); return timeLeft > 0; } @@ -2575,11 +2576,12 @@ class Player final : public Creature, public Cylinder, public Bankable { return false; } - auto featureKV = kv()->scoped("features")->get("autoloot"); - auto value = featureKV.has_value() ? featureKV->getNumber() : 0; + const auto featureKV = kv()->scoped("features")->get("autoloot"); + const auto value = featureKV.has_value() ? featureKV->getNumber() : 0; if (value == 2) { return true; - } else if (value == 1) { + } + if (value == 1) { return !isBoss; } return false; @@ -2685,20 +2687,20 @@ class Player final : public Creature, public Cylinder, public Bankable { void setNextActionPushTask(const std::shared_ptr<Task> &task); void setNextPotionActionTask(const std::shared_ptr<Task> &task); - void death(std::shared_ptr<Creature> lastHitCreature) override; + void death(const std::shared_ptr<Creature> &lastHitCreature) override; bool spawn(); void despawn(); bool dropCorpse(const std::shared_ptr<Creature> &lastHitCreature, const std::shared_ptr<Creature> &mostDamageCreature, bool lastHitUnjustified, bool mostDamageUnjustified) override; std::shared_ptr<Item> getCorpse(const std::shared_ptr<Creature> &lastHitCreature, const std::shared_ptr<Creature> &mostDamageCreature) override; // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing>) override { } - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) override; @@ -2727,7 +2729,7 @@ class Player final : public Creature, public Cylinder, public Bankable { void addBestiaryKill(const std::shared_ptr<MonsterType> &mType); void addBosstiaryKill(const std::shared_ptr<MonsterType> &mType); - phmap::flat_hash_set<uint32_t> attackedSet; + phmap::flat_hash_set<uint32_t> attackedSet {}; std::map<uint8_t, OpenContainer> openContainers; std::map<uint32_t, std::shared_ptr<DepotLocker>> depotLockerMap; @@ -2984,8 +2986,8 @@ class Player final : public Creature, public Cylinder, public Bankable { uint32_t getAttackSpeed() const { if (onFistAttackSpeed) { - uint32_t baseAttackSpeed = vocation->getAttackSpeed(); - uint32_t skillLevel = getSkillLevel(SKILL_FIST); + const uint32_t baseAttackSpeed = vocation->getAttackSpeed(); + const uint32_t skillLevel = getSkillLevel(SKILL_FIST); uint32_t attackSpeed = baseAttackSpeed - (skillLevel * g_configManager().getNumber(MULTIPLIER_ATTACKONFIST, __FUNCTION__)); if (attackSpeed < MAX_ATTACK_SPEED) { diff --git a/src/creatures/players/storages/storages.cpp b/src/creatures/players/storages/storages.cpp index 886db3e61e1..9e2673e62cd 100644 --- a/src/creatures/players/storages/storages.cpp +++ b/src/creatures/players/storages/storages.cpp @@ -36,8 +36,8 @@ bool Storages::loadFromXML() { uint32_t start = range.attribute("start").as_uint(); uint32_t end = range.attribute("end").as_uint(); - for (const auto &existingRange : ranges) { - if ((start >= existingRange.first && start <= existingRange.second) || (end >= existingRange.first && end <= existingRange.second)) { + for (const auto &[fst, snd] : ranges) { + if ((start >= fst && start <= snd) || (end >= fst && end <= snd)) { g_logger().warn("[{}] Storage range from {} to {} conflicts with a previously defined range", __func__, start, end); continue; } diff --git a/src/creatures/players/vip/player_vip.cpp b/src/creatures/players/vip/player_vip.cpp index 25fbfdba0e4..e7d14f030f2 100644 --- a/src/creatures/players/vip/player_vip.cpp +++ b/src/creatures/players/vip/player_vip.cpp @@ -25,7 +25,8 @@ PlayerVIP::PlayerVIP(Player &player) : size_t PlayerVIP::getMaxEntries() const { if (m_player.group && m_player.group->maxVipEntries != 0) { return m_player.group->maxVipEntries; - } else if (m_player.isPremium()) { + } + if (m_player.isPremium()) { return 100; } return 20; @@ -102,7 +103,7 @@ bool PlayerVIP::addInternal(uint32_t vipGuid) { } bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t icon, bool notify, const std::vector<uint8_t> &groupsId) const { - const auto it = vipGuids.find(vipGuid); + const auto &it = vipGuids.find(vipGuid); if (it == vipGuids.end()) { return false; // player is not in VIP } @@ -125,7 +126,7 @@ bool PlayerVIP::edit(uint32_t vipGuid, const std::string &description, uint32_t } std::shared_ptr<VIPGroup> PlayerVIP::getGroupByID(uint8_t groupId) const { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const auto &vipGroup) { + const auto &it = std::ranges::find_if(vipGroups, [groupId](const auto &vipGroup) { return vipGroup->id == groupId; }); @@ -134,7 +135,7 @@ std::shared_ptr<VIPGroup> PlayerVIP::getGroupByID(uint8_t groupId) const { std::shared_ptr<VIPGroup> PlayerVIP::getGroupByName(const std::string &name) const { const auto groupName = name.c_str(); - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupName](const auto &vipGroup) { + const auto &it = std::ranges::find_if(vipGroups, [groupName](const auto &vipGroup) { return strcmp(groupName, vipGroup->name.c_str()) == 0; }); @@ -157,7 +158,7 @@ void PlayerVIP::addGroupInternal(uint8_t groupId, const std::string &name, bool } void PlayerVIP::removeGroup(uint8_t groupId) { - auto it = std::find_if(vipGroups.begin(), vipGroups.end(), [groupId](const auto &vipGroup) { + const auto &it = std::ranges::find_if(vipGroups, [groupId](const auto &vipGroup) { return vipGroup->id == groupId; }); @@ -188,7 +189,7 @@ void PlayerVIP::addGroup(const std::string &name, bool customizable /*= true */) return; } - std::shared_ptr<VIPGroup> vipGroup = std::make_shared<VIPGroup>(freeId, name, customizable); + auto vipGroup = std::make_shared<VIPGroup>(freeId, name, customizable); vipGroups.emplace_back(vipGroup); if (m_player.account) { @@ -200,7 +201,7 @@ void PlayerVIP::addGroup(const std::string &name, bool customizable /*= true */) } } -void PlayerVIP::editGroup(uint8_t groupId, const std::string &newName, bool customizable /*= true*/) { +void PlayerVIP::editGroup(uint8_t groupId, const std::string &newName, bool customizable /*= true*/) const { if (getGroupByName(newName) != nullptr) { m_player.sendCancelMessage("A group with this name already exists. Please choose another name."); return; @@ -229,7 +230,7 @@ uint8_t PlayerVIP::getFreeId() const { return 0; } -std::vector<uint8_t> PlayerVIP::getGroupsIdGuidBelongs(uint32_t guid) { +std::vector<uint8_t> PlayerVIP::getGroupsIdGuidBelongs(uint32_t guid) const { std::vector<uint8_t> guidBelongs; for (const auto &vipGroup : vipGroups) { if (vipGroup->vipGroupGuids.contains(guid)) { diff --git a/src/creatures/players/vip/player_vip.hpp b/src/creatures/players/vip/player_vip.hpp index 09a20dd1788..7ceb47cab68 100644 --- a/src/creatures/players/vip/player_vip.hpp +++ b/src/creatures/players/vip/player_vip.hpp @@ -15,7 +15,8 @@ class Player; -struct VIPGroup { +class VIPGroup { +public: uint8_t id = 0; std::string name; bool customizable = false; @@ -25,8 +26,8 @@ struct VIPGroup { VIPGroup(uint8_t id, std::string name, bool customizable) : id(id), name(std::move(name)), customizable(customizable) { } }; -class PlayerVIP { +class PlayerVIP { public: explicit PlayerVIP(Player &player); @@ -56,12 +57,12 @@ class PlayerVIP { void addGroupInternal(uint8_t groupId, const std::string &name, bool customizable); void removeGroup(uint8_t groupId); void addGroup(const std::string &name, bool customizable = true); - void editGroup(uint8_t groupId, const std::string &newName, bool customizable = true); + void editGroup(uint8_t groupId, const std::string &newName, bool customizable = true) const; void addGuidToGroupInternal(uint8_t groupId, uint32_t guid) const; uint8_t getFreeId() const; - std::vector<uint8_t> getGroupsIdGuidBelongs(uint32_t guid); + std::vector<uint8_t> getGroupsIdGuidBelongs(uint32_t guid) const; [[nodiscard]] const std::vector<std::shared_ptr<VIPGroup>> &getGroups() const { return vipGroups; diff --git a/src/creatures/players/vocations/vocation.cpp b/src/creatures/players/vocations/vocation.cpp index 42a7154e301..316c9e66023 100644 --- a/src/creatures/players/vocations/vocation.cpp +++ b/src/creatures/players/vocations/vocation.cpp @@ -25,8 +25,8 @@ bool Vocations::reload() { bool Vocations::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/vocations.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/vocations.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -34,15 +34,15 @@ bool Vocations::loadFromXml() { for (const auto &vocationNode : doc.child("vocations").children()) { pugi::xml_attribute attr; - if (!(attr = vocationNode.attribute("id"))) { + if (!((attr = vocationNode.attribute("id")))) { g_logger().warn("[{}] - Missing vocation id", __FUNCTION__); continue; } auto id = pugi::cast<uint16_t>(attr.value()); - auto res = vocationsMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(std::make_shared<Vocation>(id))); - auto voc = res.first->second; + auto [fst, snd] = vocationsMap.emplace(std::piecewise_construct, std::forward_as_tuple(id), std::forward_as_tuple(std::make_shared<Vocation>(id))); + const auto voc = fst->second; if ((attr = vocationNode.attribute("name"))) { voc->name = attr.as_string(); @@ -190,7 +190,7 @@ bool Vocations::loadFromXml() { pugi::xml_attribute qualityAttr = childNode.attribute("quality"); pugi::xml_attribute nameAttr = childNode.attribute("name"); auto quality = pugi::cast<uint8_t>(qualityAttr.value()); - auto name = nameAttr.as_string(); + const auto name = nameAttr.as_string(); voc->wheelGems[static_cast<WheelGemQuality_t>(quality)] = name; } } @@ -199,7 +199,7 @@ bool Vocations::loadFromXml() { } std::shared_ptr<Vocation> Vocations::getVocation(uint16_t id) { - auto it = vocationsMap.find(id); + const auto &it = vocationsMap.find(id); if (it == vocationsMap.end()) { g_logger().warn("[Vocations::getVocation] - " "Vocation {} not found", @@ -210,32 +210,32 @@ std::shared_ptr<Vocation> Vocations::getVocation(uint16_t id) { } uint16_t Vocations::getVocationId(const std::string &name) const { - for (const auto &it : vocationsMap) { - if (strcasecmp(it.second->name.c_str(), name.c_str()) == 0) { - return it.first; + for (const auto &[fst, snd] : vocationsMap) { + if (strcasecmp(snd->name.c_str(), name.c_str()) == 0) { + return fst; } } return -1; } uint16_t Vocations::getPromotedVocation(uint16_t vocationId) const { - for (const auto &it : vocationsMap) { - if (it.second->fromVocation == vocationId && it.first != vocationId) { - return it.first; + for (const auto &[fst, snd] : vocationsMap) { + if (snd->fromVocation == vocationId && fst != vocationId) { + return fst; } } return VOCATION_NONE; } uint32_t Vocation::skillBase[SKILL_LAST + 1] = { 50, 50, 50, 50, 30, 100, 20 }; -const uint16_t minSkillLevel = 10; +constexpr uint16_t minSkillLevel = 10; absl::uint128 Vocation::getTotalSkillTries(uint8_t skill, uint16_t level) { if (skill > SKILL_LAST) { return 0; } - auto it = cacheSkillTotal[skill].find(level); + const auto &it = cacheSkillTotal[skill].find(level); if (it != cacheSkillTotal[skill].end()) { return it->second; } @@ -253,12 +253,12 @@ uint64_t Vocation::getReqSkillTries(uint8_t skill, uint16_t level) { return 0; } - auto it = cacheSkill[skill].find(level); + const auto &it = cacheSkill[skill].find(level); if (it != cacheSkill[skill].end()) { return it->second; } - auto tries = static_cast<uint64_t>(skillBase[skill] * std::pow(static_cast<double>(skillMultipliers[skill]), level - (minSkillLevel + 1))); + const auto tries = static_cast<uint64_t>(skillBase[skill] * std::pow(static_cast<double>(skillMultipliers[skill]), level - (minSkillLevel + 1))); cacheSkill[skill][level] = tries; return tries; } @@ -267,7 +267,7 @@ absl::uint128 Vocation::getTotalMana(uint32_t magLevel) { if (magLevel == 0) { return 0; } - auto it = cacheManaTotal.find(magLevel); + const auto &it = cacheManaTotal.find(magLevel); if (it != cacheManaTotal.end()) { return it->second; } @@ -282,12 +282,12 @@ uint64_t Vocation::getReqMana(uint32_t magLevel) { if (magLevel == 0) { return 0; } - auto it = cacheMana.find(magLevel); + const auto &it = cacheMana.find(magLevel); if (it != cacheMana.end()) { return it->second; } - uint64_t reqMana = std::floor<uint64_t>(1600 * std::pow<double>(manaMultiplier, static_cast<int32_t>(magLevel) - 1)); + const uint64_t reqMana = std::floor<uint64_t>(1600 * std::pow<double>(manaMultiplier, static_cast<int32_t>(magLevel) - 1)); cacheMana[magLevel] = reqMana; return reqMana; } @@ -296,7 +296,7 @@ std::vector<WheelGemSupremeModifier_t> Vocation::getSupremeGemModifiers() { if (!m_supremeGemModifiers.empty()) { return m_supremeGemModifiers; } - auto baseVocation = g_vocations().getVocation(getBaseId()); + const auto baseVocation = g_vocations().getVocation(getBaseId()); auto vocationName = asLowerCaseString(baseVocation->getVocName()); auto allModifiers = magic_enum::enum_entries<WheelGemSupremeModifier_t>(); g_logger().debug("Loading supreme gem modifiers for vocation: {}", vocationName); @@ -305,7 +305,7 @@ std::vector<WheelGemSupremeModifier_t> Vocation::getSupremeGemModifiers() { toLowerCaseString(targetVocation); g_logger().debug("Checking supreme gem modifier: {}, targetVocation: {}", modifierName, targetVocation); if (targetVocation == "general" || targetVocation.find(vocationName) != std::string::npos) { - m_supremeGemModifiers.push_back(value); + m_supremeGemModifiers.emplace_back(value); } } return m_supremeGemModifiers; diff --git a/src/creatures/players/wheel/player_wheel.cpp b/src/creatures/players/wheel/player_wheel.cpp index c475ece182c..da62b744a4b 100644 --- a/src/creatures/players/wheel/player_wheel.cpp +++ b/src/creatures/players/wheel/player_wheel.cpp @@ -10,13 +10,10 @@ #include "pch.hpp" #include "creatures/players/wheel/player_wheel.hpp" - #include "io/io_wheel.hpp" - #include "game/game.hpp" #include "creatures/players/player.hpp" #include "creatures/combat/spells.hpp" - #include "config/configmanager.hpp" const static std::vector<WheelGemBasicModifier_t> wheelGemBasicSlot1Allowed = { @@ -145,12 +142,12 @@ namespace { PlayerWheel::PlayerWheel(Player &initPlayer) : m_player(initPlayer) { - auto pointsPerLevel = (uint16_t)g_configManager().getNumber(WHEEL_POINTS_PER_LEVEL, __FUNCTION__); + const auto pointsPerLevel = static_cast<uint16_t>(g_configManager().getNumber(WHEEL_POINTS_PER_LEVEL, __FUNCTION__)); m_pointsPerLevel = pointsPerLevel > 0 ? pointsPerLevel : 1; } bool PlayerWheel::canPlayerSelectPointOnSlot(WheelSlots_t slot, bool recursive) const { - auto playerPoints = getWheelPoints(); + const auto playerPoints = getWheelPoints(); // Green quadrant if (slot == WheelSlots_t::SLOT_GREEN_200) { if (playerPoints < 375u) { @@ -684,19 +681,22 @@ uint16_t PlayerWheel::getUnusedPoints() const { } bool PlayerWheel::getSpellAdditionalArea(const std::string &spellName) const { - auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); + const auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); if (stage == 0) { return false; } - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { return checkSpellArea(g_game().getIOWheel()->getWheelBonusData().spells.knight, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { return checkSpellArea(g_game().getIOWheel()->getWheelBonusData().spells.paladin, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { return checkSpellArea(g_game().getIOWheel()->getWheelBonusData().spells.druid, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { return checkSpellArea(g_game().getIOWheel()->getWheelBonusData().spells.sorcerer, spellName, stage); } @@ -704,19 +704,22 @@ bool PlayerWheel::getSpellAdditionalArea(const std::string &spellName) const { } int PlayerWheel::getSpellAdditionalTarget(const std::string &spellName) const { - auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); + const auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); if (stage == 0) { return 0; } - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { return checkSpellAdditionalTarget(g_game().getIOWheel()->getWheelBonusData().spells.knight, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { return checkSpellAdditionalTarget(g_game().getIOWheel()->getWheelBonusData().spells.paladin, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { return checkSpellAdditionalTarget(g_game().getIOWheel()->getWheelBonusData().spells.druid, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { return checkSpellAdditionalTarget(g_game().getIOWheel()->getWheelBonusData().spells.sorcerer, spellName, stage); } @@ -724,19 +727,22 @@ int PlayerWheel::getSpellAdditionalTarget(const std::string &spellName) const { } int PlayerWheel::getSpellAdditionalDuration(const std::string &spellName) const { - auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); + const auto stage = static_cast<uint8_t>(getSpellUpgrade(spellName)); if (stage == 0) { return 0; } - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { return checkSpellAdditionalDuration(g_game().getIOWheel()->getWheelBonusData().spells.knight, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_PALADIN_CIP) { return checkSpellAdditionalDuration(g_game().getIOWheel()->getWheelBonusData().spells.paladin, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { return checkSpellAdditionalDuration(g_game().getIOWheel()->getWheelBonusData().spells.druid, spellName, stage); - } else if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { + } + if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { return checkSpellAdditionalDuration(g_game().getIOWheel()->getWheelBonusData().spells.sorcerer, spellName, stage); } @@ -746,15 +752,15 @@ int PlayerWheel::getSpellAdditionalDuration(const std::string &spellName) const void PlayerWheel::addPromotionScrolls(NetworkMessage &msg) const { std::vector<uint16_t> unlockedScrolls; - for (const auto &scroll : WheelOfDestinyPromotionScrolls) { + for (const auto &[itemId, name, extraPoints] : WheelOfDestinyPromotionScrolls) { const auto &scrollKv = m_player.kv()->scoped("wheel-of-destiny")->scoped("scrolls"); if (!scrollKv) { continue; } - auto scrollOpt = scrollKv->get(scroll.name); + const auto scrollOpt = scrollKv->get(name); if (scrollOpt && scrollOpt->get<bool>()) { - unlockedScrolls.push_back(scroll.itemId); + unlockedScrolls.emplace_back(itemId); } } @@ -770,24 +776,24 @@ std::shared_ptr<KV> PlayerWheel::gemsKV() const { std::vector<PlayerWheelGem> PlayerWheel::getRevealedGems() const { std::vector<PlayerWheelGem> unlockedGems; - auto unlockedGemUUIDs = gemsKV()->scoped("revealed")->keys(); + const auto unlockedGemUUIDs = gemsKV()->scoped("revealed")->keys(); if (unlockedGemUUIDs.empty()) { return unlockedGems; } std::vector<std::string> sortedUnlockedGemGUIDs; for (const auto &uuid : unlockedGemUUIDs) { - sortedUnlockedGemGUIDs.push_back(uuid); + sortedUnlockedGemGUIDs.emplace_back(uuid); } - std::sort(sortedUnlockedGemGUIDs.begin(), sortedUnlockedGemGUIDs.end(), [](const std::string &a, const std::string &b) { + std::ranges::sort(sortedUnlockedGemGUIDs, [](const std::string &a, const std::string &b) { return std::stoull(a) < std::stoull(b); }); for (const auto &uuid : sortedUnlockedGemGUIDs) { - auto gem = PlayerWheelGem::load(gemsKV(), uuid); + const auto &gem = PlayerWheelGem::load(gemsKV(), uuid); if (gem.uuid.empty()) { continue; } - unlockedGems.push_back(gem); + unlockedGems.emplace_back(gem); } return unlockedGems; } @@ -809,7 +815,7 @@ std::vector<PlayerWheelGem> PlayerWheel::getActiveGems() const { if (gem.uuid.empty()) { continue; } - activeGems.push_back(gem); + activeGems.emplace_back(gem); } return activeGems; } @@ -850,7 +856,7 @@ uint64_t PlayerWheel::getGemRevealCost(WheelGemQuality_t quality) { return static_cast<uint64_t>(g_configManager().getNumber(key, __FUNCTION__)); } -void PlayerWheel::revealGem(WheelGemQuality_t quality) { +void PlayerWheel::revealGem(WheelGemQuality_t quality) const { uint16_t gemId = m_player.getVocation()->getWheelGemId(quality); if (gemId == 0) { g_logger().error("[{}] Failed to get gem id for quality {} and vocation {}", __FUNCTION__, fmt::underlying(quality), m_player.getVocation()->getVocName()); @@ -869,7 +875,7 @@ void PlayerWheel::revealGem(WheelGemQuality_t quality) { g_logger().error("[{}] Failed to remove gem with id {} from player with name {}", __FUNCTION__, gemId, m_player.getName()); return; } - auto supremeModifiers = m_player.getVocation()->getSupremeGemModifiers(); + const auto supremeModifiers = m_player.getVocation()->getSupremeGemModifiers(); PlayerWheelGem gem; gem.uuid = KV::generateUUID(); gem.locked = false; @@ -908,7 +914,7 @@ PlayerWheelGem PlayerWheel::getGem(const std::string &uuid) const { } uint16_t PlayerWheel::getGemIndex(const std::string &uuid) const { - auto gems = getRevealedGems(); + const auto gems = getRevealedGems(); for (uint16_t i = 0; i < gems.size(); ++i) { if (gems[i].uuid == uuid) { return i; @@ -918,8 +924,8 @@ uint16_t PlayerWheel::getGemIndex(const std::string &uuid) const { return 0xFF; } -void PlayerWheel::destroyGem(uint16_t index) { - auto gem = getGem(index); +void PlayerWheel::destroyGem(uint16_t index) const { + const auto gem = getGem(index); if (gem.locked) { g_logger().error("[{}] Player {} trying to destroy locked gem with index {}", __FUNCTION__, m_player.getName(), index); return; @@ -928,7 +934,7 @@ void PlayerWheel::destroyGem(uint16_t index) { sendOpenWheelWindow(m_player.getID()); } -void PlayerWheel::switchGemDomain(uint16_t index) { +void PlayerWheel::switchGemDomain(uint16_t index) const { auto gem = getGem(index); if (gem.locked) { g_logger().error("[{}] Player {} trying to destroy locked gem with index {}", __FUNCTION__, m_player.getName(), index); @@ -946,15 +952,15 @@ void PlayerWheel::switchGemDomain(uint16_t index) { sendOpenWheelWindow(m_player.getID()); } -void PlayerWheel::toggleGemLock(uint16_t index) { +void PlayerWheel::toggleGemLock(uint16_t index) const { auto gem = getGem(index); gem.locked = !gem.locked; gem.save(gemsKV()); sendOpenWheelWindow(m_player.getID()); } -void PlayerWheel::setActiveGem(WheelGemAffinity_t affinity, uint16_t index) { - auto gem = getGem(index); +void PlayerWheel::setActiveGem(WheelGemAffinity_t affinity, uint16_t index) const { + const auto gem = getGem(index); if (gem.uuid.empty()) { g_logger().error("[{}] Failed to load gem with index {}", __FUNCTION__, index); return; @@ -963,17 +969,17 @@ void PlayerWheel::setActiveGem(WheelGemAffinity_t affinity, uint16_t index) { g_logger().error("[{}] Gem with index {} has affinity {} but trying to set it to {}", __FUNCTION__, index, fmt::underlying(gem.affinity), fmt::underlying(affinity)); return; } - std::string key(magic_enum::enum_name(affinity)); + const std::string key(magic_enum::enum_name(affinity)); gemsKV()->scoped("active")->set(key, gem.uuid); } -void PlayerWheel::removeActiveGem(WheelGemAffinity_t affinity) { - std::string key(magic_enum::enum_name(affinity)); +void PlayerWheel::removeActiveGem(WheelGemAffinity_t affinity) const { + const std::string key(magic_enum::enum_name(affinity)); gemsKV()->scoped("active")->remove(key); } void PlayerWheel::addGems(NetworkMessage &msg) const { - auto activeGems = getActiveGems(); + const auto activeGems = getActiveGems(); msg.addByte(activeGems.size()); g_logger().debug("[{}] Player {} has {} active gems", __FUNCTION__, m_player.getName(), activeGems.size()); for (const auto &gem : activeGems) { @@ -982,7 +988,7 @@ void PlayerWheel::addGems(NetworkMessage &msg) const { msg.add<uint16_t>(getGemIndex(gem.uuid)); } - auto revealedGems = getRevealedGems(); + const auto revealedGems = getRevealedGems(); msg.add<uint16_t>(revealedGems.size()); uint16_t index = 0; for (const auto &gem : revealedGems) { @@ -1010,7 +1016,7 @@ void PlayerWheel::sendOpenWheelWindow(NetworkMessage &msg, uint32_t ownerId) con } msg.addByte(0x5F); - bool canUse = canOpenWheel(); + const bool canUse = canOpenWheel(); msg.add<uint32_t>(ownerId); // Player ID msg.addByte(canUse ? 1 : 0); // Can Use if (!canUse) { @@ -1065,7 +1071,7 @@ bool PlayerWheel::checkSavePointsBySlotType(WheelSlots_t slotType, uint16_t poin setPointsBySlotType(static_cast<uint8_t>(slotType), 0); - auto unusedPoints = getUnusedPoints(); + const auto unusedPoints = getUnusedPoints(); if (points > unusedPoints) { return false; } @@ -1077,7 +1083,7 @@ bool PlayerWheel::checkSavePointsBySlotType(WheelSlots_t slotType, uint16_t poin void PlayerWheel::saveSlotPointsHandleRetryErrors(std::vector<SlotInfo> &retryTable, int &errors) { std::vector<SlotInfo> temporaryTable; for (const auto &data : retryTable) { - auto saved = checkSavePointsBySlotType(static_cast<WheelSlots_t>(data.slot), data.points); + const auto saved = checkSavePointsBySlotType(static_cast<WheelSlots_t>(data.slot), data.points); if (saved) { errors--; } else { @@ -1111,13 +1117,13 @@ void PlayerWheel::saveSlotPointsOnPressSaveButton(NetworkMessage &msg) { return; } - auto order = g_game().getIOWheel()->getSlotPrioritaryOrder(static_cast<WheelSlots_t>(slot)); + const auto order = g_game().getIOWheel()->getSlotPrioritaryOrder(static_cast<WheelSlots_t>(slot)); if (order == -1) { continue; } // The slot information is then added to the vector in order. - sortedTable.push_back({ order, slot, slotPoints }); + sortedTable.emplace_back(order, slot, slotPoints); } // After iterating over all slots, the vector is sorted according to the slot order. @@ -1130,7 +1136,7 @@ void PlayerWheel::saveSlotPointsOnPressSaveButton(NetworkMessage &msg) { // Processes the vector in the correct order. If it is not possible to save points for a slot, for (const auto &data : sortedTable) { - auto canSave = checkSavePointsBySlotType(static_cast<WheelSlots_t>(data.slot), data.points); + const auto canSave = checkSavePointsBySlotType(static_cast<WheelSlots_t>(data.slot), data.points); if (!canSave) { sortedTableRetry.emplace_back(data); errors++; @@ -1155,12 +1161,12 @@ void PlayerWheel::saveSlotPointsOnPressSaveButton(NetworkMessage &msg) { // Gem Vessels for (const auto &affinity : magic_enum::enum_values<WheelGemAffinity_t>()) { - bool hasGem = msg.getByte(); + const bool hasGem = msg.getByte(); if (!hasGem) { removeActiveGem(affinity); continue; } - uint16_t gemIndex = msg.get<uint16_t>(); + const auto gemIndex = msg.get<uint16_t>(); setActiveGem(affinity, gemIndex); } @@ -1176,15 +1182,15 @@ void PlayerWheel::saveSlotPointsOnPressSaveButton(NetworkMessage &msg) { * Functions for load and save player database informations */ void PlayerWheel::loadDBPlayerSlotPointsOnLogin() { - auto resultString = fmt::format("SELECT `slot` FROM `player_wheeldata` WHERE `player_id` = {}", m_player.getGUID()); - DBResult_ptr result = Database::getInstance().storeQuery(resultString); + const auto resultString = fmt::format("SELECT `slot` FROM `player_wheeldata` WHERE `player_id` = {}", m_player.getGUID()); + const DBResult_ptr result = Database::getInstance().storeQuery(resultString); // Ignore if player not have nothing inserted in the table if (!result) { return; } unsigned long size; - auto attribute = result->getStream("slot", size); + const auto attribute = result->getStream("slot", size); PropStream propStream; propStream.init(attribute, size); for (size_t i = 0; i < size; i++) { @@ -1198,7 +1204,7 @@ void PlayerWheel::loadDBPlayerSlotPointsOnLogin() { } bool PlayerWheel::saveDBPlayerSlotPointsOnLogout() const { - Database &db = Database::getInstance(); + const Database &db = Database::getInstance(); std::ostringstream query; DBInsert insertWheelData("INSERT INTO `player_wheeldata` (`player_id`, `slot`) VALUES "); insertWheelData.upsert({ "slot" }); @@ -1218,7 +1224,7 @@ bool PlayerWheel::saveDBPlayerSlotPointsOnLogout() const { size_t attributesSize; const char* attributes = stream.getStream(attributesSize); if (attributesSize > 0) { - query << m_player.getGUID() << ',' << db.escapeBlob(attributes, (uint32_t)attributesSize); + query << m_player.getGUID() << ',' << db.escapeBlob(attributes, static_cast<uint32_t>(attributesSize)); if (!insertWheelData.addRow(query)) { g_logger().debug("[{}] failed to insert row data", __FUNCTION__); return false; @@ -1240,15 +1246,15 @@ uint16_t PlayerWheel::getExtraPoints() const { } uint16_t totalBonus = 0; - for (const auto &scroll : WheelOfDestinyPromotionScrolls) { + for (const auto &[itemId, name, extraPoints] : WheelOfDestinyPromotionScrolls) { const auto &scrollKv = m_player.kv()->scoped("wheel-of-destiny")->scoped("scrolls"); if (!scrollKv) { continue; } - auto scrollKV = scrollKv->get(scroll.name); + const auto scrollKV = scrollKv->get(name); if (scrollKV && scrollKV->get<bool>()) { - totalBonus += scroll.extraPoints; + totalBonus += extraPoints; } } @@ -1256,7 +1262,7 @@ uint16_t PlayerWheel::getExtraPoints() const { } uint16_t PlayerWheel::getWheelPoints(bool includeExtraPoints /* = true*/) const { - uint32_t level = m_player.getLevel(); + const uint32_t level = m_player.getLevel(); auto totalPoints = std::max(0u, (level - m_minLevelToStartCountPoints)) * m_pointsPerLevel; if (includeExtraPoints) { @@ -1374,7 +1380,7 @@ void PlayerWheel::setPlayerCombatStats(CombatType_t type, int32_t leechAmount) { } } -void PlayerWheel::reloadPlayerData() { +void PlayerWheel::reloadPlayerData() const { // Maybe it's not really necessary, but it doesn't hurt to validate if (!m_player.getTile()) { return; @@ -1407,22 +1413,22 @@ void PlayerWheel::registerPlayerBonusData() { auto activeGems = getActiveGems(); std::string playerName = m_player.getName(); - for (const auto &gem : activeGems) { - auto count = m_playerBonusData.unlockedVesselResonances[static_cast<uint8_t>(gem.affinity)]; + for (const auto &[uuid, locked, affinity, quality, basicModifier1, basicModifier2, supremeModifier] : activeGems) { + auto count = m_playerBonusData.unlockedVesselResonances[static_cast<uint8_t>(affinity)]; if (count >= 1) { - std::string modifierName(magic_enum::enum_name(gem.basicModifier1)); - g_logger().debug("[{}] Adding basic modifier 1 {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(gem.quality), magic_enum::enum_name(gem.affinity)); - m_modifierContext->addStrategies(gem.basicModifier1); + std::string modifierName(magic_enum::enum_name(basicModifier1)); + g_logger().debug("[{}] Adding basic modifier 1 {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(quality), magic_enum::enum_name(affinity)); + m_modifierContext->addStrategies(basicModifier1); } - if (count >= 2 && gem.quality >= WheelGemQuality_t::Regular) { - std::string modifierName(magic_enum::enum_name(gem.basicModifier2)); - g_logger().debug("[{}] Adding basic modifier 2 {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(gem.quality), magic_enum::enum_name(gem.affinity)); - m_modifierContext->addStrategies(gem.basicModifier2); + if (count >= 2 && quality >= WheelGemQuality_t::Regular) { + std::string modifierName(magic_enum::enum_name(basicModifier2)); + g_logger().debug("[{}] Adding basic modifier 2 {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(quality), magic_enum::enum_name(affinity)); + m_modifierContext->addStrategies(basicModifier2); } - if (count >= 3 && gem.quality >= WheelGemQuality_t::Greater) { - std::string modifierName(magic_enum::enum_name(gem.supremeModifier)); - g_logger().debug("[{}] Adding supreme modifier {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(gem.quality), magic_enum::enum_name(gem.affinity)); - m_modifierContext->addStrategies(gem.supremeModifier); + if (count >= 3 && quality >= WheelGemQuality_t::Greater) { + std::string modifierName(magic_enum::enum_name(supremeModifier)); + g_logger().debug("[{}] Adding supreme modifier {} to player {} from {} gem affinity {}", __FUNCTION__, modifierName, playerName, magic_enum::enum_name(quality), magic_enum::enum_name(affinity)); + m_modifierContext->addStrategies(supremeModifier); } } m_modifierContext->executeStrategies(); @@ -1664,12 +1670,12 @@ void PlayerWheel::printPlayerWheelMethodsBonusData(const PlayerWheelMethodsBonus g_logger().debug("Vessel Resonance:"); for (size_t i = 0; i < bonusData.unlockedVesselResonances.size(); ++i) { - auto count = bonusData.unlockedVesselResonances[i]; + const auto count = bonusData.unlockedVesselResonances[i]; if (count == 0) { continue; } - auto affinity = static_cast<WheelGemAffinity_t>(i); + const auto affinity = static_cast<WheelGemAffinity_t>(i); std::string affinityName(magic_enum::enum_name(affinity)); g_logger().debug(" Affinity: {} count: {}", affinityName, bonusData.unlockedVesselResonances[i]); } @@ -1777,13 +1783,13 @@ void PlayerWheel::printPlayerWheelMethodsBonusData(const PlayerWheelMethodsBonus void PlayerWheel::loadDedicationAndConvictionPerks() { using VocationBonusFunction = std::function<void(const std::shared_ptr<Player> &, uint16_t, uint8_t, PlayerWheelMethodsBonusData &)>; auto wheelFunctions = g_game().getIOWheel()->getWheelMapFunctions(); - auto vocationCipId = m_player.getPlayerVocationEnum(); + const auto vocationCipId = m_player.getPlayerVocationEnum(); if (vocationCipId < VOCATION_KNIGHT_CIP || vocationCipId > VOCATION_DRUID_CIP) { return; } for (uint8_t i = WheelSlots_t::SLOT_FIRST; i <= WheelSlots_t::SLOT_LAST; ++i) { - uint16_t points = getPointsBySlotType(static_cast<WheelSlots_t>(i)); + const uint16_t points = getPointsBySlotType(static_cast<WheelSlots_t>(i)); if (points > 0) { VocationBonusFunction internalData = nullptr; auto it = wheelFunctions.find(static_cast<WheelSlots_t>(i)); @@ -1817,8 +1823,8 @@ void PlayerWheel::loadRevelationPerks() { m_playerBonusData.stats.damage += statsDamage; m_playerBonusData.stats.healing += statsHealing; - auto redStageValue = static_cast<uint8_t>(redStageEnum); - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto redStageValue = static_cast<uint8_t>(redStageEnum); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_DRUID_CIP) { m_playerBonusData.stages.blessingOfTheGrove = redStageValue; } else if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { @@ -1845,8 +1851,8 @@ void PlayerWheel::loadRevelationPerks() { m_playerBonusData.stats.damage += statsDamage; m_playerBonusData.stats.healing += statsHealing; - auto purpleStage = static_cast<uint8_t>(purpleStageEnum); - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto purpleStage = static_cast<uint8_t>(purpleStageEnum); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { m_playerBonusData.avatar.steel = purpleStage; for (uint8_t i = 0; i < purpleStage; ++i) { @@ -1876,8 +1882,8 @@ void PlayerWheel::loadRevelationPerks() { m_playerBonusData.stats.damage += statsDamage; m_playerBonusData.stats.healing += statsHealing; - auto blueStage = static_cast<uint8_t>(blueStageEnum); - auto vocationEnum = m_player.getPlayerVocationEnum(); + const auto blueStage = static_cast<uint8_t>(blueStageEnum); + const auto vocationEnum = m_player.getPlayerVocationEnum(); if (vocationEnum == Vocation_t::VOCATION_KNIGHT_CIP) { m_playerBonusData.stages.combatMastery = blueStage; } else if (vocationEnum == Vocation_t::VOCATION_SORCERER_CIP) { @@ -1903,7 +1909,7 @@ void PlayerWheel::loadRevelationPerks() { WheelStageEnum_t PlayerWheel::getPlayerSliceStage(const std::string &color) const { std::vector<WheelSlots_t> slots; - WheelGemAffinity_t affinity = WheelGemAffinity_t::Green; + auto affinity = WheelGemAffinity_t::Green; if (color == "green") { affinity = WheelGemAffinity_t::Green; slots = { @@ -1968,9 +1974,11 @@ WheelStageEnum_t PlayerWheel::getPlayerSliceStage(const std::string &color) cons if (totalPoints >= static_cast<int>(WheelStagePointsEnum_t::THREE)) { return WheelStageEnum_t::THREE; - } else if (totalPoints >= static_cast<int>(WheelStagePointsEnum_t::TWO)) { + } + if (totalPoints >= static_cast<int>(WheelStagePointsEnum_t::TWO)) { return WheelStageEnum_t::TWO; - } else if (totalPoints >= static_cast<uint8_t>(WheelStagePointsEnum_t::ONE)) { + } + if (totalPoints >= static_cast<uint8_t>(WheelStagePointsEnum_t::ONE)) { return WheelStageEnum_t::ONE; } @@ -2034,8 +2042,8 @@ bool PlayerWheel::checkBattleInstinct() { if (creaturesNearby >= 5) { m_creaturesNearby = creaturesNearby; creaturesNearby -= 4; - uint16_t meleeSkill = 1 * creaturesNearby; - uint16_t shieldSkill = 6 * creaturesNearby; + const uint16_t meleeSkill = 1 * creaturesNearby; + const uint16_t shieldSkill = 6 * creaturesNearby; if (getMajorStat(WheelMajor_t::MELEE) != meleeSkill || getMajorStat(WheelMajor_t::SHIELD) != shieldSkill) { setMajorStat(WheelMajor_t::MELEE, meleeSkill); setMajorStat(WheelMajor_t::SHIELD, shieldSkill); @@ -2079,8 +2087,8 @@ bool PlayerWheel::checkPositionalTatics() { break; } } - uint16_t magicSkill = 3; - uint16_t distanceSkill = 3; + constexpr uint16_t magicSkill = 3; + constexpr uint16_t distanceSkill = 3; if (creaturesNearby == 0) { m_creaturesNearby = creaturesNearby; if (getMajorStat(WheelMajor_t::DISTANCE) != distanceSkill) { @@ -2108,9 +2116,9 @@ bool PlayerWheel::checkPositionalTatics() { bool PlayerWheel::checkBallisticMastery() { setOnThinkTimer(WheelOnThink_t::BALLISTIC_MASTERY, OTSYS_TIME() + 2000); bool updateClient = false; - int32_t newCritical = 1000; - uint16_t newHolyBonus = 2; // 2% - uint16_t newPhysicalBonus = 2; // 2% + constexpr int32_t newCritical = 1000; + constexpr uint16_t newHolyBonus = 2; // 2% + constexpr uint16_t newPhysicalBonus = 2; // 2% const auto &item = m_player.getWeapon(); if (item && item->getAmmoType() == AMMO_BOLT) { @@ -2151,7 +2159,7 @@ bool PlayerWheel::checkBallisticMastery() { bool PlayerWheel::checkCombatMastery() { setOnThinkTimer(WheelOnThink_t::COMBAT_MASTERY, OTSYS_TIME() + 2000); bool updateClient = false; - uint8_t stage = getStage(WheelStage_t::COMBAT_MASTERY); + const uint8_t stage = getStage(WheelStage_t::COMBAT_MASTERY); const auto &item = m_player.getWeapon(); if (item && item->getSlotPosition() & SLOTP_TWO_HAND) { @@ -2218,7 +2226,7 @@ bool PlayerWheel::checkDivineEmpowerment() { } if (isOwner) { - uint8_t stage = getStage(WheelStage_t::DIVINE_EMPOWERMENT); + const uint8_t stage = getStage(WheelStage_t::DIVINE_EMPOWERMENT); if (stage >= 3) { damageBonus = 7; } else if (stage >= 2) { @@ -2242,7 +2250,7 @@ int32_t PlayerWheel::checkDivineGrenade(const std::shared_ptr<Creature> &target) } int32_t damageBonus = 0; - uint8_t stage = getStage(WheelStage_t::DIVINE_GRENADE); + const uint8_t stage = getStage(WheelStage_t::DIVINE_GRENADE); if (stage >= 3) { damageBonus = 100; @@ -2264,7 +2272,7 @@ void PlayerWheel::checkGiftOfLife() { g_game().addMagicEffect(m_player.getPosition(), CONST_ME_WATER_DROP); g_game().combatChangeHealth(m_player.getPlayer(), m_player.getPlayer(), giftDamage); // Condition cooldown reduction - uint16_t reductionTimer = 60000; + constexpr uint16_t reductionTimer = 60000; reduceAllSpellsCooldownTimer(reductionTimer); // Set cooldown @@ -2278,8 +2286,8 @@ int32_t PlayerWheel::checkBlessingGroveHealingByTarget(const std::shared_ptr<Cre } int32_t healingBonus = 0; - uint8_t stage = getStage(WheelStage_t::BLESSING_OF_THE_GROVE); - int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); + const uint8_t stage = getStage(WheelStage_t::BLESSING_OF_THE_GROVE); + const int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); if (healthPercent <= 30) { if (stage >= 3) { healingBonus = 24; @@ -2307,8 +2315,8 @@ int32_t PlayerWheel::checkTwinBurstByTarget(const std::shared_ptr<Creature> &tar } int32_t damageBonus = 0; - uint8_t stage = getStage(WheelStage_t::TWIN_BURST); - int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); + const uint8_t stage = getStage(WheelStage_t::TWIN_BURST); + const int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); if (healthPercent > 60) { if (stage >= 3) { damageBonus = 60; @@ -2328,8 +2336,8 @@ int32_t PlayerWheel::checkExecutionersThrow(const std::shared_ptr<Creature> &tar } int32_t damageBonus = 0; - uint8_t stage = getStage(WheelStage_t::EXECUTIONERS_THROW); - int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); + const uint8_t stage = getStage(WheelStage_t::EXECUTIONERS_THROW); + const int32_t healthPercent = std::round((static_cast<double>(target->getHealth()) * 100) / static_cast<double>(target->getMaxHealth())); if (healthPercent <= 30) { if (stage >= 3) { damageBonus = 150; @@ -2345,7 +2353,7 @@ int32_t PlayerWheel::checkExecutionersThrow(const std::shared_ptr<Creature> &tar int32_t PlayerWheel::checkBeamMasteryDamage() const { int32_t damageBoost = 0; - uint8_t stage = getStage(WheelStage_t::BEAM_MASTERY); + const uint8_t stage = getStage(WheelStage_t::BEAM_MASTERY); if (stage >= 3) { damageBoost = 14; } else if (stage >= 2) { @@ -2362,7 +2370,7 @@ int32_t PlayerWheel::checkDrainBodyLeech(const std::shared_ptr<Creature> &target return 0; } - uint8_t stage = target->getWheelOfDestinyDrainBodyDebuff(); + const uint8_t stage = target->getWheelOfDestinyDrainBodyDebuff(); if (target->getBuff(BUFF_DAMAGERECEIVED) > 100 && skill == SKILL_MANA_LEECH_AMOUNT) { int32_t manaLeechSkill = 0; if (stage >= 3) { @@ -2391,14 +2399,14 @@ int32_t PlayerWheel::checkDrainBodyLeech(const std::shared_ptr<Creature> &target } int32_t PlayerWheel::checkBattleHealingAmount() const { - double amount = (double)m_player.getSkillLevel(SKILL_SHIELD) * 0.2; - uint8_t healthPercent = (m_player.getHealth() * 100) / m_player.getMaxHealth(); + double amount = static_cast<double>(m_player.getSkillLevel(SKILL_SHIELD)) * 0.2; + const uint8_t healthPercent = (m_player.getHealth() * 100) / m_player.getMaxHealth(); if (healthPercent <= 30) { amount *= 3; } else if (healthPercent <= 60) { amount *= 2; } - return (int32_t)amount; + return static_cast<int32_t>(amount); } int32_t PlayerWheel::checkAvatarSkill(WheelAvatarSkill_t skill) const { @@ -2426,9 +2434,11 @@ int32_t PlayerWheel::checkAvatarSkill(WheelAvatarSkill_t skill) const { if (skill == WheelAvatarSkill_t::DAMAGE_REDUCTION) { if (stage >= 3) { return 15; - } else if (stage >= 2) { + } + if (stage >= 2) { return 10; - } else if (stage >= 1) { + } + if (stage >= 1) { return 5; } } else if (skill == WheelAvatarSkill_t::CRITICAL_CHANCE) { @@ -2436,9 +2446,11 @@ int32_t PlayerWheel::checkAvatarSkill(WheelAvatarSkill_t skill) const { } else if (skill == WheelAvatarSkill_t::CRITICAL_DAMAGE) { if (stage >= 3) { return 1500; - } else if (stage >= 2) { + } + if (stage >= 2) { return 1000; - } else if (stage >= 1) { + } + if (stage >= 1) { return 500; } } @@ -2517,7 +2529,7 @@ void PlayerWheel::onThink(bool force /* = false*/) { } } -void PlayerWheel::reduceAllSpellsCooldownTimer(int32_t value) { +void PlayerWheel::reduceAllSpellsCooldownTimer(int32_t value) const { for (const auto &condition : m_player.getConditionsByType(CONDITION_SPELLCOOLDOWN)) { if (condition->getTicks() <= value) { m_player.sendSpellCooldown(condition->getSubId(), 0); @@ -2573,7 +2585,7 @@ void PlayerWheel::downgradeSpell(const std::string &name) { std::shared_ptr<Spell> PlayerWheel::getCombatDataSpell(CombatDamage &damage) { std::shared_ptr<Spell> spell = nullptr; - WheelSpellGrade_t spellGrade = WheelSpellGrade_t::NONE; + auto spellGrade = WheelSpellGrade_t::NONE; if (!(damage.instantSpellName).empty()) { spellGrade = getSpellUpgrade(damage.instantSpellName); spell = g_spells().getInstantSpellByName(damage.instantSpellName); @@ -2798,43 +2810,62 @@ bool PlayerWheel::getInstant(WheelInstant_t type) const { uint8_t PlayerWheel::getStage(const std::string &name) const { if (name == "Battle Instinct") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_INSTINCT); - } else if (name == "Battle Healing") { + } + if (name == "Battle Healing") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_HEALING); - } else if (name == "Positional Tatics") { + } + if (name == "Positional Tatics") { return PlayerWheel::getInstant(WheelInstant_t::POSITIONAL_TATICS); - } else if (name == "Ballistic Mastery") { + } + if (name == "Ballistic Mastery") { return PlayerWheel::getInstant(WheelInstant_t::BALLISTIC_MASTERY); - } else if (name == "Healing Link") { + } + if (name == "Healing Link") { return PlayerWheel::getInstant(WheelInstant_t::HEALING_LINK); - } else if (name == "Runic Mastery") { + } + if (name == "Runic Mastery") { return PlayerWheel::getInstant(WheelInstant_t::RUNIC_MASTERY); - } else if (name == "Focus Mastery") { + } + if (name == "Focus Mastery") { return PlayerWheel::getInstant(WheelInstant_t::FOCUS_MASTERY); - } else if (name == "Beam Mastery") { + } + if (name == "Beam Mastery") { return PlayerWheel::getStage(WheelStage_t::BEAM_MASTERY); - } else if (name == "Combat Mastery") { + } + if (name == "Combat Mastery") { return PlayerWheel::getStage(WheelStage_t::COMBAT_MASTERY); - } else if (name == "Gift of Life") { + } + if (name == "Gift of Life") { return PlayerWheel::getStage(WheelStage_t::GIFT_OF_LIFE); - } else if (name == "Blessing of the Grove") { + } + if (name == "Blessing of the Grove") { return PlayerWheel::getStage(WheelStage_t::BLESSING_OF_THE_GROVE); - } else if (name == "Drain Body") { + } + if (name == "Drain Body") { return PlayerWheel::getStage(WheelStage_t::DRAIN_BODY); - } else if (name == "Divine Empowerment") { + } + if (name == "Divine Empowerment") { return PlayerWheel::getStage(WheelStage_t::DIVINE_EMPOWERMENT); - } else if (name == "Divine Grenade") { + } + if (name == "Divine Grenade") { return PlayerWheel::getStage(WheelStage_t::DIVINE_GRENADE); - } else if (name == "Twin Burst") { + } + if (name == "Twin Burst") { return PlayerWheel::getStage(WheelStage_t::TWIN_BURST); - } else if (name == "Executioner's Throw") { + } + if (name == "Executioner's Throw") { return PlayerWheel::getStage(WheelStage_t::EXECUTIONERS_THROW); - } else if (name == "Avatar of Light") { + } + if (name == "Avatar of Light") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_LIGHT); - } else if (name == "Avatar of Nature") { + } + if (name == "Avatar of Nature") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_NATURE); - } else if (name == "Avatar of Steel") { + } + if (name == "Avatar of Steel") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_STEEL); - } else if (name == "Avatar of Storm") { + } + if (name == "Avatar of Storm") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_STORM); } @@ -2922,43 +2953,62 @@ int64_t PlayerWheel::getOnThinkTimer(WheelOnThink_t type) const { bool PlayerWheel::getInstant(const std::string &name) const { if (name == "Battle Instinct") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_INSTINCT); - } else if (name == "Battle Healing") { + } + if (name == "Battle Healing") { return PlayerWheel::getInstant(WheelInstant_t::BATTLE_HEALING); - } else if (name == "Positional Tatics") { + } + if (name == "Positional Tatics") { return PlayerWheel::getInstant(WheelInstant_t::POSITIONAL_TATICS); - } else if (name == "Ballistic Mastery") { + } + if (name == "Ballistic Mastery") { return PlayerWheel::getInstant(WheelInstant_t::BALLISTIC_MASTERY); - } else if (name == "Healing Link") { + } + if (name == "Healing Link") { return PlayerWheel::getInstant(WheelInstant_t::HEALING_LINK); - } else if (name == "Runic Mastery") { + } + if (name == "Runic Mastery") { return PlayerWheel::getInstant(WheelInstant_t::RUNIC_MASTERY); - } else if (name == "Focus Mastery") { + } + if (name == "Focus Mastery") { return PlayerWheel::getInstant(WheelInstant_t::FOCUS_MASTERY); - } else if (name == "Beam Mastery") { + } + if (name == "Beam Mastery") { return PlayerWheel::getStage(WheelStage_t::BEAM_MASTERY); - } else if (name == "Combat Mastery") { + } + if (name == "Combat Mastery") { return PlayerWheel::getStage(WheelStage_t::COMBAT_MASTERY); - } else if (name == "Gift of Life") { + } + if (name == "Gift of Life") { return PlayerWheel::getStage(WheelStage_t::GIFT_OF_LIFE); - } else if (name == "Blessing of the Grove") { + } + if (name == "Blessing of the Grove") { return PlayerWheel::getStage(WheelStage_t::BLESSING_OF_THE_GROVE); - } else if (name == "Drain Body") { + } + if (name == "Drain Body") { return PlayerWheel::getStage(WheelStage_t::DRAIN_BODY); - } else if (name == "Divine Empowerment") { + } + if (name == "Divine Empowerment") { return PlayerWheel::getStage(WheelStage_t::DIVINE_EMPOWERMENT); - } else if (name == "Divine Grenade") { + } + if (name == "Divine Grenade") { return PlayerWheel::getStage(WheelStage_t::DIVINE_GRENADE); - } else if (name == "Twin Burst") { + } + if (name == "Twin Burst") { return PlayerWheel::getStage(WheelStage_t::TWIN_BURST); - } else if (name == "Executioner's Throw") { + } + if (name == "Executioner's Throw") { return PlayerWheel::getStage(WheelStage_t::EXECUTIONERS_THROW); - } else if (name == "Avatar of Light") { + } + if (name == "Avatar of Light") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_LIGHT); - } else if (name == "Avatar of Nature") { + } + if (name == "Avatar of Nature") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_NATURE); - } else if (name == "Avatar of Steel") { + } + if (name == "Avatar of Steel") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_STEEL); - } else if (name == "Avatar of Storm") { + } + if (name == "Avatar of Storm") { return PlayerWheel::getStage(WheelStage_t::AVATAR_OF_STORM); } @@ -2969,9 +3019,11 @@ bool PlayerWheel::getInstant(const std::string &name) const { uint32_t PlayerWheel::getGiftOfLifeTotalCooldown() const { if (getStage(WheelStage_t::GIFT_OF_LIFE) == 1) { return 1 * 60 * 60 * 30; - } else if (getStage(WheelStage_t::GIFT_OF_LIFE) == 2) { + } + if (getStage(WheelStage_t::GIFT_OF_LIFE) == 2) { return 1 * 60 * 60 * 20; - } else if (getStage(WheelStage_t::GIFT_OF_LIFE) == 3) { + } + if (getStage(WheelStage_t::GIFT_OF_LIFE) == 3) { return 1 * 60 * 60 * 10; } return 0; @@ -2980,9 +3032,11 @@ uint32_t PlayerWheel::getGiftOfLifeTotalCooldown() const { uint8_t PlayerWheel::getGiftOfLifeValue() const { if (getStage(WheelStage_t::GIFT_OF_LIFE) == 1) { return 20; - } else if (getStage(WheelStage_t::GIFT_OF_LIFE) == 2) { + } + if (getStage(WheelStage_t::GIFT_OF_LIFE) == 2) { return 25; - } else if (getStage(WheelStage_t::GIFT_OF_LIFE) == 3) { + } + if (getStage(WheelStage_t::GIFT_OF_LIFE) == 3) { return 30; } @@ -2990,7 +3044,7 @@ uint8_t PlayerWheel::getGiftOfLifeValue() const { } int32_t PlayerWheel::getGiftOfCooldown() const { - int32_t value = m_player.getStorageValue(STORAGEVALUE_GIFT_OF_LIFE_COOLDOWN_WOD); + const int32_t value = m_player.getStorageValue(STORAGEVALUE_GIFT_OF_LIFE_COOLDOWN_WOD); if (value <= 0) { return 0; } @@ -3005,7 +3059,7 @@ void PlayerWheel::setGiftOfCooldown(int32_t value, bool isOnThink) { } void PlayerWheel::decreaseGiftOfCooldown(int32_t value) { - int32_t cooldown = getGiftOfCooldown() - value; + const int32_t cooldown = getGiftOfCooldown() - value; if (cooldown <= 0) { setOnThinkTimer(WheelOnThink_t::GIFT_OF_LIFE, OTSYS_TIME() + 3600000); return; @@ -3080,7 +3134,7 @@ void PlayerWheel::healIfBattleHealingActive() const { } void PlayerWheel::adjustDamageBasedOnResistanceAndSkill(int32_t &damage, CombatType_t combatType) const { - int32_t wheelOfDestinyElementAbsorb = getResistance(combatType); + const int32_t wheelOfDestinyElementAbsorb = getResistance(combatType); if (wheelOfDestinyElementAbsorb > 0) { damage -= std::ceil((damage * wheelOfDestinyElementAbsorb) / 10000.); } @@ -3089,10 +3143,10 @@ void PlayerWheel::adjustDamageBasedOnResistanceAndSkill(int32_t &damage, CombatT } float PlayerWheel::calculateMitigation() const { - int32_t skill = m_player.getSkillLevel(SKILL_SHIELD); + const int32_t skill = m_player.getSkillLevel(SKILL_SHIELD); int32_t defenseValue = 0; - std::shared_ptr<Item> weapon = m_player.inventory[CONST_SLOT_LEFT]; - std::shared_ptr<Item> shield = m_player.inventory[CONST_SLOT_RIGHT]; + const auto &weapon = m_player.inventory[CONST_SLOT_LEFT]; + const auto &shield = m_player.inventory[CONST_SLOT_RIGHT]; float fightFactor = 1.0f; float shieldFactor = 1.0f; @@ -3139,8 +3193,8 @@ float PlayerWheel::calculateMitigation() const { } } - float mitigation = std::ceil(((((skill * m_player.vocation->mitigationFactor) + (shieldFactor * (float)defenseValue)) / 100.0f) * fightFactor * distanceFactor) * 100.0f) / 100.0f; - mitigation += (mitigation * (float)getMitigationMultiplier()) / 100.f; + float mitigation = std::ceil(((((skill * m_player.vocation->mitigationFactor) + (shieldFactor * static_cast<float>(defenseValue))) / 100.0f) * fightFactor * distanceFactor) * 100.0f) / 100.0f; + mitigation += (mitigation * static_cast<float>(getMitigationMultiplier())) / 100.f; return mitigation; } diff --git a/src/creatures/players/wheel/player_wheel.hpp b/src/creatures/players/wheel/player_wheel.hpp index 427c5afa496..d9979bbd3ea 100644 --- a/src/creatures/players/wheel/player_wheel.hpp +++ b/src/creatures/players/wheel/player_wheel.hpp @@ -41,7 +41,7 @@ struct PlayerWheelGem { } static PlayerWheelGem load(const std::shared_ptr<KV> &kv, const std::string &uuid) { - auto val = kv->scoped("revealed")->get(uuid); + const auto val = kv->scoped("revealed")->get(uuid); if (!val || !val.has_value()) { return {}; } @@ -157,7 +157,7 @@ class PlayerWheel { void setPlayerCombatStats(CombatType_t type, int32_t leechAmount); - void reloadPlayerData(); + void reloadPlayerData() const; void registerPlayerBonusData(); @@ -239,7 +239,7 @@ class PlayerWheel { int32_t checkFocusMasteryDamage(); int32_t checkElementSensitiveReduction(CombatType_t type) const; // Wheel of destiny - General functions: - void reduceAllSpellsCooldownTimer(int32_t value); + void reduceAllSpellsCooldownTimer(int32_t value) const; void resetUpgradedSpells(); void upgradeSpell(const std::string &name); void downgradeSpell(const std::string &name); @@ -388,12 +388,12 @@ class PlayerWheel { PlayerWheelGem getGem(uint16_t index) const; PlayerWheelGem getGem(const std::string &uuid) const; uint16_t getGemIndex(const std::string &uuid) const; - void revealGem(WheelGemQuality_t quality); - void destroyGem(uint16_t index); - void switchGemDomain(uint16_t index); - void toggleGemLock(uint16_t index); - void setActiveGem(WheelGemAffinity_t affinity, uint16_t index); - void removeActiveGem(WheelGemAffinity_t affinity); + void revealGem(WheelGemQuality_t quality) const; + void destroyGem(uint16_t index) const; + void switchGemDomain(uint16_t index) const; + void toggleGemLock(uint16_t index) const; + void setActiveGem(WheelGemAffinity_t affinity, uint16_t index) const; + void removeActiveGem(WheelGemAffinity_t affinity) const; void addRevelationBonus(WheelGemAffinity_t affinity, uint16_t points) { m_bonusRevelationPoints[static_cast<size_t>(affinity)] += points; } @@ -401,7 +401,7 @@ class PlayerWheel { m_bonusRevelationPoints = { 0, 0, 0, 0 }; } - void addSpellBonus(const std::string &spellName, WheelSpells::Bonus bonus) { + void addSpellBonus(const std::string &spellName, const WheelSpells::Bonus &bonus) { if (m_spellsBonuses.contains(spellName)) { m_spellsBonuses[spellName].decrease.cooldown += bonus.decrease.cooldown; m_spellsBonuses[spellName].decrease.manaCost += bonus.decrease.manaCost; @@ -425,28 +425,28 @@ class PlayerWheel { if (!m_spellsBonuses.contains(spellName)) { return 0; } - auto bonus = m_spellsBonuses.at(spellName); + auto [leech, increase, decrease] = m_spellsBonuses.at(spellName); switch (boost) { case WheelSpellBoost_t::COOLDOWN: - return bonus.decrease.cooldown; + return decrease.cooldown; case WheelSpellBoost_t::MANA: - return bonus.decrease.manaCost; + return decrease.manaCost; case WheelSpellBoost_t::SECONDARY_GROUP_COOLDOWN: - return bonus.decrease.secondaryGroupCooldown; + return decrease.secondaryGroupCooldown; case WheelSpellBoost_t::CRITICAL_CHANCE: - return bonus.increase.criticalChance; + return increase.criticalChance; case WheelSpellBoost_t::CRITICAL_DAMAGE: - return bonus.increase.criticalDamage; + return increase.criticalDamage; case WheelSpellBoost_t::DAMAGE: - return bonus.increase.damage; + return increase.damage; case WheelSpellBoost_t::DAMAGE_REDUCTION: - return bonus.increase.damageReduction; + return increase.damageReduction; case WheelSpellBoost_t::HEAL: - return bonus.increase.heal; + return increase.heal; case WheelSpellBoost_t::LIFE_LEECH: - return bonus.leech.life; + return leech.life; case WheelSpellBoost_t::MANA_LEECH: - return bonus.leech.mana; + return leech.mana; default: return 0; } diff --git a/src/creatures/players/wheel/wheel_gems.cpp b/src/creatures/players/wheel/wheel_gems.cpp index 16bd037a9e0..06363c64d3d 100644 --- a/src/creatures/players/wheel/wheel_gems.cpp +++ b/src/creatures/players/wheel/wheel_gems.cpp @@ -30,181 +30,181 @@ void GemModifierSpellBonusStrategy::execute() { void WheelModifierContext::addStrategies(WheelGemBasicModifier_t modifier) { switch (modifier) { case WheelGemBasicModifier_t::General_PhysicalResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_PHYSICALDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_PHYSICALDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_HolyResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_DeathResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_FireResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 200)); break; case WheelGemBasicModifier_t::General_EarthResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 200)); break; case WheelGemBasicModifier_t::General_IceResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 200)); break; case WheelGemBasicModifier_t::General_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 200)); break; case WheelGemBasicModifier_t::General_HolyResistance_DeathWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, 150)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, -100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, -100)); break; case WheelGemBasicModifier_t::General_DeathResistance_HolyWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, 150)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, -100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_DEATHDAMAGE, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_HOLYDAMAGE, -100)); break; case WheelGemBasicModifier_t::General_FireResistance_EarthResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_FireResistance_IceResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_FireResistance_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_EarthResistance_IceResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_EarthResistance_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_IceResistance_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::General_FireResistance_EarthWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_FireResistance_IceWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_FireResistance_EnergyWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EarthResistance_FireWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EarthResistance_IceWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EarthResistance_EnergyWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_IceResistance_EarthWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_IceResistance_FireWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_IceResistance_EnergyWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EnergyResistance_EarthWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EnergyResistance_IceWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_EnergyResistance_FireWeakness: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, -200)); break; case WheelGemBasicModifier_t::General_ManaDrainResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_MANADRAIN, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_MANADRAIN, 300)); break; case WheelGemBasicModifier_t::General_LifeDrainResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_LIFEDRAIN, 300)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_LIFEDRAIN, 300)); break; case WheelGemBasicModifier_t::General_ManaDrainResistance_LifeDrainResistance: - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_MANADRAIN, 150)); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_LIFEDRAIN, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_MANADRAIN, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_LIFEDRAIN, 150)); break; case WheelGemBasicModifier_t::General_MitigationMultiplier: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MITIGATION, 500)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MITIGATION, 500)); break; case WheelGemBasicModifier_t::Vocation_Health: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); break; case WheelGemBasicModifier_t::Vocation_Mana_FireResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Mana_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Mana_Earth_Resistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Mana_Ice_Resistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Mana: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); break; case WheelGemBasicModifier_t::Vocation_Health_FireResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Health_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Health_EarthResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Health_IceResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Mixed: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::HEALTH, getHealthValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA, getManaValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); break; case WheelGemBasicModifier_t::Vocation_Capacity_FireResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_FIREDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Capacity_EnergyResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ENERGYDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Capacity_EarthResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_EARTHDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Capacity_IceResistance: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); - m_strategies.push_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierResistanceStrategy>(m_wheel, CombatType_t::COMBAT_ICEDAMAGE, 100)); break; case WheelGemBasicModifier_t::Vocation_Capacity: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CAPACITY, getCapacityValue(m_vocation, modifier))); break; default: @@ -217,307 +217,307 @@ void WheelModifierContext::addStrategies(WheelGemSupremeModifier_t modifier) { switch (modifier) { case WheelGemSupremeModifier_t::General_Dodge: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::DODGE, 25)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::DODGE, 25)); break; case WheelGemSupremeModifier_t::General_LifeLeech: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::LIFE_LEECH, 120)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::LIFE_LEECH, 120)); break; case WheelGemSupremeModifier_t::General_ManaLeech: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA_LEECH, 40)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::MANA_LEECH, 40)); break; case WheelGemSupremeModifier_t::General_CriticalDamage: - m_strategies.push_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CRITICAL_DAMAGE, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierStatStrategy>(m_wheel, WheelStat_t::CRITICAL_DAMAGE, 150)); break; case WheelGemSupremeModifier_t::General_RevelationMastery_GiftOfLife: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Green, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Green, 150)); break; case WheelGemSupremeModifier_t::SorcererDruid_UltimateHealing: bonus.increase.heal = 10; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ultimate Healing", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ultimate Healing", bonus)); break; case WheelGemSupremeModifier_t::Knight_RevelationMastery_ExecutionersThrow: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); break; case WheelGemSupremeModifier_t::Knight_RevelationMastery_AvatarOfSteel: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); break; case WheelGemSupremeModifier_t::Knight_RevelationMastery_CombatMastery: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); break; case WheelGemSupremeModifier_t::Paladin_RevelationMastery_DivineGrenade: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); break; case WheelGemSupremeModifier_t::Paladin_RevelationMastery_AvatarOfLight: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); break; case WheelGemSupremeModifier_t::Paladin_RevelationMastery_DivineEmpowerment: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); break; case WheelGemSupremeModifier_t::Druid_RevelationMastery_BlessingOfTheGrove: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); break; case WheelGemSupremeModifier_t::Druid_RevelationMastery_AvatarOfNature: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); break; case WheelGemSupremeModifier_t::Druid_RevelationMastery_TwinBursts: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); break; case WheelGemSupremeModifier_t::Sorcerer_RevelationMastery_BeamMastery: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Red, 150)); break; case WheelGemSupremeModifier_t::Sorcerer_RevelationMastery_AvatarOfStorm: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Purple, 150)); break; case WheelGemSupremeModifier_t::Sorcerer_RevelationMastery_DrainBody: - m_strategies.push_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); + m_strategies.emplace_back(std::make_unique<GemModifierRevelationStrategy>(m_wheel, WheelGemAffinity_t::Blue, 150)); break; case WheelGemSupremeModifier_t::Knight_AvatarOfSteel_Cooldown: bonus.decrease.cooldown = 300 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Steel", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Steel", bonus)); break; case WheelGemSupremeModifier_t::Knight_ExecutionersThrow_Cooldown: bonus.decrease.cooldown = 1 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); break; case WheelGemSupremeModifier_t::Knight_ExecutionersThrow_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); break; case WheelGemSupremeModifier_t::Knight_ExecutionersThrow_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Executioner's Throw", bonus)); break; case WheelGemSupremeModifier_t::Knight_Fierce_Berserk_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fierce Berserk", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fierce Berserk", bonus)); break; case WheelGemSupremeModifier_t::Knight_Fierce_Berserk_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fierce Berserk", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fierce Berserk", bonus)); break; case WheelGemSupremeModifier_t::Knight_Berserk_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Berserk", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Berserk", bonus)); break; case WheelGemSupremeModifier_t::Knight_Berserk_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Berserk", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Berserk", bonus)); break; case WheelGemSupremeModifier_t::Knight_Front_Sweep_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Front Sweep", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Front Sweep", bonus)); break; case WheelGemSupremeModifier_t::Knight_Front_Sweep_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Front Sweep", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Front Sweep", bonus)); break; case WheelGemSupremeModifier_t::Knight_Groundshaker_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Groundshaker", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Groundshaker", bonus)); break; case WheelGemSupremeModifier_t::Knight_Groundshaker_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Groundshaker", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Groundshaker", bonus)); break; case WheelGemSupremeModifier_t::Knight_Annihilation_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Annihilation", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Annihilation", bonus)); break; case WheelGemSupremeModifier_t::Knight_Annihilation_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Annihilation", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Annihilation", bonus)); break; case WheelGemSupremeModifier_t::Knight_FairWoundCleansing_HealingIncrease: bonus.increase.heal = 10; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fair Wound Cleansing", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Fair Wound Cleansing", bonus)); break; case WheelGemSupremeModifier_t::Paladin_AvatarOfLight_Cooldown: bonus.decrease.cooldown = 300 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Light", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Light", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineDazzle_Cooldown: bonus.decrease.cooldown = 2 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Dazzle", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Dazzle", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineGrenade_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineGrenade_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineCaldera_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Caldera", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Caldera", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineCaldera_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Caldera", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Caldera", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineMissile_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Missile", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Missile", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineMissile_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Missile", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Missile", bonus)); break; case WheelGemSupremeModifier_t::Paladin_EtherealSpear_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ethereal Spear", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ethereal Spear", bonus)); break; case WheelGemSupremeModifier_t::Paladin_EtherealSpear_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ethereal Spear", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ethereal Spear", bonus)); break; case WheelGemSupremeModifier_t::Paladin_StrongEtherealSpear_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ethereal Spear", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ethereal Spear", bonus)); break; case WheelGemSupremeModifier_t::Paladin_StrongEtherealSpear_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ethereal Spear", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ethereal Spear", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineEmpowerment_Cooldown: bonus.decrease.cooldown = 3 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Empowerment", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Empowerment", bonus)); break; case WheelGemSupremeModifier_t::Paladin_DivineGrenade_Cooldown: bonus.decrease.cooldown = 1 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Divine Grenade", bonus)); break; case WheelGemSupremeModifier_t::Paladin_Salvation_HealingIncrease: bonus.increase.heal = 10; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Salvation", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Salvation", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_AvatarOfStorm_Cooldown: bonus.decrease.cooldown = 300 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Storm", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Storm", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_EnergyWave_Cooldown: bonus.decrease.cooldown = 1 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatDeathBeam_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Death Beam", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Death Beam", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatDeathBeam_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Death Beam", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Death Beam", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_HellsCore_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Hell's Core", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Hell's Core", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_HellsCore_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Hell's Core", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Hell's Core", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_EnergyWave_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_EnergyWave_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Energy Wave", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatFireWave_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Fire Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Fire Wave", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatFireWave_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Fire Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Fire Wave", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_RageOfTheSkies_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Rage of the Skies", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Rage of the Skies", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_RageOfTheSkies_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Rage of the Skies", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Rage of the Skies", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatEnergyBeam_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Energy Beam", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Energy Beam", bonus)); break; case WheelGemSupremeModifier_t::Sorcerer_GreatEnergyBeam_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Energy Beam", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Great Energy Beam", bonus)); break; case WheelGemSupremeModifier_t::Druid_AvatarOfNature_Cooldown: bonus.decrease.cooldown = 300 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Nature", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Avatar of Nature", bonus)); break; case WheelGemSupremeModifier_t::Druid_NaturesEmbrace_Cooldown: bonus.decrease.cooldown = 5 * 1000; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Nature's Embrace", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Nature's Embrace", bonus)); break; case WheelGemSupremeModifier_t::Druid_TerraBurst_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Burst", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Burst", bonus)); break; case WheelGemSupremeModifier_t::Druid_TerraBurst_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Burst", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Burst", bonus)); break; case WheelGemSupremeModifier_t::Druid_IceBurst_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ice Burst", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ice Burst", bonus)); break; case WheelGemSupremeModifier_t::Druid_IceBurst_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ice Burst", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Ice Burst", bonus)); break; case WheelGemSupremeModifier_t::Druid_EternalWinter_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Eternal Winter", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Eternal Winter", bonus)); break; case WheelGemSupremeModifier_t::Druid_EternalWinter_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Eternal Winter", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Eternal Winter", bonus)); break; case WheelGemSupremeModifier_t::Druid_TerraWave_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Wave", bonus)); break; case WheelGemSupremeModifier_t::Druid_TerraWave_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Terra Wave", bonus)); break; case WheelGemSupremeModifier_t::Druid_StrongIceWave_DamageIncrease: bonus.increase.damage = 25; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ice Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ice Wave", bonus)); break; case WheelGemSupremeModifier_t::Druid_StrongIceWave_CriticalExtraDamage: bonus.increase.criticalDamage = 8; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ice Wave", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Strong Ice Wave", bonus)); break; case WheelGemSupremeModifier_t::Druid_HealFriend_HealingIncrease: bonus.increase.heal = 10; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Heal Friend", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Heal Friend", bonus)); break; case WheelGemSupremeModifier_t::Druid_MassHealing_HealingIncrease: bonus.increase.heal = 10; - m_strategies.push_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Mass Healing", bonus)); + m_strategies.emplace_back(std::make_unique<GemModifierSpellBonusStrategy>(m_wheel, "Mass Healing", bonus)); break; default: g_logger().error("WheelModifierContext::setStrategy: Invalid supreme modifier: {}", static_cast<uint8_t>(modifier)); } } -void WheelModifierContext::executeStrategies() { +void WheelModifierContext::executeStrategies() const { for (const auto &strategy : m_strategies) { strategy->execute(); } diff --git a/src/creatures/players/wheel/wheel_gems.hpp b/src/creatures/players/wheel/wheel_gems.hpp index 030bcc5df5d..a25204a9c7e 100644 --- a/src/creatures/players/wheel/wheel_gems.hpp +++ b/src/creatures/players/wheel/wheel_gems.hpp @@ -181,7 +181,7 @@ class GemModifierStrategy { PlayerWheel &m_wheel; }; -class GemModifierResistanceStrategy : public GemModifierStrategy { +class GemModifierResistanceStrategy final : public GemModifierStrategy { public: explicit GemModifierResistanceStrategy(PlayerWheel &wheel, CombatType_t combatType, int32_t resistance) : GemModifierStrategy(wheel), @@ -195,7 +195,7 @@ class GemModifierResistanceStrategy : public GemModifierStrategy { int32_t m_resistance; }; -class GemModifierStatStrategy : public GemModifierStrategy { +class GemModifierStatStrategy final : public GemModifierStrategy { public: explicit GemModifierStatStrategy(PlayerWheel &wheel, WheelStat_t stat, int32_t value) : GemModifierStrategy(wheel), @@ -209,7 +209,7 @@ class GemModifierStatStrategy : public GemModifierStrategy { int32_t m_value; }; -class GemModifierRevelationStrategy : public GemModifierStrategy { +class GemModifierRevelationStrategy final : public GemModifierStrategy { public: explicit GemModifierRevelationStrategy(PlayerWheel &wheel, WheelGemAffinity_t affinity, [[maybe_unused]] uint16_t value) : GemModifierStrategy(wheel), @@ -222,9 +222,9 @@ class GemModifierRevelationStrategy : public GemModifierStrategy { uint16_t m_value {}; }; -class GemModifierSpellBonusStrategy : public GemModifierStrategy { +class GemModifierSpellBonusStrategy final : public GemModifierStrategy { public: - explicit GemModifierSpellBonusStrategy(PlayerWheel &wheel, std::string spellName, WheelSpells::Bonus bonus) : + explicit GemModifierSpellBonusStrategy(PlayerWheel &wheel, std::string spellName, const WheelSpells::Bonus &bonus) : GemModifierStrategy(wheel), m_spellName(std::move(spellName)), m_bonus(bonus) { } @@ -248,7 +248,7 @@ class WheelModifierContext { m_strategies.clear(); } - void executeStrategies(); + void executeStrategies() const; private: std::vector<std::unique_ptr<GemModifierStrategy>> m_strategies; @@ -323,9 +323,9 @@ class WheelModifierContext { }, }; - auto modifierIt = stats.find(modifier); + const auto modifierIt = stats.find(modifier); if (modifierIt != stats.end()) { - auto vocationIt = modifierIt->second.find(vocation); + const auto vocationIt = modifierIt->second.find(vocation); if (vocationIt != modifierIt->second.end()) { return vocationIt->second; } @@ -399,9 +399,9 @@ class WheelModifierContext { } }; - auto modifierIt = stats.find(modifier); + const auto modifierIt = stats.find(modifier); if (modifierIt != stats.end()) { - auto vocationIt = modifierIt->second.find(vocation); + const auto vocationIt = modifierIt->second.find(vocation); if (vocationIt != modifierIt->second.end()) { return vocationIt->second; } @@ -473,9 +473,9 @@ class WheelModifierContext { } }; - auto modifierIt = stats.find(modifier); + const auto modifierIt = stats.find(modifier); if (modifierIt != stats.end()) { - auto vocationIt = modifierIt->second.find(vocation); + const auto vocationIt = modifierIt->second.find(vocation); if (vocationIt != modifierIt->second.end()) { return vocationIt->second; } diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index ee0f68de332..62cae24f909 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -31,7 +31,7 @@ void Teleport::serializeAttr(PropWriteStream &propWriteStream) const { propWriteStream.write<uint8_t>(destPos.z); } -ReturnValue Teleport::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature>) { +ReturnValue Teleport::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> &) { return RETURNVALUE_NOTPOSSIBLE; } @@ -39,7 +39,7 @@ ReturnValue Teleport::queryMaxCount(int32_t, const std::shared_ptr<Thing> &, uin return RETURNVALUE_NOTPOSSIBLE; } -ReturnValue Teleport::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> /*= nullptr */) { +ReturnValue Teleport::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> & /*= nullptr */) { return RETURNVALUE_NOERROR; } @@ -66,7 +66,7 @@ void Teleport::addThing(std::shared_ptr<Thing> thing) { return addThing(0, thing); } -void Teleport::addThing(int32_t, std::shared_ptr<Thing> thing) { +void Teleport::addThing(int32_t, const std::shared_ptr<Thing> &thing) { if (!thing) { return; } diff --git a/src/game/movement/teleport.hpp b/src/game/movement/teleport.hpp index 1cd2b5fdae6..3b4248e2c37 100644 --- a/src/game/movement/teleport.hpp +++ b/src/game/movement/teleport.hpp @@ -38,13 +38,13 @@ class Teleport final : public Item, public Cylinder { bool checkInfinityLoop(const std::shared_ptr<Tile> &destTile); // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index 2ff29c8a872..7d36730d060 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -440,7 +440,7 @@ void Container::onRemoveContainerItem(uint32_t index, const std::shared_ptr<Item } } -ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> &addThing, uint32_t addCount, uint32_t flags, std::shared_ptr<Creature> actor /* = nullptr*/) { +ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> &addThing, uint32_t addCount, uint32_t flags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { // a child container is querying, since we are the top container (not carried by a player) @@ -579,7 +579,7 @@ ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr<Thing> return RETURNVALUE_NOERROR; } -ReturnValue Container::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor /*= nullptr */) { +ReturnValue Container::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor /*= nullptr */) { int32_t index = getThingIndex(thing); if (index == -1) { g_logger().debug("{} - Failed to get thing index", __FUNCTION__); @@ -683,7 +683,7 @@ void Container::addThing(std::shared_ptr<Thing> thing) { return addThing(0, thing); } -void Container::addThing(int32_t index, std::shared_ptr<Thing> thing) { +void Container::addThing(int32_t index, const std::shared_ptr<Thing> &thing) { if (!thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index 4780bf27646..7fa35055305 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -138,13 +138,13 @@ class Container : public Item, public Cylinder { } // cylinder implementations - virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) final; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) final; void addThing(std::shared_ptr<Thing> thing) final; - void addThing(int32_t index, std::shared_ptr<Thing> thing) final; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) final; void addItemBack(const std::shared_ptr<Item> &item); void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) final; diff --git a/src/items/containers/depot/depotchest.cpp b/src/items/containers/depot/depotchest.cpp index 579366d122b..049190f849a 100644 --- a/src/items/containers/depot/depotchest.cpp +++ b/src/items/containers/depot/depotchest.cpp @@ -19,7 +19,7 @@ DepotChest::DepotChest(uint16_t type) : pagination = true; } -ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor /* = nullptr*/) { +ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; diff --git a/src/items/containers/depot/depotchest.hpp b/src/items/containers/depot/depotchest.hpp index a1693af3b86..7b357540d8a 100644 --- a/src/items/containers/depot/depotchest.hpp +++ b/src/items/containers/depot/depotchest.hpp @@ -21,7 +21,7 @@ class DepotChest final : public Container { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; diff --git a/src/items/containers/depot/depotlocker.cpp b/src/items/containers/depot/depotlocker.cpp index b9b77fab8f0..087cb293135 100644 --- a/src/items/containers/depot/depotlocker.cpp +++ b/src/items/containers/depot/depotlocker.cpp @@ -24,7 +24,7 @@ Attr_ReadValue DepotLocker::readAttr(AttrTypes_t attr, PropStream &propStream) { return Item::readAttr(attr, propStream); } -ReturnValue DepotLocker::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature>) { +ReturnValue DepotLocker::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> &) { return RETURNVALUE_NOTENOUGHROOM; } diff --git a/src/items/containers/depot/depotlocker.hpp b/src/items/containers/depot/depotlocker.hpp index 4079091c22d..a4b2a3f48bf 100644 --- a/src/items/containers/depot/depotlocker.hpp +++ b/src/items/containers/depot/depotlocker.hpp @@ -33,7 +33,7 @@ class DepotLocker final : public Container { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; diff --git a/src/items/containers/inbox/inbox.cpp b/src/items/containers/inbox/inbox.cpp index e0ab1e3ab29..7376c87ff83 100644 --- a/src/items/containers/inbox/inbox.cpp +++ b/src/items/containers/inbox/inbox.cpp @@ -17,7 +17,7 @@ Inbox::Inbox(uint16_t type) : maxInboxItems = std::numeric_limits<uint16_t>::max(); } -ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t flags, std::shared_ptr<Creature>) { +ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t flags, const std::shared_ptr<Creature> &) { int32_t addCount = 0; if (!hasBitSet(FLAG_NOLIMIT, flags)) { diff --git a/src/items/containers/inbox/inbox.hpp b/src/items/containers/inbox/inbox.hpp index 6d3423f1824..731920f1ded 100644 --- a/src/items/containers/inbox/inbox.hpp +++ b/src/items/containers/inbox/inbox.hpp @@ -20,7 +20,7 @@ class Inbox final : public Container { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index ca019a7f7b8..622460419d0 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -15,7 +15,7 @@ #include "game/scheduling/save_manager.hpp" #include "map/spectators.hpp" -ReturnValue Mailbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, std::shared_ptr<Creature>) { +ReturnValue Mailbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, const std::shared_ptr<Creature> &) { const auto item = thing->getItem(); if (item && Mailbox::canSend(item)) { return RETURNVALUE_NOERROR; @@ -28,7 +28,7 @@ ReturnValue Mailbox::queryMaxCount(int32_t, const std::shared_ptr<Thing> &, uint return RETURNVALUE_NOERROR; } -ReturnValue Mailbox::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> /*= nullptr */) { +ReturnValue Mailbox::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> & /*= nullptr */) { return RETURNVALUE_NOTPOSSIBLE; } @@ -40,7 +40,7 @@ void Mailbox::addThing(std::shared_ptr<Thing> thing) { return addThing(0, thing); } -void Mailbox::addThing(int32_t, std::shared_ptr<Thing> thing) { +void Mailbox::addThing(int32_t, const std::shared_ptr<Thing> &thing) { if (!thing) { return; } diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index ffa9b408b6a..f2734726cec 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -26,13 +26,13 @@ class Mailbox final : public Item, public Cylinder { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/items/containers/rewards/reward.cpp b/src/items/containers/rewards/reward.cpp index f1f9424a128..a89f6543aa5 100644 --- a/src/items/containers/rewards/reward.cpp +++ b/src/items/containers/rewards/reward.cpp @@ -18,7 +18,7 @@ Reward::Reward() : pagination = true; } -ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, std::shared_ptr<Creature> actor /* = nullptr*/) { +ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor /* = nullptr*/) { if (actor) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/items/containers/rewards/reward.hpp b/src/items/containers/rewards/reward.hpp index 61a589a73bd..47925dab2e3 100644 --- a/src/items/containers/rewards/reward.hpp +++ b/src/items/containers/rewards/reward.hpp @@ -20,7 +20,7 @@ class Reward : public Container { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) final; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) final; void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; diff --git a/src/items/containers/rewards/rewardchest.cpp b/src/items/containers/rewards/rewardchest.cpp index dc1bac1d708..b203115199f 100644 --- a/src/items/containers/rewards/rewardchest.cpp +++ b/src/items/containers/rewards/rewardchest.cpp @@ -18,7 +18,7 @@ RewardChest::RewardChest(uint16_t type) : pagination = true; } -ReturnValue RewardChest::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> actor /* = nullptr*/) { +ReturnValue RewardChest::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor /* = nullptr*/) { if (actor) { return RETURNVALUE_NOTPOSSIBLE; } diff --git a/src/items/containers/rewards/rewardchest.hpp b/src/items/containers/rewards/rewardchest.hpp index 7de4854d910..574f5c6b1fa 100644 --- a/src/items/containers/rewards/rewardchest.hpp +++ b/src/items/containers/rewards/rewardchest.hpp @@ -20,7 +20,7 @@ class RewardChest final : public Container { } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) final; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) final; void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; diff --git a/src/items/cylinder.hpp b/src/items/cylinder.hpp index 4a352008904..07099a0aa8c 100644 --- a/src/items/cylinder.hpp +++ b/src/items/cylinder.hpp @@ -30,7 +30,7 @@ class Cylinder : virtual public Thing { * \param actor the creature trying to add the thing * \returns ReturnValue holds the return value */ - virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) = 0; + virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) = 0; /** * Query the cylinder how much it can accept @@ -49,9 +49,10 @@ class Cylinder : virtual public Thing { * \param thing the object to move/remove * \param count is the amount that we want to remove * \param flags optional flags to modify the default behaviour + * \param * \returns ReturnValue holds the return value */ - virtual ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> = nullptr) = 0; + virtual ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) = 0; /** * Query the destination cylinder @@ -76,7 +77,7 @@ class Cylinder : virtual public Thing { * \param index points to the destination index (inventory slot/container position) * \param thing is the object to add */ - virtual void addThing(int32_t index, std::shared_ptr<Thing> thing) = 0; + virtual void addThing(int32_t index, const std::shared_ptr<Thing> &thing) = 0; /** * Update the item count or type for an object @@ -176,13 +177,13 @@ class VirtualCylinder final : public Cylinder { public: static std::shared_ptr<VirtualCylinder> virtualCylinder; - virtual ReturnValue queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> = nullptr) override { + virtual ReturnValue queryAdd(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> & = nullptr) override { return RETURNVALUE_NOTPOSSIBLE; } virtual ReturnValue queryMaxCount(int32_t, const std::shared_ptr<Thing> &, uint32_t, uint32_t &, uint32_t) override { return RETURNVALUE_NOTPOSSIBLE; } - virtual ReturnValue queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> = nullptr) override { + virtual ReturnValue queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor = nullptr) override { return RETURNVALUE_NOTPOSSIBLE; } virtual std::shared_ptr<Cylinder> queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>*, uint32_t &) override { @@ -190,7 +191,7 @@ class VirtualCylinder final : public Cylinder { } virtual void addThing(std::shared_ptr<Thing>) override { } - virtual void addThing(int32_t, std::shared_ptr<Thing>) override { } + virtual void addThing(int32_t, const std::shared_ptr<Thing> &) override { } virtual void updateThing(const std::shared_ptr<Thing> &, uint16_t, uint32_t) override { } virtual void replaceThing(uint32_t, const std::shared_ptr<Thing> &) override { } virtual void removeThing(const std::shared_ptr<Thing> &, uint32_t) override { } diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 76226211dba..76e727ffb46 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -573,7 +573,7 @@ void Tile::onUpdateTile(const CreatureVector &spectators) { } } -ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t tileFlags, std::shared_ptr<Creature>) { +ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t tileFlags, const std::shared_ptr<Creature> &) { if (hasBitSet(FLAG_NOLIMIT, tileFlags)) { return RETURNVALUE_NOERROR; } @@ -849,7 +849,7 @@ ReturnValue Tile::queryMaxCount(int32_t, const std::shared_ptr<Thing> &, uint32_ return RETURNVALUE_NOERROR; } -ReturnValue Tile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr<Creature> /*= nullptr */) { +ReturnValue Tile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> & /*= nullptr */) { int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; @@ -991,7 +991,7 @@ void Tile::addThing(std::shared_ptr<Thing> thing) { addThing(0, thing); } -void Tile::addThing(int32_t, std::shared_ptr<Thing> thing) { +void Tile::addThing(int32_t, const std::shared_ptr<Thing> &thing) { if (!thing) { return; // RETURNVALUE_NOTPOSSIBLE } diff --git a/src/items/tile.hpp b/src/items/tile.hpp index c2bf20a38f6..a9ae3c33d09 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -207,15 +207,15 @@ class Tile : public Cylinder, public SharedObject { int32_t getStackposOfItem(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item) const; // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; std::vector<std::shared_ptr<Tile>> getSurroundingTiles(); void addThing(std::shared_ptr<Thing> thing) final; - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateTileFlags(const std::shared_ptr<Item> &item); void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) final; diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index 0a0efc72aad..abba6d3968e 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -12,7 +12,7 @@ #include "items/trashholder.hpp" #include "game/game.hpp" -ReturnValue TrashHolder::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, std::shared_ptr<Creature> actor) { +ReturnValue TrashHolder::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor) { const auto item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOERROR; @@ -28,7 +28,7 @@ ReturnValue TrashHolder::queryMaxCount(int32_t, const std::shared_ptr<Thing> &, return RETURNVALUE_NOERROR; } -ReturnValue TrashHolder::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, std::shared_ptr<Creature> /*= nullptr*/) { +ReturnValue TrashHolder::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> & /*= nullptr */) { return RETURNVALUE_NOTPOSSIBLE; } @@ -40,7 +40,7 @@ void TrashHolder::addThing(std::shared_ptr<Thing> thing) { return addThing(0, thing); } -void TrashHolder::addThing(int32_t, std::shared_ptr<Thing> thing) { +void TrashHolder::addThing(int32_t, const std::shared_ptr<Thing> &thing) { if (!thing) { return; } diff --git a/src/items/trashholder.hpp b/src/items/trashholder.hpp index 2ea833fd808..44a0d876f34 100644 --- a/src/items/trashholder.hpp +++ b/src/items/trashholder.hpp @@ -21,18 +21,18 @@ class TrashHolder final : public Item, public Cylinder { return static_self_cast<TrashHolder>(); } - std::shared_ptr<Cylinder> getCylinder() final { + std::shared_ptr<Cylinder> getCylinder() override { return getTrashHolder(); } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 0064bd17b97..46588837691 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -20,7 +20,7 @@ HouseTile::HouseTile(int32_t initX, int32_t initY, int32_t initZ, std::shared_ptr<House> initHouse) : DynamicTile(initX, initY, initZ), house(std::move(initHouse)) { } -void HouseTile::addThing(int32_t index, std::shared_ptr<Thing> thing) { +void HouseTile::addThing(int32_t index, const std::shared_ptr<Thing> &thing) { Tile::addThing(index, thing); if (!thing || !thing->getParent()) { @@ -62,7 +62,7 @@ void HouseTile::updateHouse(const std::shared_ptr<Item> &item) { } } -ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, std::shared_ptr<Creature> actor /* = nullptr*/) { +ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { if (std::shared_ptr<Creature> creature = thing->getCreature()) { if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { @@ -116,7 +116,7 @@ std::shared_ptr<Cylinder> HouseTile::queryDestination(int32_t &index, const std: return Tile::queryDestination(index, thing, destItem, tileFlags); } -ReturnValue HouseTile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor /*= nullptr*/) { +ReturnValue HouseTile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor /*= nullptr */) { const auto item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; diff --git a/src/map/house/housetile.hpp b/src/map/house/housetile.hpp index 69b17fa3482..56944b08672 100644 --- a/src/map/house/housetile.hpp +++ b/src/map/house/housetile.hpp @@ -18,13 +18,13 @@ class HouseTile final : public DynamicTile { HouseTile(int32_t x, int32_t y, int32_t z, std::shared_ptr<House> house); // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; - ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, std::shared_ptr<Creature> actor = nullptr) override; + ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - void addThing(int32_t index, std::shared_ptr<Thing> thing) override; + void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void internalAddThing(uint32_t index, const std::shared_ptr<Thing> &thing) override; std::shared_ptr<House> getHouse() override { From a5ea2d3a7b7f8c120659f4ea6faf00916fa3364d Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Sat, 7 Sep 2024 23:27:15 -0400 Subject: [PATCH 23/34] update 07/09/2024 --- src/canary_server.cpp | 14 +- src/canary_server.hpp | 8 +- src/creatures/players/player.cpp | 62 +++-- src/game/game.cpp | 6 +- src/items/item.hpp | 2 +- src/lua/callbacks/events_callbacks.cpp | 4 +- src/lua/creature/movement.cpp | 6 +- src/lua/creature/raids.cpp | 4 +- .../functions/core/game/global_functions.cpp | 4 +- src/lua/functions/core/libs/kv_functions.cpp | 2 +- .../creatures/monster/loot_functions.cpp | 2 +- .../monster/monster_type_functions.cpp | 10 +- .../creatures/npc/npc_type_functions.cpp | 4 +- .../creatures/npc/shop_functions.cpp | 2 +- .../creatures/player/player_functions.cpp | 2 +- .../creatures/player/player_functions.hpp | 7 +- src/lua/functions/items/weapon_functions.hpp | 6 + src/lua/functions/lua_functions_loader.cpp | 32 +-- src/lua/functions/lua_functions_loader.hpp | 4 +- src/lua/functions/map/house_functions.cpp | 22 +- src/lua/functions/map/house_functions.hpp | 6 + src/lua/functions/map/map_functions.hpp | 9 +- src/lua/functions/map/position_functions.cpp | 26 +- src/lua/functions/map/position_functions.hpp | 6 + src/lua/functions/map/teleport_functions.cpp | 2 +- src/lua/functions/map/teleport_functions.hpp | 6 + src/lua/functions/map/tile_functions.cpp | 34 +-- src/lua/functions/map/tile_functions.hpp | 7 + src/lua/functions/map/town_functions.hpp | 8 +- src/lua/global/baseevents.cpp | 14 +- src/lua/global/globalevent.cpp | 16 +- src/lua/global/globalevent.hpp | 2 +- src/lua/modules/modules.cpp | 28 +- src/lua/modules/modules.hpp | 8 +- src/lua/scripts/lua_environment.cpp | 20 +- src/lua/scripts/lua_environment.hpp | 10 +- src/lua/scripts/luascript.cpp | 20 +- src/lua/scripts/luascript.hpp | 10 +- src/lua/scripts/script_environment.cpp | 26 +- src/lua/scripts/script_environment.hpp | 4 +- src/lua/scripts/scripts.cpp | 6 +- src/lua/scripts/scripts.hpp | 2 +- src/map/house/house.cpp | 118 ++++---- src/map/house/house.hpp | 12 +- src/map/house/housetile.cpp | 20 +- src/map/house/housetile.hpp | 2 +- src/map/map.cpp | 66 ++--- src/map/map.hpp | 4 +- src/map/mapcache.cpp | 20 +- src/map/mapcache.hpp | 10 +- src/map/spectators.hpp | 4 +- src/map/town.hpp | 8 +- src/map/utils/astarnodes.cpp | 16 +- src/map/utils/mapsector.cpp | 4 +- src/pch.hpp | 6 +- src/security/argon.cpp | 20 +- src/security/rsa.cpp | 28 +- src/server/network/connection/connection.cpp | 71 ++--- src/server/network/message/networkmessage.cpp | 6 +- src/server/network/message/outputmessage.cpp | 2 +- src/server/network/protocol/protocol.cpp | 254 ++++++++++++------ src/server/network/protocol/protocol.hpp | 29 +- src/server/network/protocol/protocolgame.cpp | 14 +- src/server/network/protocol/protocollogin.cpp | 9 +- src/server/network/protocol/protocollogin.hpp | 6 +- .../network/protocol/protocolstatus.cpp | 24 +- .../network/protocol/protocolstatus.hpp | 2 +- src/server/network/webhook/webhook.cpp | 24 +- src/server/server.cpp | 26 +- src/server/server.hpp | 10 +- src/utils/arraylist.hpp | 38 +-- src/utils/benchmark.hpp | 1 - src/utils/hash.hpp | 12 +- src/utils/lockfree.hpp | 2 +- src/utils/pugicast.hpp | 2 +- src/utils/simd.hpp | 2 +- src/utils/tools.cpp | 241 ++++++++++------- src/utils/tools.hpp | 2 +- src/utils/vectorset.hpp | 18 +- src/utils/vectorsort.hpp | 14 +- src/utils/wildcardtree.cpp | 22 +- src/utils/wildcardtree.hpp | 2 +- 82 files changed, 934 insertions(+), 710 deletions(-) diff --git a/src/canary_server.cpp b/src/canary_server.cpp index 1460a450f67..5a583f23387 100644 --- a/src/canary_server.cpp +++ b/src/canary_server.cpp @@ -60,7 +60,7 @@ int CanaryServer::run() { try { loadConfigLua(); - logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) ? " and 10x allowed!" : ""); + logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL, "CanaryServer::run") ? " and 10x allowed!" : ""); #ifdef FEATURE_METRICS metrics::Options metricsOptions; metricsOptions.enablePrometheusExporter = g_configManager().getBoolean(METRICS_ENABLE_PROMETHEUS, __FUNCTION__); @@ -100,7 +100,7 @@ int CanaryServer::run() { g_game().start(&serviceManager); g_game().setGameState(GAME_STATE_NORMAL); - if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE, __FUNCTION__)) { + if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE, "CanaryServer::run")) { g_game().setGameState(GAME_STATE_CLOSED); g_logger().warn("Initialized in maintain mode!"); g_webhook().sendMessage(":yellow_square: Server is now **online** _(access restricted to staff)_"); @@ -142,7 +142,7 @@ int CanaryServer::run() { return EXIT_SUCCESS; } -void CanaryServer::setWorldType() { +void CanaryServer::setWorldType() const { const std::string worldType = asLowerCaseString(g_configManager().getString(WORLD_TYPE, __FUNCTION__)); if (worldType == "pvp") { g_game().setWorldType(WORLD_TYPE_PVP); @@ -176,9 +176,9 @@ void CanaryServer::loadMaps() const { } } -void CanaryServer::setupHousesRent() { +void CanaryServer::setupHousesRent() const { RentPeriod_t rentPeriod; - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); + const std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); if (strRentPeriod == "yearly") { rentPeriod = RENTPERIOD_YEARLY; @@ -269,7 +269,7 @@ std::string CanaryServer::getCompiler() { #endif } -void CanaryServer::loadConfigLua() { +void CanaryServer::loadConfigLua() const { std::string configName = "config.lua"; // Check if config or config.dist exist std::ifstream c_test("./" + configName); @@ -323,7 +323,7 @@ void CanaryServer::initializeDatabase() const { } } -void CanaryServer::loadModules() { +void CanaryServer::loadModules() const { // If "USE_ANY_DATAPACK_FOLDER" is set to true then you can choose any datapack folder for your server const auto useAnyDatapack = g_configManager().getBoolean(USE_ANY_DATAPACK_FOLDER, __FUNCTION__); auto datapackName = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); diff --git a/src/canary_server.hpp b/src/canary_server.hpp index dbcd7cb2212..01435e72240 100644 --- a/src/canary_server.hpp +++ b/src/canary_server.hpp @@ -60,11 +60,11 @@ class CanaryServer { static std::string getCompiler(); static std::string getPlatform(); - void loadConfigLua(); + void loadConfigLua() const; void initializeDatabase() const; - void loadModules(); - void setWorldType(); + void loadModules() const; + void setWorldType() const; void loadMaps() const; - void setupHousesRent(); + void setupHousesRent() const; void modulesLoadHelper(bool loaded, std::string moduleName) const; }; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index b1ea534f65a..3cf09df3692 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -1000,8 +1000,7 @@ bool Player::canWalkthrough(const std::shared_ptr<Creature> &creature) { thisPlayer->setLastWalkthroughPosition(creature->getPosition()); return true; - } - if (npc) { + } else if (npc) { const auto &tile = npc->getTile(); const auto &houseTile = std::dynamic_pointer_cast<HouseTile>(tile); return (houseTile != nullptr); @@ -1028,13 +1027,13 @@ bool Player::canWalkthroughEx(const std::shared_ptr<Creature> &creature) const { if (player) { const auto &playerTile = player->getTile(); return playerTile && (playerTile->hasFlag(TILESTATE_NOPVPZONE) || playerTile->hasFlag(TILESTATE_PROTECTIONZONE) || player->getLevel() <= static_cast<uint32_t>(g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__)) || g_game().getWorldType() == WORLD_TYPE_NO_PVP); - } - if (npc) { + } else if (npc) { const auto &tile = npc->getTile(); const auto &houseTile = std::dynamic_pointer_cast<HouseTile>(tile); return (houseTile != nullptr); + } else { + return false; } - return false; } void Player::onReceiveMail() { @@ -2675,16 +2674,22 @@ BlockType_t Player::blockHit(const std::shared_ptr<Creature> &attacker, const Co } } - for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { - ImbuementInfo imbuementInfo; - if (!item->getImbuementInfo(slotid, &imbuementInfo)) { - continue; - } + if (item) { + for (uint8_t slotid = 0; slotid < item->getImbuementSlot(); slotid++) { + ImbuementInfo imbuementInfo; + if (!item) { + continue; + } + + if (!item->getImbuementInfo(slotid, &imbuementInfo)) { + continue; + } - const int16_t &imbuementAbsorbPercent = imbuementInfo.imbuement->absorbPercent[combatTypeToIndex(combatType)]; + const int16_t &imbuementAbsorbPercent = imbuementInfo.imbuement->absorbPercent[combatTypeToIndex(combatType)]; - if (imbuementAbsorbPercent != 0) { - damage -= std::ceil(damage * (imbuementAbsorbPercent / 100.)); + if (imbuementAbsorbPercent != 0) { + damage -= std::ceil(damage * (imbuementAbsorbPercent / 100.)); + } } } } @@ -2894,10 +2899,10 @@ void Player::death(const std::shared_ptr<Creature> &lastHitCreature) { const auto &condition = *it; // isSupress block to delete spells conditions (ensures that the player cannot, for example, reset the cooldown time of the familiar and summon several) if (condition->isPersistent() && condition->isRemovableOnDeath()) { - it = conditions.erase(it); - condition->endCondition(static_self_cast<Player>()); onEndCondition(condition->getType()); + + it = conditions.erase(it); } else { ++it; } @@ -2909,10 +2914,10 @@ void Player::death(const std::shared_ptr<Creature> &lastHitCreature) { while (it != end) { const auto &condition = *it; if (condition->isPersistent()) { - it = conditions.erase(it); - condition->endCondition(static_self_cast<Player>()); onEndCondition(condition->getType()); + + it = conditions.erase(it); } else { ++it; } @@ -3553,8 +3558,9 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh index = INDEX_WHEREEVER; *destItem = nullptr; return subCylinder; + } else { + return getPlayer(); } - return getPlayer(); } void Player::addThing(int32_t index, const std::shared_ptr<Thing> &thing) { @@ -4209,20 +4215,27 @@ void Player::postAddNotification(const std::shared_ptr<Thing> &thing, const std: } void Player::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link /*= LINK_OWNER*/) { - if (link == LINK_OWNER) { - // calling movement scripts - g_moveEvents().onPlayerDeEquip(getPlayer(), thing->getItem(), static_cast<Slots_t>(index)); + if (!thing || !newParent) { + return; } + const auto copyThing = thing; + const auto copyNewParent = newParent; + + if (link == LINK_OWNER) { + if (const auto &item = copyThing->getItem()) { + g_moveEvents().onPlayerDeEquip(getPlayer(), item, static_cast<Slots_t>(index)); + } + } bool requireListUpdate = true; if (link == LINK_OWNER || link == LINK_TOPPARENT) { - const auto &i = (newParent ? newParent->getItem() : nullptr); + const auto &i = (copyNewParent ? copyNewParent->getItem() : nullptr); const auto &container = i ? i->getContainer() : nullptr; if (container) { requireListUpdate = container->getHoldingPlayer() != getPlayer(); } else { - requireListUpdate = newParent != getPlayer(); + requireListUpdate = copyNewParent != getPlayer(); } updateInventoryWeight(); @@ -4231,7 +4244,7 @@ void Player::postRemoveNotification(const std::shared_ptr<Thing> &thing, const s sendStats(); } - if (const auto &item = thing->getItem()) { + if (const auto &item = copyThing->getItem()) { if (const auto &container = item->getContainer()) { checkLootContainers(container); @@ -4272,7 +4285,6 @@ void Player::postRemoveNotification(const std::shared_ptr<Thing> &thing, const s } } } - // i will keep this function so it can be reviewed bool Player::updateSaleShopList(const std::shared_ptr<Item> &item) { const uint16_t itemId = item->getID(); diff --git a/src/game/game.cpp b/src/game/game.cpp index bb216f131c9..d2a2c5567ff 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -534,9 +534,9 @@ void Game::start(ServiceManager* manager) { ); } - // g_dispatcher().cycleEvent( - // 5000, [this] { teste(); }, "Calling GC" - // ); + g_dispatcher().cycleEvent( + 5000, [this] { teste(); }, "Calling GC" + ); } void Game::teste() const { diff --git a/src/items/item.hpp b/src/items/item.hpp index f84896fca5a..96d90ac8195 100644 --- a/src/items/item.hpp +++ b/src/items/item.hpp @@ -630,7 +630,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return true; } virtual void onRemoved(); - virtual void onTradeEvent(TradeEvents_t, std::shared_ptr<Player>) { } + virtual void onTradeEvent(TradeEvents_t, const std::shared_ptr<Player>&) { } virtual void startDecaying(); virtual void stopDecaying(); diff --git a/src/lua/callbacks/events_callbacks.cpp b/src/lua/callbacks/events_callbacks.cpp index d8ab997d416..51748298781 100644 --- a/src/lua/callbacks/events_callbacks.cpp +++ b/src/lua/callbacks/events_callbacks.cpp @@ -29,7 +29,7 @@ EventsCallbacks &EventsCallbacks::getInstance() { } void EventsCallbacks::addCallback(const std::shared_ptr<EventCallback> &callback) { - m_callbacks.push_back(callback); + m_callbacks.emplace_back(callback); } std::vector<std::shared_ptr<EventCallback>> EventsCallbacks::getCallbacks() const { @@ -43,7 +43,7 @@ std::vector<std::shared_ptr<EventCallback>> EventsCallbacks::getCallbacksByType( continue; } - eventCallbacks.push_back(callback); + eventCallbacks.emplace_back(callback); } return eventCallbacks; diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index f317a7a6deb..d0417d709f4 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -126,7 +126,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, int3 auto it = moveListMap.find(id); if (it == moveListMap.end()) { MoveEventList moveEventList; - moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent); + moveEventList.moveEvent[moveEvent->getEventType()].emplace_back(moveEvent); moveListMap[id] = moveEventList; return true; } else { @@ -245,7 +245,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, cons auto it = moveListMap.find(position); if (it == moveListMap.end()) { MoveEventList moveEventList; - moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent); + moveEventList.moveEvent[moveEvent->getEventType()].emplace_back(moveEvent); moveListMap[position] = moveEventList; return true; } else { @@ -260,7 +260,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, cons return false; } - moveEventList.push_back(moveEvent); + moveEventList.emplace_back(moveEvent); return true; } } diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index c0c64e75e06..65b21fea7b2 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -83,7 +83,7 @@ bool Raids::loadFromXml() { auto newRaid = std::make_shared<Raid>(name, interval, margin, repeat); if (newRaid->loadFromXml(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/" + file)) { - raidList.push_back(newRaid); + raidList.emplace_back(newRaid); } else { g_logger().error("{} - Failed to load raid: {}", __FUNCTION__, name); } @@ -199,7 +199,7 @@ bool Raid::loadFromXml(const std::string &filename) { } if (event->configureRaidEvent(eventNode)) { - raidEvents.push_back(event); + raidEvents.emplace_back(event); } else { g_logger().error("{} - " "In file: {}, eventNode: {}", diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 4a7335eada9..840fb71a778 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -652,7 +652,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaTimerEventDesc eventDesc; for (int i = 0; i < parameters - 2; ++i) { // -2 because addEvent needs at least two parameters - eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX)); + eventDesc.parameters.emplace_back(luaL_ref(globalState, LUA_REGISTRYINDEX)); } uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2)); @@ -858,7 +858,7 @@ bool GlobalFunctions::getArea(lua_State* L, std::list<uint32_t> &list, uint32_t if (!isNumber(L, -1)) { return false; } - list.push_back(getNumber<uint32_t>(L, -1)); + list.emplace_back(getNumber<uint32_t>(L, -1)); lua_pop(L, 1); } diff --git a/src/lua/functions/core/libs/kv_functions.cpp b/src/lua/functions/core/libs/kv_functions.cpp index f145c2c0b5d..0e6200a5858 100644 --- a/src/lua/functions/core/libs/kv_functions.cpp +++ b/src/lua/functions/core/libs/kv_functions.cpp @@ -138,7 +138,7 @@ std::optional<ValueWrapper> KVFunctions::getValueWrapper(lua_State* L) { g_logger().warn("[{}] invalid param type", __FUNCTION__); return std::nullopt; } - array.push_back(value.value()); + array.emplace_back(value.value()); lua_pop(L, 1); } return ValueWrapper(array); diff --git a/src/lua/functions/creatures/monster/loot_functions.cpp b/src/lua/functions/creatures/monster/loot_functions.cpp index 47e0d8778e3..c3beb74d638 100644 --- a/src/lua/functions/creatures/monster/loot_functions.cpp +++ b/src/lua/functions/creatures/monster/loot_functions.cpp @@ -261,7 +261,7 @@ int LootFunctions::luaLootAddChildLoot(lua_State* L) { if (loot) { const auto childLoot = getUserdata<Loot>(L, 2); if (childLoot) { - loot->lootBlock.childLoot.push_back(childLoot->lootBlock); + loot->lootBlock.childLoot.emplace_back(childLoot->lootBlock); pushBoolean(L, true); } else { pushBoolean(L, false); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 7aa8ae926ec..005f65c877f 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -819,7 +819,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { - monsterType->info.attackSpells.push_back(std::move(sb)); + monsterType->info.attackSpells.emplace_back(std::move(sb)); } else { g_logger().warn("Monster: {}, cant load spell: {}", monsterType->name, spell->name); } @@ -881,7 +881,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { - monsterType->info.defenseSpells.push_back(std::move(sb)); + monsterType->info.defenseSpells.emplace_back(std::move(sb)); } else { g_logger().warn("Monster: {}, Cant load spell: {}", monsterType->name, spell->name); } @@ -958,7 +958,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddVoice(lua_State* L) { monsterType->info.yellSpeedTicks = getNumber<uint32_t>(L, 3); monsterType->info.yellChance = getNumber<uint32_t>(L, 4); voice.yellText = getBoolean(L, 5); - monsterType->info.voiceVector.push_back(voice); + monsterType->info.voiceVector.emplace_back(voice); pushBoolean(L, true); } else { lua_pushnil(L); @@ -1109,7 +1109,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSummon(lua_State* L) { summon.speed = getNumber<int32_t>(L, 3); summon.count = getNumber<int32_t>(L, 5, 1); summon.chance = getNumber<int32_t>(L, 4); - monsterType->info.summons.push_back(summon); + monsterType->info.summons.emplace_back(summon); pushBoolean(L, true); } else { lua_pushnil(L); @@ -1654,7 +1654,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSound(lua_State* L) { return 1; } - monsterType->info.soundVector.push_back(getNumber<SoundEffect_t>(L, 2)); + monsterType->info.soundVector.emplace_back(getNumber<SoundEffect_t>(L, 2)); pushBoolean(L, true); return 1; } diff --git a/src/lua/functions/creatures/npc/npc_type_functions.cpp b/src/lua/functions/creatures/npc/npc_type_functions.cpp index ef79b671a34..f52e8462232 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.cpp @@ -210,7 +210,7 @@ int NpcTypeFunctions::luaNpcTypeAddVoice(lua_State* L) { npcType->info.yellSpeedTicks = getNumber<uint32_t>(L, 3); npcType->info.yellChance = getNumber<uint32_t>(L, 4); voice.yellText = getBoolean(L, 5); - npcType->info.voiceVector.push_back(voice); + npcType->info.voiceVector.emplace_back(voice); pushBoolean(L, true); } else { lua_pushnil(L); @@ -546,7 +546,7 @@ int NpcTypeFunctions::luaNpcTypeAddSound(lua_State* L) { return 1; } - npcType->info.soundVector.push_back(getNumber<SoundEffect_t>(L, 2)); + npcType->info.soundVector.emplace_back(getNumber<SoundEffect_t>(L, 2)); pushBoolean(L, true); return 1; } diff --git a/src/lua/functions/creatures/npc/shop_functions.cpp b/src/lua/functions/creatures/npc/shop_functions.cpp index 122e249a8db..5fda97ccbd9 100644 --- a/src/lua/functions/creatures/npc/shop_functions.cpp +++ b/src/lua/functions/creatures/npc/shop_functions.cpp @@ -139,7 +139,7 @@ int ShopFunctions::luaShopSetStorageValue(lua_State* L) { int ShopFunctions::luaShopAddChildShop(lua_State* L) { // shop:addChildShop(shop) if (const auto &shop = getUserdataShared<Shop>(L, 1)) { - shop->shopBlock.childShop.push_back(getUserdataShared<Shop>(L, 2)->shopBlock); + shop->shopBlock.childShop.emplace_back(getUserdataShared<Shop>(L, 2)->shopBlock); } else { lua_pushnil(L); } diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index deb4e689576..5e062872348 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -3097,7 +3097,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { spells.reserve(30); for (auto &[key, spell] : g_spells().getInstantSpells()) { if (spell->canCast(player)) { - spells.push_back(spell); + spells.emplace_back(spell); } } diff --git a/src/lua/functions/creatures/player/player_functions.hpp b/src/lua/functions/creatures/player/player_functions.hpp index 7cee43424cd..722151bc247 100644 --- a/src/lua/functions/creatures/player/player_functions.hpp +++ b/src/lua/functions/creatures/player/player_functions.hpp @@ -17,7 +17,12 @@ #include "lua/functions/creatures/player/vocation_functions.hpp" class PlayerFunctions final : LuaScriptInterface { -private: + explicit PlayerFunctions(lua_State* L) + : LuaScriptInterface("PlayerFunctions") { + init(L); + } + ~PlayerFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Player", "Creature", PlayerFunctions::luaPlayerCreate); registerMetaMethod(L, "Player", "__eq", PlayerFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/weapon_functions.hpp b/src/lua/functions/items/weapon_functions.hpp index b7ac6fe6aaa..2aeef132710 100644 --- a/src/lua/functions/items/weapon_functions.hpp +++ b/src/lua/functions/items/weapon_functions.hpp @@ -13,6 +13,12 @@ class WeaponFunctions final : LuaScriptInterface { public: + explicit WeaponFunctions(lua_State* L) + : LuaScriptInterface("WeaponFunctions") { + init(L); + } + ~WeaponFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Weapon", "", WeaponFunctions::luaCreateWeapon); registerMethod(L, "Weapon", "action", WeaponFunctions::luaWeaponAction); diff --git a/src/lua/functions/lua_functions_loader.cpp b/src/lua/functions/lua_functions_loader.cpp index 224a3b8367b..728fd0f4fb6 100644 --- a/src/lua/functions/lua_functions_loader.cpp +++ b/src/lua/functions/lua_functions_loader.cpp @@ -98,11 +98,11 @@ int LuaFunctionsLoader::protectedCall(lua_State* L, int nargs, int nresults) { return ret; } - int error_index = lua_gettop(L) - nargs; + const int error_index = lua_gettop(L) - nargs; lua_pushcfunction(L, luaErrorHandler); lua_insert(L, error_index); - int ret = lua_pcall(L, nargs, nresults, error_index); + const int ret = lua_pcall(L, nargs, nresults, error_index); lua_remove(L, error_index); return ret; } @@ -134,7 +134,7 @@ void LuaFunctionsLoader::reportError(const char* function, const std::string &er } logMsg << "Error Description: " << error_desc << "\n"; if (stack_trace && scriptInterface) { - std::string stackTrace = scriptInterface->getStackTrace(error_desc); + const std::string stackTrace = scriptInterface->getStackTrace(error_desc); if (!stackTrace.empty() && stackTrace != "N/A") { logMsg << "Stack Trace:\n" << stackTrace << "\n"; @@ -147,7 +147,7 @@ void LuaFunctionsLoader::reportError(const char* function, const std::string &er int LuaFunctionsLoader::luaErrorHandler(lua_State* L) { const std::string &errorMessage = popString(L); - auto interface = getScriptEnv()->getScriptInterface(); + const auto interface = getScriptEnv()->getScriptInterface(); if (!interface) { g_logger().error("[{}]: LuaScriptInterface not found, error: {}", __FUNCTION__, errorMessage); return 0; @@ -280,13 +280,13 @@ void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std const std::string &weakName = name + "_weak"; - auto result = weakObjectTypes.emplace(name); + const auto result = weakObjectTypes.emplace(name); if (result.second) { luaL_getmetatable(L, name.c_str()); - int childMetatable = lua_gettop(L); + const int childMetatable = lua_gettop(L); luaL_newmetatable(L, weakName.c_str()); - int metatable = lua_gettop(L); + const int metatable = lua_gettop(L); for (static const std::vector<std::string> methodKeys = { "__index", "__metatable", "__eq" }; const std::string &metaKey : methodKeys) { @@ -295,7 +295,7 @@ void LuaFunctionsLoader::setWeakMetatable(lua_State* L, int32_t index, const std } for (static const std::vector<int> methodIndexes = { 'h', 'p', 't' }; - int metaIndex : methodIndexes) { + const int metaIndex : methodIndexes) { lua_rawgeti(L, childMetatable, metaIndex); lua_rawseti(L, metatable, metaIndex); } @@ -353,8 +353,8 @@ CombatDamage LuaFunctionsLoader::getCombatDamage(lua_State* L) { // Get std::string LuaFunctionsLoader::getFormatedLoggerMessage(lua_State* L) { - std::string format = getString(L, 1); - int n = lua_gettop(L); + const std::string format = getString(L, 1); + const int n = lua_gettop(L); fmt::dynamic_format_arg_store<fmt::format_context> args; for (int i = 2; i <= n; i++) { @@ -365,7 +365,7 @@ std::string LuaFunctionsLoader::getFormatedLoggerMessage(lua_State* L) { } else if (isBoolean(L, i)) { args.push_back(lua_toboolean(L, i) ? "true" : "false"); } else if (isUserdata(L, i)) { - LuaData_t userType = getUserdataType(L, i); + const LuaData_t userType = getUserdataType(L, i); args.push_back(getUserdataTypeName(userType)); } else if (isTable(L, i)) { args.push_back("table"); @@ -556,7 +556,7 @@ LuaData_t LuaFunctionsLoader::getUserdataType(lua_State* L, int32_t arg) { } lua_rawgeti(L, -1, 't'); - LuaData_t type = getNumber<LuaData_t>(L, -1); + const LuaData_t type = getNumber<LuaData_t>(L, -1); lua_pop(L, 2); return type; @@ -645,11 +645,11 @@ void LuaFunctionsLoader::registerClass(lua_State* L, const std::string &classNam lua_newtable(L); lua_pushvalue(L, -1); lua_setglobal(L, className.c_str()); - int methods = lua_gettop(L); + const int methods = lua_gettop(L); // methodsTable = {} lua_newtable(L); - int methodsTable = lua_gettop(L); + const int methodsTable = lua_gettop(L); if (newFunction) { // className.__call = newFunction @@ -671,7 +671,7 @@ void LuaFunctionsLoader::registerClass(lua_State* L, const std::string &classNam // className.metatable = {} luaL_newmetatable(L, className.c_str()); - int metatable = lua_gettop(L); + const int metatable = lua_gettop(L); // className.metatable.__metatable = className lua_pushvalue(L, methods); @@ -781,7 +781,7 @@ void LuaFunctionsLoader::registerSharedClass(lua_State* L, const std::string &cl } int LuaFunctionsLoader::luaGarbageCollection(lua_State* L) { - auto objPtr = static_cast<std::shared_ptr<SharedObject>*>(lua_touserdata(L, 1)); + const auto objPtr = static_cast<std::shared_ptr<SharedObject>*>(lua_touserdata(L, 1)); if (objPtr) { objPtr->reset(); } diff --git a/src/lua/functions/lua_functions_loader.hpp b/src/lua/functions/lua_functions_loader.hpp index c8176e03522..9c5b65c14bb 100644 --- a/src/lua/functions/lua_functions_loader.hpp +++ b/src/lua/functions/lua_functions_loader.hpp @@ -60,12 +60,12 @@ class LuaFunctionsLoader { static void setCreatureMetatable(lua_State* L, int32_t index, const std::shared_ptr<Creature> &creature); template <typename T> - static typename std::enable_if<std::is_enum<T>::value, T>::type + static std::enable_if_t<std::is_enum_v<T>, T> getNumber(lua_State* L, int32_t arg) { return static_cast<T>(static_cast<int64_t>(lua_tonumber(L, arg))); } template <typename T> - static typename std::enable_if<std::is_integral<T>::value || std::is_floating_point<T>::value, T>::type getNumber(lua_State* L, int32_t arg) { + static std::enable_if_t<std::is_integral_v<T> || std::is_floating_point_v<T>, T> getNumber(lua_State* L, int32_t arg) { auto number = lua_tonumber(L, arg); // If there is overflow, we return the value 0 if constexpr (std::is_integral_v<T> && std::is_unsigned_v<T>) { diff --git a/src/lua/functions/map/house_functions.cpp b/src/lua/functions/map/house_functions.cpp index 99e2c7eb975..5ce229040e0 100644 --- a/src/lua/functions/map/house_functions.cpp +++ b/src/lua/functions/map/house_functions.cpp @@ -116,8 +116,8 @@ int HouseFunctions::luaHouseSetHouseOwner(lua_State* L) { return 1; } - uint32_t guid = getNumber<uint32_t>(L, 2); - bool updateDatabase = getBoolean(L, 3, true); + const uint32_t guid = getNumber<uint32_t>(L, 2); + const bool updateDatabase = getBoolean(L, 3, true); house->setOwner(guid, updateDatabase); pushBoolean(L, true); return 1; @@ -127,7 +127,7 @@ int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { // house:setNewOwnerGuid(guid[, updateDatabase = true]) const auto &house = getUserdataShared<House>(L, 1); if (house) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && house->hasNewOwnership()) { const auto &player = g_game().getPlayerByGUID(house->getOwner()); if (player) { @@ -137,7 +137,7 @@ int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { return 1; } - auto guid = getNumber<uint32_t>(L, 2, 0); + const auto guid = getNumber<uint32_t>(L, 2, 0); house->setNewOwnerGuid(guid, false); pushBoolean(L, true); } else { @@ -168,7 +168,7 @@ int HouseFunctions::luaHouseHasNewOwnership(lua_State* L) { return 1; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); pushBoolean(L, isTransferOnRestart && house->hasNewOwnership()); return 1; } @@ -210,7 +210,7 @@ int HouseFunctions::luaHouseStartTrade(lua_State* L) { return 1; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && house->hasNewOwnership()) { tradePartner->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You cannot buy this house. Ownership is already scheduled to be transferred upon the next server restart."); player->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You cannot sell this house. Ownership is already scheduled to be transferred upon the next server restart."); @@ -337,7 +337,7 @@ int HouseFunctions::luaHouseGetItems(lua_State* L) { int index = 0; for (const auto &tile : tiles) { - TileItemVector* itemVector = tile->getItemList(); + const TileItemVector* itemVector = tile->getItemList(); if (itemVector) { for (const auto &item : *itemVector) { pushUserdata<Item>(L, item); @@ -367,7 +367,7 @@ int HouseFunctions::luaHouseCanEditAccessList(lua_State* L) { return 1; } - uint32_t listId = getNumber<uint32_t>(L, 2); + const uint32_t listId = getNumber<uint32_t>(L, 2); const auto &player = getPlayer(L, 3); if (!player) { @@ -388,7 +388,7 @@ int HouseFunctions::luaHouseGetAccessList(lua_State* L) { } std::string list; - uint32_t listId = getNumber<uint32_t>(L, 2); + const uint32_t listId = getNumber<uint32_t>(L, 2); if (house->getAccessList(listId, list)) { pushString(L, list); } else { @@ -405,7 +405,7 @@ int HouseFunctions::luaHouseSetAccessList(lua_State* L) { return 1; } - uint32_t listId = getNumber<uint32_t>(L, 2); + const uint32_t listId = getNumber<uint32_t>(L, 2); const std::string &list = getString(L, 3); house->setAccessList(listId, list); pushBoolean(L, true); @@ -426,7 +426,7 @@ int HouseFunctions::luaHouseKickPlayer(lua_State* L) { return 1; } - auto targetPlayer = getPlayer(L, 3); + const auto &targetPlayer = getPlayer(L, 3); if (!targetPlayer) { reportErrorFunc("Target player is nullptr"); return 1; diff --git a/src/lua/functions/map/house_functions.hpp b/src/lua/functions/map/house_functions.hpp index ede7e1f0998..addb2e7015c 100644 --- a/src/lua/functions/map/house_functions.hpp +++ b/src/lua/functions/map/house_functions.hpp @@ -13,6 +13,12 @@ class HouseFunctions final : LuaScriptInterface { public: + explicit HouseFunctions(lua_State* L) + : LuaScriptInterface("HouseFunctions") { + init(L); + } + ~HouseFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "House", "", HouseFunctions::luaHouseCreate); registerMetaMethod(L, "House", "__eq", HouseFunctions::luaUserdataCompare); diff --git a/src/lua/functions/map/map_functions.hpp b/src/lua/functions/map/map_functions.hpp index 43b025c9155..4f1e76097a2 100644 --- a/src/lua/functions/map/map_functions.hpp +++ b/src/lua/functions/map/map_functions.hpp @@ -18,6 +18,13 @@ class MapFunctions final : LuaScriptInterface { public: + + explicit MapFunctions(lua_State* L) + : LuaScriptInterface("MapFunctions") { + init(L); + } + ~MapFunctions() override = default; + static void init(lua_State* L) { HouseFunctions::init(L); PositionFunctions::init(L); @@ -25,6 +32,4 @@ class MapFunctions final : LuaScriptInterface { TileFunctions::init(L); TownFunctions::init(L); } - -private: }; diff --git a/src/lua/functions/map/position_functions.cpp b/src/lua/functions/map/position_functions.cpp index ae095a652cd..5c8c0b4b805 100644 --- a/src/lua/functions/map/position_functions.cpp +++ b/src/lua/functions/map/position_functions.cpp @@ -27,9 +27,9 @@ int PositionFunctions::luaPositionCreate(lua_State* L) { const Position &position = getPosition(L, 2, stackpos); pushPosition(L, position, stackpos); } else { - auto x = getNumber<uint16_t>(L, 2, 0); - auto y = getNumber<uint16_t>(L, 3, 0); - auto z = getNumber<uint8_t>(L, 4, 0); + const auto x = getNumber<uint16_t>(L, 2, 0); + const auto y = getNumber<uint16_t>(L, 3, 0); + const auto z = getNumber<uint8_t>(L, 4, 0); stackpos = getNumber<int32_t>(L, 5, 0); pushPosition(L, Position(x, y, z), stackpos); @@ -102,7 +102,7 @@ int PositionFunctions::luaPositionGetPathTo(lua_State* L) { lua_newtable(L); int index = 0; - for (Direction dir : dirList) { + for (const Direction dir : dirList) { lua_pushnumber(L, dir); lua_rawseti(L, -2, ++index); } @@ -114,7 +114,7 @@ int PositionFunctions::luaPositionGetPathTo(lua_State* L) { int PositionFunctions::luaPositionIsSightClear(lua_State* L) { // position:isSightClear(positionEx[, sameFloor = true]) - bool sameFloor = getBoolean(L, 3, true); + const bool sameFloor = getBoolean(L, 3, true); const Position &positionEx = getPosition(L, 2); const Position &position = getPosition(L, 1); pushBoolean(L, g_game().isSightClear(position, positionEx, sameFloor)); @@ -159,7 +159,7 @@ int PositionFunctions::luaPositionSendMagicEffect(lua_State* L) { spectators.emplace_back(player); } - MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2); + const MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isMagicEffectRegistered(magicEffect)) { g_logger().warn("[PositionFunctions::luaPositionSendMagicEffect] An unregistered magic effect type with id '{}' was blocked to prevent client crash.", fmt::underlying(magicEffect)); pushBoolean(L, false); @@ -190,7 +190,7 @@ int PositionFunctions::luaPositionRemoveMagicEffect(lua_State* L) { spectators.emplace_back(player); } - MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2); + const MagicEffectClasses magicEffect = getNumber<MagicEffectClasses>(L, 2); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isMagicEffectRegistered(magicEffect)) { g_logger().warn("[PositionFunctions::luaPositionRemoveMagicEffect] An unregistered magic effect type with id '{}' was blocked to prevent client crash.", fmt::underlying(magicEffect)); pushBoolean(L, false); @@ -221,7 +221,7 @@ int PositionFunctions::luaPositionSendDistanceEffect(lua_State* L) { spectators.emplace_back(player); } - ShootType_t distanceEffect = getNumber<ShootType_t>(L, 3); + const ShootType_t distanceEffect = getNumber<ShootType_t>(L, 3); const Position &positionEx = getPosition(L, 2); const Position &position = getPosition(L, 1); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isDistanceEffectRegistered(distanceEffect)) { @@ -242,8 +242,8 @@ int PositionFunctions::luaPositionSendDistanceEffect(lua_State* L) { int PositionFunctions::luaPositionSendSingleSoundEffect(lua_State* L) { // position:sendSingleSoundEffect(soundId[, actor = nullptr]) const Position &position = getPosition(L, 1); - SoundEffect_t soundEffect = getNumber<SoundEffect_t>(L, 2); - std::shared_ptr<Creature> actor = getCreature(L, 3); + const SoundEffect_t soundEffect = getNumber<SoundEffect_t>(L, 2); + const auto actor = getCreature(L, 3); g_game().sendSingleSoundEffect(position, soundEffect, actor); pushBoolean(L, true); @@ -253,9 +253,9 @@ int PositionFunctions::luaPositionSendSingleSoundEffect(lua_State* L) { int PositionFunctions::luaPositionSendDoubleSoundEffect(lua_State* L) { // position:sendDoubleSoundEffect(mainSoundId, secondarySoundId[, actor = nullptr]) const Position &position = getPosition(L, 1); - SoundEffect_t mainSoundEffect = getNumber<SoundEffect_t>(L, 2); - SoundEffect_t secondarySoundEffect = getNumber<SoundEffect_t>(L, 3); - std::shared_ptr<Creature> actor = getCreature(L, 4); + const SoundEffect_t mainSoundEffect = getNumber<SoundEffect_t>(L, 2); + const SoundEffect_t secondarySoundEffect = getNumber<SoundEffect_t>(L, 3); + const auto &actor = getCreature(L, 4); g_game().sendDoubleSoundEffect(position, mainSoundEffect, secondarySoundEffect, actor); pushBoolean(L, true); diff --git a/src/lua/functions/map/position_functions.hpp b/src/lua/functions/map/position_functions.hpp index e8b126c60f1..debdbd864ec 100644 --- a/src/lua/functions/map/position_functions.hpp +++ b/src/lua/functions/map/position_functions.hpp @@ -13,6 +13,12 @@ class PositionFunctions final : LuaScriptInterface { public: + explicit PositionFunctions(lua_State* L) + : LuaScriptInterface("PositionFunctions") { + init(L); + } + ~PositionFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Position", "", PositionFunctions::luaPositionCreate); registerMetaMethod(L, "Position", "__add", PositionFunctions::luaPositionAdd); diff --git a/src/lua/functions/map/teleport_functions.cpp b/src/lua/functions/map/teleport_functions.cpp index 49e2ec71b1b..c4fece38748 100644 --- a/src/lua/functions/map/teleport_functions.cpp +++ b/src/lua/functions/map/teleport_functions.cpp @@ -16,7 +16,7 @@ // Teleport int TeleportFunctions::luaTeleportCreate(lua_State* L) { // Teleport(uid) - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const auto &item = getScriptEnv()->getItemByUID(id); if (item && item->getTeleport()) { diff --git a/src/lua/functions/map/teleport_functions.hpp b/src/lua/functions/map/teleport_functions.hpp index 152cf8f0d9e..a2751ab04be 100644 --- a/src/lua/functions/map/teleport_functions.hpp +++ b/src/lua/functions/map/teleport_functions.hpp @@ -13,6 +13,12 @@ class TeleportFunctions final : LuaScriptInterface { public: + explicit TeleportFunctions(lua_State* L) + : LuaScriptInterface("TeleportFunctions") { + init(L); + } + ~TeleportFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Teleport", "Item", TeleportFunctions::luaTeleportCreate); registerMetaMethod(L, "Teleport", "__eq", TeleportFunctions::luaUserdataCompare); diff --git a/src/lua/functions/map/tile_functions.cpp b/src/lua/functions/map/tile_functions.cpp index b9776ea7884..6d87d645e5d 100644 --- a/src/lua/functions/map/tile_functions.cpp +++ b/src/lua/functions/map/tile_functions.cpp @@ -19,9 +19,9 @@ int TileFunctions::luaTileCreate(lua_State* L) { if (isTable(L, 2)) { tile = g_game().map.getTile(getPosition(L, 2)); } else { - uint8_t z = getNumber<uint8_t>(L, 4); - uint16_t y = getNumber<uint16_t>(L, 3); - uint16_t x = getNumber<uint16_t>(L, 2); + const uint8_t z = getNumber<uint8_t>(L, 4); + const uint16_t y = getNumber<uint16_t>(L, 3); + const uint16_t x = getNumber<uint16_t>(L, 2); tile = g_game().map.getTile(x, y, z); } @@ -59,7 +59,7 @@ int TileFunctions::luaTileGetGround(lua_State* L) { int TileFunctions::luaTileGetThing(lua_State* L) { // tile:getThing(index) - int32_t index = getNumber<int32_t>(L, 2); + const int32_t index = getNumber<int32_t>(L, 2); const auto &tile = getUserdataShared<Tile>(L, 1); if (!tile) { lua_pushnil(L); @@ -194,7 +194,7 @@ int TileFunctions::luaTileGetItemById(lua_State* L) { return 1; } } - auto subType = getNumber<int32_t>(L, 3, -1); + const auto subType = getNumber<int32_t>(L, 3, -1); const auto &item = g_game().findItemOfType(tile, itemId, false, subType); if (item) { @@ -216,7 +216,7 @@ int TileFunctions::luaTileGetItemByType(lua_State* L) { bool found; - ItemTypes_t itemType = getNumber<ItemTypes_t>(L, 2); + const ItemTypes_t itemType = getNumber<ItemTypes_t>(L, 2); switch (itemType) { case ITEM_TYPE_TELEPORT: found = tile->hasFlag(TILESTATE_TELEPORT); @@ -278,7 +278,7 @@ int TileFunctions::luaTileGetItemByTopOrder(lua_State* L) { return 1; } - int32_t topOrder = getNumber<int32_t>(L, 2); + const int32_t topOrder = getNumber<int32_t>(L, 2); const auto &item = tile->getItemByTopOrder(topOrder); if (!item) { @@ -299,7 +299,7 @@ int TileFunctions::luaTileGetItemCountById(lua_State* L) { return 1; } - auto subType = getNumber<int32_t>(L, 3, -1); + const auto subType = getNumber<int32_t>(L, 3, -1); uint16_t itemId; if (isNumber(L, 2)) { @@ -562,7 +562,7 @@ int TileFunctions::luaTileQueryAdd(lua_State* L) { const auto &thing = getThing(L, 2); if (thing) { - auto flags = getNumber<uint32_t>(L, 3, 0); + const auto flags = getNumber<uint32_t>(L, 3, 0); lua_pushnumber(L, tile->queryAdd(0, thing, 1, flags)); } else { lua_pushnil(L); @@ -589,7 +589,7 @@ int TileFunctions::luaTileAddItem(lua_State* L) { } } - auto subType = getNumber<uint32_t>(L, 3, 1); + const auto subType = getNumber<uint32_t>(L, 3, 1); const auto &item = Item::CreateItem(itemId, std::min<uint32_t>(subType, Item::items[itemId].stackSize)); if (!item) { @@ -597,9 +597,9 @@ int TileFunctions::luaTileAddItem(lua_State* L) { return 1; } - auto flags = getNumber<uint32_t>(L, 4, 0); + const auto flags = getNumber<uint32_t>(L, 4, 0); - ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); + const ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { pushUserdata<Item>(L, item); setItemMetatable(L, -1, item); @@ -630,8 +630,8 @@ int TileFunctions::luaTileAddItemEx(lua_State* L) { return 1; } - auto flags = getNumber<uint32_t>(L, 3, 0); - ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); + const auto flags = getNumber<uint32_t>(L, 3, 0); + const ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); } @@ -663,13 +663,13 @@ int TileFunctions::luaTileSweep(lua_State* L) { lua_pushnil(L); return 1; } - auto actor = getPlayer(L, 2); + const auto &actor = getPlayer(L, 2); if (!actor) { lua_pushnil(L); return 1; } - auto house = tile->getHouse(); + const auto &house = tile->getHouse(); if (!house) { g_logger().debug("TileFunctions::luaTileSweep: tile has no house"); lua_pushnil(L); @@ -682,7 +682,7 @@ int TileFunctions::luaTileSweep(lua_State* L) { return 1; } - auto houseTile = std::dynamic_pointer_cast<HouseTile>(tile); + const auto &houseTile = std::dynamic_pointer_cast<HouseTile>(tile); if (!houseTile) { g_logger().debug("TileFunctions::luaTileSweep: tile is not a house tile"); lua_pushnil(L); diff --git a/src/lua/functions/map/tile_functions.hpp b/src/lua/functions/map/tile_functions.hpp index 78e8c44b32c..2ce32cf18dd 100644 --- a/src/lua/functions/map/tile_functions.hpp +++ b/src/lua/functions/map/tile_functions.hpp @@ -13,6 +13,13 @@ class TileFunctions final : LuaScriptInterface { public: + + explicit TileFunctions(lua_State* L) + : LuaScriptInterface("TileFunctions") { + init(L); + } + ~TileFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Tile", "", TileFunctions::luaTileCreate); registerMetaMethod(L, "Tile", "__eq", TileFunctions::luaUserdataCompare); diff --git a/src/lua/functions/map/town_functions.hpp b/src/lua/functions/map/town_functions.hpp index 65ff991c2c9..efc6e849259 100644 --- a/src/lua/functions/map/town_functions.hpp +++ b/src/lua/functions/map/town_functions.hpp @@ -13,6 +13,12 @@ class TownFunctions final : LuaScriptInterface { public: + explicit TownFunctions(lua_State* L) + : LuaScriptInterface("TownFunctions") { + init(L); + } + ~TownFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Town", "", TownFunctions::luaTownCreate); registerMetaMethod(L, "Town", "__eq", TownFunctions::luaUserdataCompare); @@ -24,8 +30,8 @@ class TownFunctions final : LuaScriptInterface { private: static int luaTownCreate(lua_State* L); - static int luaTownGetId(lua_State* L); static int luaTownGetName(lua_State* L); static int luaTownGetTemplePosition(lua_State* L); }; + diff --git a/src/lua/global/baseevents.cpp b/src/lua/global/baseevents.cpp index 5bc8578062e..1347985f5b0 100644 --- a/src/lua/global/baseevents.cpp +++ b/src/lua/global/baseevents.cpp @@ -20,7 +20,7 @@ bool BaseEvents::loadFromXml() { } std::string scriptsName = getScriptBaseName(); - std::string basePath = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/" + scriptsName + "/"; + const std::string basePath = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/" + scriptsName + "/"; if (getScriptInterface().loadFile( basePath + "lib/" + scriptsName + ".lua", scriptsName + ".lua" @@ -29,10 +29,10 @@ bool BaseEvents::loadFromXml() { g_logger().warn(__FUNCTION__, scriptsName, scriptsName); } - std::string filename = basePath + scriptsName + ".xml"; + const std::string filename = basePath + scriptsName + ".xml"; pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filename.c_str()); + const pugi::xml_parse_result result = doc.load_file(filename.c_str()); if (!result) { printXMLError(__FUNCTION__, filename, result); return false; @@ -40,7 +40,7 @@ bool BaseEvents::loadFromXml() { loaded = true; - for (auto node : doc.child(scriptsName.c_str()).children()) { + for (const auto &node : doc.child(scriptsName.c_str()).children()) { const auto &event = getEvent(node.name()); if (!event) { continue; @@ -104,7 +104,7 @@ bool Event::checkScript(const std::string &basePath, const std::string &scriptsN return false; } - int32_t id = testInterface->getEvent(getScriptEventName()); + const int32_t id = testInterface->getEvent(getScriptEventName()); if (id == -1) { g_logger().warn("[Event::checkScript] - Event " "{} not found {}", @@ -129,7 +129,7 @@ bool Event::loadScript(const std::string &scriptFile, const std::string &scriptN return false; } - int32_t id = scriptInterface->getEvent(getScriptEventName()); + const int32_t id = scriptInterface->getEvent(getScriptEventName()); if (id == -1) { g_logger().warn( "[Event::loadScript] - Event {} not found {}", @@ -152,7 +152,7 @@ bool CallBack::loadCallBack(LuaScriptInterface* interface, const std::string &na scriptInterface = interface; - int32_t id = scriptInterface->getEvent(name); + const int32_t id = scriptInterface->getEvent(name); if (id == -1) { g_logger().warn("[{}] - Event {} not found", __FUNCTION__, name); return false; diff --git a/src/lua/global/globalevent.cpp b/src/lua/global/globalevent.cpp index 4849672f3b2..50b51f693ec 100644 --- a/src/lua/global/globalevent.cpp +++ b/src/lua/global/globalevent.cpp @@ -32,7 +32,7 @@ void GlobalEvents::clear() { bool GlobalEvents::registerLuaEvent(const std::shared_ptr<GlobalEvent> &globalEvent) { if (globalEvent->getEventType() == GLOBALEVENT_TIMER) { - auto result = timerMap.emplace(globalEvent->getName(), globalEvent); + const auto result = timerMap.emplace(globalEvent->getName(), globalEvent); if (result.second) { if (timerEventId == 0) { timerEventId = g_dispatcher().scheduleEvent( @@ -42,12 +42,12 @@ bool GlobalEvents::registerLuaEvent(const std::shared_ptr<GlobalEvent> &globalEv return true; } } else if (globalEvent->getEventType() != GLOBALEVENT_NONE) { - auto result = serverMap.emplace(globalEvent->getName(), globalEvent); + const auto result = serverMap.emplace(globalEvent->getName(), globalEvent); if (result.second) { return true; } } else { // think event - auto result = thinkMap.emplace(globalEvent->getName(), globalEvent); + const auto result = thinkMap.emplace(globalEvent->getName(), globalEvent); if (result.second) { if (thinkEventId == 0) { thinkEventId = g_dispatcher().scheduleEvent( @@ -75,13 +75,13 @@ void GlobalEvents::save() const { } void GlobalEvents::timer() { - time_t now = time(nullptr); + const time_t now = time(nullptr); int64_t nextScheduledTime = std::numeric_limits<int64_t>::max(); auto it = timerMap.begin(); while (it != timerMap.end()) { - const auto globalEvent = it->second; + const auto &globalEvent = it->second; int64_t nextExecutionTime = globalEvent->getNextExecution() - now; if (nextExecutionTime > 0) { @@ -116,7 +116,7 @@ void GlobalEvents::timer() { } void GlobalEvents::think() { - int64_t now = OTSYS_TIME(); + const int64_t now = OTSYS_TIME(); int64_t nextScheduledTime = std::numeric_limits<int64_t>::max(); for (const auto &[globalEventName, globalEvent] : thinkMap) { @@ -145,7 +145,7 @@ void GlobalEvents::think() { } if (nextScheduledTime != std::numeric_limits<int64_t>::max()) { - auto delay = static_cast<uint32_t>(nextScheduledTime); + const auto delay = static_cast<uint32_t>(nextScheduledTime); thinkEventId = g_dispatcher().scheduleEvent( delay, [this] { think(); }, "GlobalEvents::think" ); @@ -230,7 +230,7 @@ bool GlobalEvent::executePeriodChange(LightState_t lightState, LightInfo lightIn return getScriptInterface()->callFunction(2); } -bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) { +bool GlobalEvent::executeRecord(uint32_t current, uint32_t old) const { // onRecord(current, old) if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[GlobalEvent::executeRecord - {}] " diff --git a/src/lua/global/globalevent.hpp b/src/lua/global/globalevent.hpp index 9298ef38bad..5bc374ab08a 100644 --- a/src/lua/global/globalevent.hpp +++ b/src/lua/global/globalevent.hpp @@ -55,7 +55,7 @@ class GlobalEvent final : public Script { explicit GlobalEvent(LuaScriptInterface* interface); bool executePeriodChange(LightState_t lightState, LightInfo lightInfo) const; - bool executeRecord(uint32_t current, uint32_t old); + bool executeRecord(uint32_t current, uint32_t old) const; bool executeEvent() const; GlobalEvent_t getEventType() const { diff --git a/src/lua/modules/modules.cpp b/src/lua/modules/modules.cpp index 70747a7c3bd..f32775e1833 100644 --- a/src/lua/modules/modules.cpp +++ b/src/lua/modules/modules.cpp @@ -20,8 +20,8 @@ Modules::Modules() : void Modules::clear() { // clear recvbyte list - for (const auto &it : recvbyteList) { - it.second->clearEvent(); + for (const auto &[fst, snd] : recvbyteList) { + snd->clearEvent(); } // clear lua state @@ -44,13 +44,13 @@ Event_ptr Modules::getEvent(const std::string &nodeName) { } bool Modules::registerEvent(const Event_ptr &event, const pugi::xml_node &) { - auto module = std::dynamic_pointer_cast<Module>(event); + const auto &module = std::dynamic_pointer_cast<Module>(event); if (module->getEventType() == MODULE_TYPE_NONE) { g_logger().error("Trying to register event without type!"); return false; } - auto oldModule = getEventByRecvbyte(module->getRecvbyte(), false); + const auto oldModule = getEventByRecvbyte(module->getRecvbyte(), false); if (oldModule) { if (!oldModule->isLoaded() && oldModule->getEventType() == module->getEventType()) { oldModule->copyEvent(module); @@ -59,7 +59,7 @@ bool Modules::registerEvent(const Event_ptr &event, const pugi::xml_node &) { return false; } - auto it = recvbyteList.find(module->getRecvbyte()); + const auto it = recvbyteList.find(module->getRecvbyte()); if (it != recvbyteList.end()) { it->second = module; } else { @@ -69,7 +69,7 @@ bool Modules::registerEvent(const Event_ptr &event, const pugi::xml_node &) { } Module_ptr Modules::getEventByRecvbyte(uint8_t recvbyte, bool force) { - auto it = recvbyteList.find(recvbyte); + const auto it = recvbyteList.find(recvbyte); if (it != recvbyteList.end()) { if (!force || it->second->isLoaded()) { return it->second; @@ -79,13 +79,13 @@ Module_ptr Modules::getEventByRecvbyte(uint8_t recvbyte, bool force) { } void Modules::executeOnRecvbyte(uint32_t playerId, NetworkMessage &msg, uint8_t byte) const { - auto player = g_game().getPlayerByID(playerId); + const auto &player = g_game().getPlayerByID(playerId); if (!player) { return; } - for (const auto &it : recvbyteList) { - auto &module = it.second; + for (const auto &[fst, snd] : recvbyteList) { + auto &module = snd; if (module->getEventType() == MODULE_TYPE_RECVBYTE && module->getRecvbyte() == byte && player->canRunModule(module->getRecvbyte())) { player->setModuleDelay(module->getRecvbyte(), module->getDelay()); module->executeOnRecvbyte(player, msg); @@ -100,15 +100,15 @@ Module::Module(LuaScriptInterface* interface) : bool Module::configureEvent(const pugi::xml_node &node) { delay = 0; - auto typeAttribute = node.attribute("type"); + const auto typeAttribute = node.attribute("type"); if (!typeAttribute) { g_logger().error("Missing type for module."); return false; } - auto tmpStr = asLowerCaseString(typeAttribute.as_string()); + const auto tmpStr = asLowerCaseString(typeAttribute.as_string()); if (tmpStr == "recvbyte") { - auto byteAttribute = node.attribute("byte"); + const auto byteAttribute = node.attribute("byte"); if (!byteAttribute) { g_logger().error("Missing byte for module typed recvbyte."); return false; @@ -121,7 +121,7 @@ bool Module::configureEvent(const pugi::xml_node &node) { return false; } - auto delayAttribute = node.attribute("delay"); + const auto delayAttribute = node.attribute("delay"); if (delayAttribute) { delay = static_cast<int16_t>(delayAttribute.as_uint()); } @@ -153,7 +153,7 @@ void Module::clearEvent() { loaded = false; } -void Module::executeOnRecvbyte(const std::shared_ptr<Player> &player, NetworkMessage &msg) { +void Module::executeOnRecvbyte(const std::shared_ptr<Player> &player, NetworkMessage &msg) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("Call stack overflow. Too many lua script calls being nested {}", player->getName()); return; diff --git a/src/lua/modules/modules.hpp b/src/lua/modules/modules.hpp index a9211db3317..5917013ec90 100644 --- a/src/lua/modules/modules.hpp +++ b/src/lua/modules/modules.hpp @@ -21,7 +21,7 @@ class Module final : public Event { public: explicit Module(LuaScriptInterface* interface); - bool configureEvent(const pugi::xml_node &node) final; + bool configureEvent(const pugi::xml_node &node) override; ModuleType_t getEventType() const { return type; @@ -34,7 +34,7 @@ class Module final : public Event { void copyEvent(const Module_ptr &creatureEvent); // scripting - void executeOnRecvbyte(const std::shared_ptr<Player> &player, NetworkMessage &msg); + void executeOnRecvbyte(const std::shared_ptr<Player> &player, NetworkMessage &msg) const; // uint8_t getRecvbyte() const { @@ -46,7 +46,7 @@ class Module final : public Event { } protected: - std::string getScriptEventName() const final; + std::string getScriptEventName() const override; ModuleType_t type; uint8_t recvbyte {}; @@ -74,7 +74,7 @@ class Modules final : public BaseEvents { std::string getScriptBaseName() const override; Event_ptr getEvent(const std::string &nodeName) override; bool registerEvent(const Event_ptr &event, const pugi::xml_node &node) override; - void clear() final; + void clear() override; using ModulesList = std::map<uint8_t, Module_ptr>; ModulesList recvbyteList; diff --git a/src/lua/scripts/lua_environment.cpp b/src/lua/scripts/lua_environment.cpp index cd5023a8d4b..70b0d5136db 100644 --- a/src/lua/scripts/lua_environment.cpp +++ b/src/lua/scripts/lua_environment.cpp @@ -71,7 +71,7 @@ bool LuaEnvironment::closeState() { for (auto &timerEntry : timerEvents) { LuaTimerEventDesc timerEventDesc = std::move(timerEntry.second); - for (int32_t parameter : timerEventDesc.parameters) { + for (const int32_t parameter : timerEventDesc.parameters) { luaL_unref(luaState, LUA_REGISTRYINDEX, parameter); } luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); @@ -96,7 +96,7 @@ LuaScriptInterface* LuaEnvironment::getTestInterface() { } std::shared_ptr<Combat> LuaEnvironment::getCombatObject(uint32_t id) const { - auto it = combatMap.find(id); + const auto it = combatMap.find(id); if (it == combatMap.end()) { return nullptr; } @@ -106,12 +106,12 @@ std::shared_ptr<Combat> LuaEnvironment::getCombatObject(uint32_t id) const { std::shared_ptr<Combat> LuaEnvironment::createCombatObject(LuaScriptInterface* interface) { auto combat = std::make_shared<Combat>(); combatMap[++lastCombatId] = combat; - combatIdMap[interface].push_back(lastCombatId); + combatIdMap[interface].emplace_back(lastCombatId); return combat; } void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface) { - auto it = combatIdMap.find(interface); + const auto it = combatIdMap.find(interface); if (it == combatIdMap.end()) { return; } @@ -121,7 +121,7 @@ void LuaEnvironment::clearCombatObjects(LuaScriptInterface* interface) { } const std::unique_ptr<AreaCombat> &LuaEnvironment::getAreaObject(uint32_t id) const { - auto it = areaMap.find(id); + const auto it = areaMap.find(id); if (it == areaMap.end()) { return AreaCombatNull; } @@ -130,12 +130,12 @@ const std::unique_ptr<AreaCombat> &LuaEnvironment::getAreaObject(uint32_t id) co uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface) { areaMap[++lastAreaId] = std::make_unique<AreaCombat>(); - areaIdMap[interface].push_back(lastAreaId); + areaIdMap[interface].emplace_back(lastAreaId); return lastAreaId; } void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface) { - auto it = areaIdMap.find(interface); + const auto it = areaIdMap.find(interface); if (it == areaIdMap.end()) { return; } @@ -150,7 +150,7 @@ void LuaEnvironment::clearAreaObjects(LuaScriptInterface* interface) { } void LuaEnvironment::executeTimerEvent(uint32_t eventIndex) { - auto it = timerEvents.find(eventIndex); + const auto it = timerEvents.find(eventIndex); if (it == timerEvents.end()) { return; } @@ -162,7 +162,7 @@ void LuaEnvironment::executeTimerEvent(uint32_t eventIndex) { lua_rawgeti(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); // push parameters - for (auto parameter : std::views::reverse(timerEventDesc.parameters)) { + for (const auto parameter : std::views::reverse(timerEventDesc.parameters)) { lua_rawgeti(luaState, LUA_REGISTRYINDEX, parameter); } @@ -180,7 +180,7 @@ void LuaEnvironment::executeTimerEvent(uint32_t eventIndex) { // free resources luaL_unref(luaState, LUA_REGISTRYINDEX, timerEventDesc.function); - for (auto parameter : timerEventDesc.parameters) { + for (const auto parameter : timerEventDesc.parameters) { luaL_unref(luaState, LUA_REGISTRYINDEX, parameter); } } diff --git a/src/lua/scripts/lua_environment.hpp b/src/lua/scripts/lua_environment.hpp index d6611249f61..7c5b0e5edea 100644 --- a/src/lua/scripts/lua_environment.hpp +++ b/src/lua/scripts/lua_environment.hpp @@ -22,7 +22,7 @@ class Cylinder; class Game; class GlobalFunctions; -class LuaEnvironment : public LuaScriptInterface { +class LuaEnvironment final : public LuaScriptInterface { public: static bool shuttingDown; @@ -52,15 +52,15 @@ class LuaEnvironment : public LuaScriptInterface { template <typename T> std::shared_ptr<T> createWeaponObject(LuaScriptInterface* interface) { auto weapon = std::make_shared<T>(interface); - auto weaponId = ++lastWeaponId; + const auto weaponId = ++lastWeaponId; weaponMap[weaponId] = weapon; - weaponIdMap[interface].push_back(weaponId); + weaponIdMap[interface].emplace_back(weaponId); return weapon; } template <typename T> std::shared_ptr<T> getWeaponObject(uint32_t id) const { - auto it = weaponMap.find(id); + const auto it = weaponMap.find(id); if (it == weaponMap.end()) { return nullptr; } @@ -68,7 +68,7 @@ class LuaEnvironment : public LuaScriptInterface { } void clearWeaponObjects(LuaScriptInterface* interface) { - auto it = weaponIdMap.find(interface); + const auto it = weaponIdMap.find(interface); if (it == weaponIdMap.end()) { return; } diff --git a/src/lua/scripts/luascript.cpp b/src/lua/scripts/luascript.cpp index d67b90e9d18..ae1d31845ff 100644 --- a/src/lua/scripts/luascript.cpp +++ b/src/lua/scripts/luascript.cpp @@ -25,7 +25,7 @@ LuaScriptInterface::LuaScriptInterface(std::string initInterfaceName) : } LuaScriptInterface::~LuaScriptInterface() { - closeState(); + LuaScriptInterface::closeState(); } bool LuaScriptInterface::reInitState() { @@ -158,7 +158,7 @@ const std::string &LuaScriptInterface::getFileById(int32_t scriptId) { return loadingFile; } - auto it = cacheFiles.find(scriptId); + const auto it = cacheFiles.find(scriptId); if (it == cacheFiles.end()) { static const std::string &unk = "(Unknown scriptfile)"; return unk; @@ -166,7 +166,7 @@ const std::string &LuaScriptInterface::getFileById(int32_t scriptId) { return it->second; } -std::string LuaScriptInterface::getStackTrace(const std::string &error_desc) { +std::string LuaScriptInterface::getStackTrace(const std::string &error_desc) const { lua_getglobal(luaState, "debug"); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); @@ -195,7 +195,7 @@ std::string LuaScriptInterface::getStackTrace(const std::string &error_desc) { return stackTrace; } -bool LuaScriptInterface::pushFunction(int32_t functionId) { +bool LuaScriptInterface::pushFunction(int32_t functionId) const { lua_rawgeti(luaState, LUA_REGISTRYINDEX, eventTableRef); if (!isTable(luaState, -1)) { return false; @@ -237,7 +237,7 @@ bool LuaScriptInterface::closeState() { return true; } -std::string LuaScriptInterface::getMetricsScope() { +std::string LuaScriptInterface::getMetricsScope() const { metrics::method_latency measure(__METHOD_NAME__); int32_t scriptId; int32_t callbackId; @@ -255,7 +255,7 @@ std::string LuaScriptInterface::getMetricsScope() { if (name.empty()) { return "unknown"; } - auto pos = name.find("data"); + const auto pos = name.find("data"); if (pos != std::string::npos) { name = name.substr(pos); } @@ -264,10 +264,10 @@ std::string LuaScriptInterface::getMetricsScope() { return fmt::format("{}:{}", name, timerEvent ? "timer" : "<direct>"); } -bool LuaScriptInterface::callFunction(int params) { +bool LuaScriptInterface::callFunction(int params) const { metrics::lua_latency measure(getMetricsScope()); bool result = false; - int size = lua_gettop(luaState); + const int size = lua_gettop(luaState); if (protectedCall(luaState, params, 1) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::getString(luaState, -1)); } else { @@ -283,9 +283,9 @@ bool LuaScriptInterface::callFunction(int params) { return result; } -void LuaScriptInterface::callVoidFunction(int params) { +void LuaScriptInterface::callVoidFunction(int params) const { metrics::lua_latency measure(getMetricsScope()); - int size = lua_gettop(luaState); + const int size = lua_gettop(luaState); if (protectedCall(luaState, params, 0) != 0) { LuaScriptInterface::reportError(nullptr, LuaScriptInterface::popString(luaState)); } diff --git a/src/lua/scripts/luascript.hpp b/src/lua/scripts/luascript.hpp index 06654c35a21..4f020c0dbd2 100644 --- a/src/lua/scripts/luascript.hpp +++ b/src/lua/scripts/luascript.hpp @@ -58,12 +58,12 @@ class LuaScriptInterface : public LuaFunctionsLoader { return luaState; } - bool pushFunction(int32_t functionId); + bool pushFunction(int32_t functionId) const; - bool callFunction(int params); - void callVoidFunction(int params); + bool callFunction(int params) const; + void callVoidFunction(int params) const; - std::string getStackTrace(const std::string &error_desc); + std::string getStackTrace(const std::string &error_desc) const; protected: virtual bool closeState(); @@ -73,7 +73,7 @@ class LuaScriptInterface : public LuaFunctionsLoader { std::map<int32_t, std::string> cacheFiles; private: - std::string getMetricsScope(); + std::string getMetricsScope() const; std::string lastLuaError; std::string interfaceName; diff --git a/src/lua/scripts/script_environment.cpp b/src/lua/scripts/script_environment.cpp index 1a46457959e..bd4d2aac934 100644 --- a/src/lua/scripts/script_environment.cpp +++ b/src/lua/scripts/script_environment.cpp @@ -31,9 +31,9 @@ void ScriptEnvironment::resetEnv() { localMap.clear(); tempResults.clear(); - auto pair = tempItems.equal_range(this); - auto it = pair.first; - while (it != pair.second) { + const auto [fst, snd] = tempItems.equal_range(this); + auto it = fst; + while (it != snd) { const auto item = it->second; it = tempItems.erase(it); } @@ -53,7 +53,7 @@ bool ScriptEnvironment::setCallbackId(int32_t newCallbackId, LuaScriptInterface* return true; } -void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface*&retScriptInterface, int32_t &retCallbackId, bool &retTimerEvent) const { +void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface* &retScriptInterface, int32_t &retCallbackId, bool &retTimerEvent) const { retScriptId = this->scriptId; retScriptInterface = interface; retCallbackId = this->callbackId; @@ -75,9 +75,9 @@ uint32_t ScriptEnvironment::addThing(const std::shared_ptr<Thing> &thing) { return item->getAttribute<uint32_t>(ItemAttribute_t::UNIQUEID); } - for (const auto &it : localMap) { - if (it.second == item) { - return it.first; + for (const auto &[fst, snd] : localMap) { + if (snd == item) { + return fst; } } @@ -86,8 +86,8 @@ uint32_t ScriptEnvironment::addThing(const std::shared_ptr<Thing> &thing) { } void ScriptEnvironment::insertItem(uint32_t uid, std::shared_ptr<Item> item) { - auto result = localMap.emplace(uid, item); - if (!result.second) { + const auto [fst, snd] = localMap.emplace(uid, item); + if (!snd) { g_logger().error("Thing uid already taken: {}", uid); } } @@ -105,7 +105,7 @@ std::shared_ptr<Thing> ScriptEnvironment::getThingByUID(uint32_t uid) { return nullptr; } - auto it = localMap.find(uid); + const auto it = localMap.find(uid); if (it != localMap.end()) { const auto &item = it->second; if (!item->isRemoved()) { @@ -137,7 +137,7 @@ void ScriptEnvironment::removeItemByUID(uint32_t uid) { return; } - auto it = localMap.find(uid); + const auto it = localMap.find(uid); if (it != localMap.end()) { localMap.erase(it); } @@ -162,7 +162,7 @@ uint32_t ScriptEnvironment::addResult(DBResult_ptr res) { } bool ScriptEnvironment::removeResult(uint32_t id) { - auto it = tempResults.find(id); + const auto it = tempResults.find(id); if (it == tempResults.end()) { return false; } @@ -172,7 +172,7 @@ bool ScriptEnvironment::removeResult(uint32_t id) { } DBResult_ptr ScriptEnvironment::getResultByID(uint32_t id) { - auto it = tempResults.find(id); + const auto it = tempResults.find(id); if (it == tempResults.end()) { return nullptr; } diff --git a/src/lua/scripts/script_environment.hpp b/src/lua/scripts/script_environment.hpp index 3e22693851a..f82bc7228f3 100644 --- a/src/lua/scripts/script_environment.hpp +++ b/src/lua/scripts/script_environment.hpp @@ -24,7 +24,7 @@ class LuaScriptInterface; class Cylinder; class Game; -class ScriptEnvironment { +class ScriptEnvironment final { public: ScriptEnvironment(); virtual ~ScriptEnvironment(); @@ -44,7 +44,7 @@ class ScriptEnvironment { int32_t getScriptId() const { return scriptId; } - LuaScriptInterface* getScriptInterface() { + LuaScriptInterface* getScriptInterface() const { return interface; } diff --git a/src/lua/scripts/scripts.cpp b/src/lua/scripts/scripts.cpp index b42e74ca3fb..d55a3bf098c 100644 --- a/src/lua/scripts/scripts.cpp +++ b/src/lua/scripts/scripts.cpp @@ -42,7 +42,7 @@ bool Scripts::loadEventSchedulerScripts(const std::string &fileName) { return false; } - std::filesystem::recursive_directory_iterator endit; + const std::filesystem::recursive_directory_iterator endit; for (std::filesystem::recursive_directory_iterator it(dir); it != endit; ++it) { if (std::filesystem::is_regular_file(*it) && it->path().extension() == ".lua") { if (it->path().filename().string() == fileName) { @@ -77,8 +77,8 @@ bool Scripts::loadScripts(std::string loadPath, bool isLib, bool reload) { // Script folder, example: "actions" std::string scriptFolder = realPath.parent_path().string(); // Create a string_view for the fileFolder and scriptFolder strings - std::string_view fileFolderView(fileFolder); - std::string_view scriptFolderView(scriptFolder); + const std::string_view fileFolderView(fileFolder); + const std::string_view scriptFolderView(scriptFolder); // Filename, example: "demon.lua" std::string file(realPath.filename().string()); if (!std::filesystem::is_regular_file(entry) || realPath.extension() != ".lua") { diff --git a/src/lua/scripts/scripts.hpp b/src/lua/scripts/scripts.hpp index 7cefaaaf8bd..10ed18ed4f4 100644 --- a/src/lua/scripts/scripts.hpp +++ b/src/lua/scripts/scripts.hpp @@ -85,7 +85,7 @@ class Script { return false; } - int32_t id = scriptInterface->getEvent(); + const int32_t id = scriptInterface->getEvent(); if (id == -1) { g_logger().error("[Script::loadCallback] Event {} not found for script with name {}", getScriptTypeName(), scriptInterface->getLoadingScriptName()); return false; diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index aca6f9a656a..482e89a0f9d 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -24,12 +24,12 @@ House::House(uint32_t houseId) : void House::addTile(const std::shared_ptr<HouseTile> &tile) { tile->setFlag(TILESTATE_PROTECTIONZONE); - houseTiles.push_back(tile); + houseTiles.emplace_back(tile); updateDoorDescription(); } void House::setNewOwnerGuid(int32_t newOwnerGuid, bool serverStartup) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (!isTransferOnRestart) { setOwner(newOwnerGuid, true); return; @@ -78,7 +78,7 @@ bool House::tryTransferOwnership(const std::shared_ptr<Player> &player, bool ser for (const auto &tile : houseTiles) { if (const CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { - const auto creature = (*creatures)[i]; + const auto &creature = (*creatures)[i]; kickPlayer(nullptr, creature->getPlayer()); } } @@ -107,7 +107,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, const std:: if (owner != 0) { tryTransferOwnership(player, false); } else { - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); + const std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); time_t currentTime = time(nullptr); if (strRentPeriod == "yearly") { currentTime += 24 * 60 * 60 * 365; @@ -130,12 +130,12 @@ void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, const std:: Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `name`, `account_id` FROM `players` WHERE `id` = " << guid; - DBResult_ptr result = db.storeQuery(query.str()); + const DBResult_ptr result = db.storeQuery(query.str()); if (!result) { return; } - std::string name = result->getString("name"); + const std::string name = result->getString("name"); if (!name.empty()) { owner = guid; ownerName = name; @@ -160,7 +160,7 @@ void House::updateDoorDescription() const { if (g_configManager().getBoolean(HOUSE_PURSHASED_SHOW_PRICE, __FUNCTION__) || owner == 0) { ss << " It costs " << formatNumber(getPrice()) << " gold coins."; } - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); + const std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); if (strRentPeriod != "never") { ss << " The rent cost is " << formatNumber(getRent()) << " gold coins and it is billed " << strRentPeriod << "."; } @@ -206,7 +206,7 @@ bool House::kickPlayer(const std::shared_ptr<Player> &player, const std::shared_ return false; } - std::shared_ptr<HouseTile> houseTile = std::dynamic_pointer_cast<HouseTile>(target->getTile()); + const auto &houseTile = std::dynamic_pointer_cast<HouseTile>(target->getTile()); if (!houseTile || houseTile->getHouse() != static_self_cast<House>()) { return false; } @@ -215,7 +215,7 @@ bool House::kickPlayer(const std::shared_ptr<Player> &player, const std::shared_ return false; } - Position oldPosition = target->getPosition(); + const Position oldPosition = target->getPosition(); if (g_game().internalTeleport(target, getEntryPosition()) == RETURNVALUE_NOERROR) { g_game().addMagicEffect(oldPosition, CONST_ME_POFF); g_game().addMagicEffect(getEntryPosition(), CONST_ME_TELEPORT); @@ -229,7 +229,7 @@ void House::setAccessList(uint32_t listId, const std::string &textlist) { } else if (listId == SUBOWNER_LIST) { subOwnerList.parseList(textlist); } else { - std::shared_ptr<Door> door = getDoorByNumber(listId); + const auto &door = getDoorByNumber(listId); if (door) { door->setAccessList(textlist); } @@ -240,7 +240,7 @@ void House::setAccessList(uint32_t listId, const std::string &textlist) { // kick uninvited players for (const std::shared_ptr<HouseTile> &tile : houseTiles) { - if (CreatureVector* creatures = tile->getCreatures()) { + if (const CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { const auto &player = (*creatures)[i]->getPlayer(); if (player && !isInvited(player)) { @@ -260,7 +260,7 @@ bool House::transferToDepot() const { if (player) { transferToDepot(player); } else { - std::shared_ptr<Player> tmpPlayer = std::make_shared<Player>(nullptr); + const auto tmpPlayer = std::make_shared<Player>(nullptr); if (!IOLoginData::loadPlayerById(tmpPlayer, owner)) { return false; } @@ -274,7 +274,7 @@ bool House::transferToDepot(const std::shared_ptr<Player> &player) const { if (townId == 0 || !player) { return false; } - for (const std::shared_ptr<HouseTile> &tile : houseTiles) { + for (const auto &tile : houseTiles) { if (!transferToDepot(player, tile)) { return false; } @@ -293,11 +293,11 @@ bool House::transferToDepot(const std::shared_ptr<Player> &player, const std::sh ItemList moveItemList; if (const TileItemVector* items = tile->getItemList()) { - for (const std::shared_ptr<Item> &item : *items) { + for (const auto &item : *items) { if (item->isWrapable()) { handleWrapableItem(moveItemList, item, player, tile); } else if (item->isPickupable()) { - moveItemList.push_back(item); + moveItemList.emplace_back(item); } else { handleContainer(moveItemList, item); } @@ -306,7 +306,7 @@ bool House::transferToDepot(const std::shared_ptr<Player> &player, const std::sh std::unordered_set<std::shared_ptr<Player>> playersToSave = { player }; - for (const std::shared_ptr<Item> &item : moveItemList) { + for (const auto &item : moveItemList) { g_logger().debug("[{}] moving item '{}' to depot", __FUNCTION__, item->getName()); auto targetPlayer = player; if (item->hasOwner() && !item->isOwner(targetPlayer)) { @@ -327,9 +327,9 @@ bool House::transferToDepot(const std::shared_ptr<Player> &player, const std::sh bool House::hasItemOnTile() const { bool foundItem = false; - for (const std::shared_ptr<HouseTile> &tile : houseTiles) { + for (const auto &tile : houseTiles) { if (const auto &items = tile->getItemList()) { - for (const std::shared_ptr<Item> &item : *items) { + for (const auto &item : *items) { if (!item) { continue; } @@ -370,19 +370,19 @@ void House::handleWrapableItem(ItemList &moveItemList, const std::shared_ptr<Ite handleContainer(moveItemList, item); } - std::shared_ptr<Item> newItem = g_game().wrapItem(item, houseTile->getHouse()); + const auto &newItem = g_game().wrapItem(item, houseTile->getHouse()); if (newItem->isRemoved() && !newItem->getParent()) { g_logger().warn("[{}] item removed during wrapping - check ground type - player name: {} item id: {} position: {}", __FUNCTION__, player->getName(), item->getID(), houseTile->getPosition().toString()); return; } - moveItemList.push_back(newItem); + moveItemList.emplace_back(newItem); } void House::handleContainer(ItemList &moveItemList, const std::shared_ptr<Item> &item) const { - if (const auto container = item->getContainer()) { - for (const std::shared_ptr<Item> &containerItem : container->getItemList()) { - moveItemList.push_back(containerItem); + if (const auto &container = item->getContainer()) { + for (const auto &containerItem : container->getItemList()) { + moveItemList.emplace_back(containerItem); } } } @@ -396,7 +396,7 @@ bool House::getAccessList(uint32_t listId, std::string &list) const { return true; } - std::shared_ptr<Door> door = getDoorByNumber(listId); + const auto &door = getDoorByNumber(listId); if (!door) { return false; } @@ -405,20 +405,20 @@ bool House::getAccessList(uint32_t listId, std::string &list) const { } void House::addDoor(const std::shared_ptr<Door> &door) { - doorList.push_back(door); + doorList.emplace_back(door); door->setHouse(static_self_cast<House>()); updateDoorDescription(); } void House::removeDoor(const std::shared_ptr<Door> &door) { - auto it = std::find(doorList.begin(), doorList.end(), door); + const auto &it = std::ranges::find(doorList, door); if (it != doorList.end()) { doorList.erase(it); } } void House::addBed(const std::shared_ptr<BedItem> &bed) { - bedsList.push_back(bed); + bedsList.emplace_back(bed); bed->setHouse(static_self_cast<House>()); } @@ -436,8 +436,8 @@ std::shared_ptr<Door> House::getDoorByNumber(uint32_t doorId) const { return nullptr; } -std::shared_ptr<Door> House::getDoorByPosition(const Position &pos) { - for (std::shared_ptr<Door> door : doorList) { +std::shared_ptr<Door> House::getDoorByPosition(const Position &pos) const { + for (const auto &door : doorList) { if (door->getPosition() == pos) { return door; } @@ -471,7 +471,7 @@ std::shared_ptr<HouseTransferItem> House::getTransferItem() { void House::resetTransferItem() { if (transferItem) { - std::shared_ptr<Item> tmpItem = transferItem; + const auto &tmpItem = transferItem; transferItem = nullptr; transfer_container->resetParent(); transfer_container->removeThing(tmpItem, tmpItem->getItemCount()); @@ -479,7 +479,7 @@ void House::resetTransferItem() { } std::shared_ptr<HouseTransferItem> HouseTransferItem::createHouseTransferItem(const std::shared_ptr<House> &house) { - std::shared_ptr<HouseTransferItem> transferItem = std::make_shared<HouseTransferItem>(house); + const auto &transferItem = std::make_shared<HouseTransferItem>(house); transferItem->setID(ITEM_DOCUMENT_RO); transferItem->setSubType(1); std::ostringstream ss; @@ -488,17 +488,17 @@ std::shared_ptr<HouseTransferItem> HouseTransferItem::createHouseTransferItem(co return transferItem; } -void HouseTransferItem::onTradeEvent(TradeEvents_t event, std::shared_ptr<Player> owner) { +void HouseTransferItem::onTradeEvent(TradeEvents_t event, const std::shared_ptr<Player> &owner) { if (event == ON_TRADE_TRANSFER) { if (house) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); auto ownershipTransferMessage = " The ownership will be transferred upon server restart."; - auto boughtMessage = fmt::format("You have successfully bought the house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); - auto soldMessage = fmt::format("You have successfully sold your house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); + const auto boughtMessage = fmt::format("You have successfully bought the house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); + const auto soldMessage = fmt::format("You have successfully sold your house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); owner->sendTextMessage(MESSAGE_EVENT_ADVANCE, boughtMessage); - auto oldOwner = g_game().getPlayerByGUID(house->getOwner()); + const auto oldOwner = g_game().getPlayerByGUID(house->getOwner()); if (oldOwner) { oldOwner->sendTextMessage(MESSAGE_EVENT_ADVANCE, soldMessage); } @@ -518,7 +518,7 @@ bool House::executeTransfer(const std::shared_ptr<HouseTransferItem> &item, cons return false; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); + const auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart) { if (hasNewOwnerOnStartup) { return false; @@ -533,7 +533,7 @@ bool House::executeTransfer(const std::shared_ptr<HouseTransferItem> &item, cons } void AccessList::parseList(const std::string &list) { - std::regex regexValidChars("[^a-zA-Z' \n*!@#]+"); + const std::regex regexValidChars("[^a-zA-Z' \n*!@#]+"); std::string validList = std::regex_replace(list, regexValidChars, ""); // Remove empty lines @@ -568,7 +568,7 @@ void AccessList::parseList(const std::string &list) { toLowerCaseString(m_line); - std::string::size_type at_pos = m_line.find('@'); + const std::string::size_type at_pos = m_line.find('@'); if (at_pos != std::string::npos) { if (at_pos == 0) { addGuild(m_line.substr(1)); @@ -591,7 +591,7 @@ void AccessList::addPlayer(const std::string &name) { if (player) { playerList.insert(player->getGUID()); } else { - uint32_t guid = IOLoginData::getGuidByName(name); + const uint32_t guid = IOLoginData::getGuidByName(name); if (guid != 0) { playerList.insert(guid); } @@ -600,12 +600,12 @@ void AccessList::addPlayer(const std::string &name) { namespace { std::shared_ptr<Guild> getGuildByName(const std::string &name) { - uint32_t guildId = IOGuild::getGuildIdByName(name); + const uint32_t guildId = IOGuild::getGuildIdByName(name); if (guildId == 0) { return nullptr; } - auto guild = g_game().getGuild(guildId); + const auto &guild = g_game().getGuild(guildId); if (guild) { return guild; } @@ -615,7 +615,7 @@ namespace { } void AccessList::addGuild(const std::string &name) { - const auto guild = getGuildByName(name); + const auto &guild = getGuildByName(name); if (guild) { for (const auto &rank : guild->getRanks()) { guildRankList.insert(rank->id); @@ -624,9 +624,9 @@ void AccessList::addGuild(const std::string &name) { } void AccessList::addGuildRank(const std::string &name, const std::string &guildName) { - const auto guild = getGuildByName(guildName); + const auto &guild = getGuildByName(guildName); if (guild) { - const GuildRank_ptr rank = guild->getRankByName(name); + const GuildRank_ptr &rank = guild->getRankByName(name); if (rank) { guildRankList.insert(rank->id); } @@ -715,7 +715,7 @@ void Door::onRemoved() { } } -std::shared_ptr<House> Houses::getHouseByPlayerId(uint32_t playerId) { +std::shared_ptr<House> Houses::getHouseByPlayerId(uint32_t playerId) const { for (const auto &it : houseMap) { if (it.second->getOwner() == playerId) { return it.second; @@ -726,13 +726,13 @@ std::shared_ptr<House> Houses::getHouseByPlayerId(uint32_t playerId) { bool Houses::loadHousesXML(const std::string &filename) { pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filename.c_str()); + const pugi::xml_parse_result result = doc.load_file(filename.c_str()); if (!result) { printXMLError(__FUNCTION__, filename, result); return false; } - for (auto houseNode : doc.child("houses").children()) { + for (const auto &houseNode : doc.child("houses").children()) { pugi::xml_attribute houseIdAttribute = houseNode.attribute("houseid"); if (!houseIdAttribute) { return false; @@ -740,7 +740,7 @@ bool Houses::loadHousesXML(const std::string &filename) { auto houseId = pugi::cast<int32_t>(houseIdAttribute.value()); - std::shared_ptr<House> house = getHouse(houseId); + const auto &house = getHouse(houseId); if (!house) { g_logger().error("[Houses::loadHousesXML] - Unknown house, id: {}", houseId); return false; @@ -748,7 +748,7 @@ bool Houses::loadHousesXML(const std::string &filename) { house->setName(houseNode.attribute("name").as_string()); - Position entryPos( + const Position entryPos( pugi::cast<uint16_t>(houseNode.attribute("entryx").value()), pugi::cast<uint16_t>(houseNode.attribute("entryy").value()), pugi::cast<uint16_t>(houseNode.attribute("entryz").value()) @@ -780,9 +780,9 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { return; } - time_t currentTime = time(nullptr); + const time_t currentTime = time(nullptr); for (const auto &it : houseMap) { - std::shared_ptr<House> house = it.second; + const auto &house = it.second; if (house->getOwner() == 0) { continue; } @@ -793,7 +793,7 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { continue; } - auto player = g_game().getPlayerByGUID(ownerId, true); + const auto &player = g_game().getPlayerByGUID(ownerId, true); if (!player) { // Player doesn't exist, reset house owner house->tryTransferOwnership(nullptr, true); @@ -803,9 +803,9 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { // Player hasn't logged in for a while, reset house owner auto daysToReset = g_configManager().getNumber(HOUSE_LOSE_AFTER_INACTIVITY, __FUNCTION__); if (daysToReset > 0) { - auto daysSinceLastLogin = (currentTime - player->getLastLoginSaved()) / (60 * 60 * 24); - bool vipKeep = g_configManager().getBoolean(VIP_KEEP_HOUSE, __FUNCTION__) && player->isVip(); - bool activityKeep = daysSinceLastLogin < daysToReset; + const auto daysSinceLastLogin = (currentTime - player->getLastLoginSaved()) / (60 * 60 * 24); + const bool vipKeep = g_configManager().getBoolean(VIP_KEEP_HOUSE, __FUNCTION__) && player->isVip(); + const bool activityKeep = daysSinceLastLogin < daysToReset; if (vipKeep && !activityKeep) { g_logger().info("Player {} has not logged in for {} days, but is a VIP, so the house will not be reset.", player->getName(), daysToReset); } else if (!vipKeep && !activityKeep) { @@ -846,7 +846,7 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { house->setPaidUntil(paidUntil); } else { if (house->getPayRentWarnings() < 7) { - int32_t daysLeft = 7 - house->getPayRentWarnings(); + const int32_t daysLeft = 7 - house->getPayRentWarnings(); std::shared_ptr<Item> letter = Item::CreateItem(ITEM_LETTER_STAMPED); std::string period; @@ -891,7 +891,7 @@ uint32_t House::getRent() const { } uint32_t House::getPrice() const { - auto sqmPrice = static_cast<uint32_t>(g_configManager().getNumber(HOUSE_PRICE_PER_SQM, __FUNCTION__)) * getSize(); - auto rentPrice = static_cast<uint32_t>(static_cast<float>(getRent()) * g_configManager().getFloat(HOUSE_PRICE_RENT_MULTIPLIER, __FUNCTION__)); + const auto sqmPrice = static_cast<uint32_t>(g_configManager().getNumber(HOUSE_PRICE_PER_SQM, __FUNCTION__)) * getSize(); + const auto rentPrice = static_cast<uint32_t>(static_cast<float>(getRent()) * g_configManager().getFloat(HOUSE_PRICE_RENT_MULTIPLIER, __FUNCTION__)); return sqmPrice + rentPrice; } diff --git a/src/map/house/house.hpp b/src/map/house/house.hpp index f1af2c4e41e..a3dc765988f 100644 --- a/src/map/house/house.hpp +++ b/src/map/house/house.hpp @@ -88,7 +88,7 @@ class HouseTransferItem final : public Item { explicit HouseTransferItem(std::shared_ptr<House> newHouse) : Item(0), house(std::move(newHouse)) { } - void onTradeEvent(TradeEvents_t event, std::shared_ptr<Player> owner) override; + void onTradeEvent(TradeEvents_t event, const std::shared_ptr<Player> &owner) override; bool canTransform() const override { return false; } @@ -97,7 +97,7 @@ class HouseTransferItem final : public Item { std::shared_ptr<House> house; }; -class House : public SharedObject { +class House final : public SharedObject { public: explicit House(uint32_t houseId); @@ -195,7 +195,7 @@ class House : public SharedObject { void addDoor(const std::shared_ptr<Door> &door); void removeDoor(const std::shared_ptr<Door> &door); std::shared_ptr<Door> getDoorByNumber(uint32_t doorId) const; - std::shared_ptr<Door> getDoorByPosition(const Position &pos); + std::shared_ptr<Door> getDoorByPosition(const Position &pos) const; std::shared_ptr<HouseTransferItem> getTransferItem(); void resetTransferItem(); @@ -284,7 +284,7 @@ class Houses { Houses &operator=(const Houses &) = delete; std::shared_ptr<House> addHouse(uint32_t id) { - if (auto it = houseMap.find(id); it != houseMap.end()) { + if (const auto it = houseMap.find(id); it != houseMap.end()) { return it->second; } @@ -292,14 +292,14 @@ class Houses { } std::shared_ptr<House> getHouse(uint32_t houseId) { - auto it = houseMap.find(houseId); + const auto it = houseMap.find(houseId); if (it == houseMap.end()) { return nullptr; } return it->second; } - std::shared_ptr<House> getHouseByPlayerId(uint32_t playerId); + std::shared_ptr<House> getHouseByPlayerId(uint32_t playerId) const; bool loadHousesXML(const std::string &filename); diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index 46588837691..b195302c26b 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -39,23 +39,23 @@ void HouseTile::internalAddThing(uint32_t index, const std::shared_ptr<Thing> &t return; } - if (const auto item = thing->getItem()) { + if (const auto &item = thing->getItem()) { updateHouse(item); } } -void HouseTile::updateHouse(const std::shared_ptr<Item> &item) { +void HouseTile::updateHouse(const std::shared_ptr<Item> &item) const { if (item->getParent().get() != this) { return; } - std::shared_ptr<Door> door = item->getDoor(); + const auto &door = item->getDoor(); if (door) { if (door->getDoorId() != 0) { house->addDoor(door); } } else { - std::shared_ptr<BedItem> bed = item->getBed(); + const auto &bed = item->getBed(); if (bed) { house->addBed(bed); } @@ -63,12 +63,12 @@ void HouseTile::updateHouse(const std::shared_ptr<Item> &item) { } ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { - if (std::shared_ptr<Creature> creature = thing->getCreature()) { + if (const auto &creature = thing->getCreature()) { if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { return RETURNVALUE_PLAYERISNOTINVITED; } - } else if (std::shared_ptr<Monster> monster = creature->getMonster()) { + } else if (const auto &monster = creature->getMonster()) { if (monster->isSummon()) { if (!house->isInvited(monster->getMaster()->getPlayer())) { return RETURNVALUE_NOTPOSSIBLE; @@ -81,7 +81,7 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thi } } } else if (thing->getItem() && actor) { - std::shared_ptr<Player> actorPlayer = actor->getPlayer(); + const auto &actorPlayer = actor->getPlayer(); if (house && (!house->isInvited(actorPlayer) || house->getHouseAccessLevel(actorPlayer) == HOUSE_GUEST) && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { return RETURNVALUE_CANNOTTHROW; } @@ -90,11 +90,11 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thi } std::shared_ptr<Cylinder> HouseTile::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &tileFlags) { - if (std::shared_ptr<Creature> creature = thing->getCreature()) { + if (const auto &creature = thing->getCreature()) { if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { const Position &entryPos = house->getEntryPosition(); - std::shared_ptr<Tile> destTile = g_game().map.getTile(entryPos); + auto destTile = g_game().map.getTile(entryPos); if (!destTile) { g_logger().error("[HouseTile::queryDestination] - " "Entry not correct for house name: {} " @@ -123,7 +123,7 @@ ReturnValue HouseTile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t } if (actor && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { - std::shared_ptr<Player> actorPlayer = actor->getPlayer(); + const auto &actorPlayer = actor->getPlayer(); if (house && !house->isInvited(actorPlayer)) { return RETURNVALUE_NOTPOSSIBLE; } else if (house && house->getHouseAccessLevel(actorPlayer) == HOUSE_GUEST) { diff --git a/src/map/house/housetile.hpp b/src/map/house/housetile.hpp index 56944b08672..eb71b78f27d 100644 --- a/src/map/house/housetile.hpp +++ b/src/map/house/housetile.hpp @@ -32,7 +32,7 @@ class HouseTile final : public DynamicTile { } private: - void updateHouse(const std::shared_ptr<Item> &item); + void updateHouse(const std::shared_ptr<Item> &item) const; std::shared_ptr<House> house; }; diff --git a/src/map/map.cpp b/src/map/map.cpp index bbff7970dc3..5e5c2fa9a94 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -163,7 +163,7 @@ std::shared_ptr<Tile> Map::getLoadedTile(uint16_t x, uint16_t y, uint8_t z) { return nullptr; } - const auto leaf = getMapSector(x, y); + const auto &leaf = getMapSector(x, y); if (!leaf) { return nullptr; } @@ -173,7 +173,7 @@ std::shared_ptr<Tile> Map::getLoadedTile(uint16_t x, uint16_t y, uint8_t z) { return nullptr; } - const auto tile = floor->getTile(x, y); + const auto &tile = floor->getTile(x, y); return tile; } @@ -182,7 +182,7 @@ std::shared_ptr<Tile> Map::getTile(uint16_t x, uint16_t y, uint8_t z) { return nullptr; } - const auto sector = getMapSector(x, y); + const auto §or = getMapSector(x, y); if (!sector) { return nullptr; } @@ -192,12 +192,12 @@ std::shared_ptr<Tile> Map::getTile(uint16_t x, uint16_t y, uint8_t z) { return nullptr; } - const auto tile = floor->getTile(x, y); + const auto &tile = floor->getTile(x, y); return tile ? tile : getOrCreateTileFromCache(floor, x, y); } void Map::refreshZones(uint16_t x, uint16_t y, uint8_t z) { - const auto tile = getLoadedTile(x, y, z); + const auto &tile = getLoadedTile(x, y, z); if (!tile) { return; } @@ -215,7 +215,7 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, const std::shared_ptr<Tile> return; } - if (const auto sector = getMapSector(x, y)) { + if (const auto §or = getMapSector(x, y)) { sector->createFloor(z)->setTile(x, y, newTile); } else { getBestMapSector(x, y)->createFloor(z)->setTile(x, y, newTile); @@ -223,7 +223,7 @@ void Map::setTile(uint16_t x, uint16_t y, uint8_t z, const std::shared_ptr<Tile> } bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr<Creature> &creature, bool extendedPos /* = false*/, bool forceLogin /* = false*/) { - auto monster = creature->getMonster(); + const auto &monster = creature->getMonster(); if (monster) { monster->ignoreFieldDamage = true; } @@ -231,10 +231,10 @@ bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr<Creatur bool foundTile; bool placeInPZ; - std::shared_ptr<Tile> tile = getTile(centerPos.x, centerPos.y, centerPos.z); + auto tile = getTile(centerPos.x, centerPos.y, centerPos.z); if (tile) { placeInPZ = tile->hasFlag(TILESTATE_PROTECTIONZONE); - ReturnValue ret = tile->queryAdd(0, creature, 1, FLAG_IGNOREBLOCKITEM | FLAG_IGNOREFIELDDAMAGE); + const ReturnValue ret = tile->queryAdd(0, creature, 1, FLAG_IGNOREBLOCKITEM | FLAG_IGNOREFIELDDAMAGE); foundTile = forceLogin || ret == RETURNVALUE_NOERROR || ret == RETURNVALUE_PLAYERISNOTINVITED; if (monster) { monster->ignoreFieldDamage = false; @@ -270,11 +270,11 @@ bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr<Creatur std::shuffle(relList.begin(), relList.begin() + 4, getRandomGenerator()); std::shuffle(relList.begin() + 4, relList.end(), getRandomGenerator()); } else { - std::shuffle(relList.begin(), relList.end(), getRandomGenerator()); + std::ranges::shuffle(relList, getRandomGenerator()); } - for (const auto &it : relList) { - Position tryPos(centerPos.x + it.first, centerPos.y + it.second, centerPos.z); + for (const auto &[fst, snd] : relList) { + Position tryPos(centerPos.x + fst, centerPos.y + snd, centerPos.z); tile = getTile(tryPos.x, tryPos.y, tryPos.z); if (!tile || (placeInPZ && !tile->hasFlag(TILESTATE_PROTECTIONZONE))) { @@ -311,7 +311,7 @@ bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr<Creatur uint32_t flags = 0; std::shared_ptr<Item> toItem = nullptr; - auto toCylinder = tile->queryDestination(index, creature, &toItem, flags); + const auto toCylinder = tile->queryDestination(index, creature, &toItem, flags); toCylinder->internalAddThing(creature); const Position &dest = toCylinder->getPosition(); @@ -336,11 +336,11 @@ void Map::moveCreature(const std::shared_ptr<Creature> &creature, const std::sha const auto &fromZones = oldTile->getZones(); const auto &toZones = newTile->getZones(); - if (auto ret = g_game().beforeCreatureZoneChange(creature, fromZones, toZones); ret != RETURNVALUE_NOERROR) { + if (const auto &ret = g_game().beforeCreatureZoneChange(creature, fromZones, toZones); ret != RETURNVALUE_NOERROR) { return; } - bool teleport = forceTeleport || !newTile->getGround() || !Position::areInRange<1, 1, 0>(oldPos, newPos); + const bool teleport = forceTeleport || !newTile->getGround() || !Position::areInRange<1, 1, 0>(oldPos, newPos); Spectators spectators; if (!teleport && oldPos.z == newPos.z) { @@ -367,15 +367,15 @@ void Map::moveCreature(const std::shared_ptr<Creature> &creature, const std::sha spectators.find<Creature>(newPos, true); } - auto playersSpectators = spectators.filter<Player>(); + const auto playersSpectators = spectators.filter<Player>(); std::vector<int32_t> oldStackPosVector; oldStackPosVector.reserve(playersSpectators.size()); for (const auto &spec : playersSpectators) { if (spec->canSeeCreature(creature)) { - oldStackPosVector.push_back(oldTile->getClientIndexOfCreature(spec->getPlayer(), creature)); + oldStackPosVector.emplace_back(oldTile->getClientIndexOfCreature(spec->getPlayer(), creature)); } else { - oldStackPosVector.push_back(-1); + oldStackPosVector.emplace_back(-1); } } @@ -412,7 +412,7 @@ void Map::moveCreature(const std::shared_ptr<Creature> &creature, const std::sha size_t i = 0; for (const auto &spectator : playersSpectators) { // Use the correct stackpos - int32_t stackpos = oldStackPosVector[i++]; + const int32_t stackpos = oldStackPosVector[i++]; if (stackpos != -1) { const auto &player = spectator->getPlayer(); player->sendCreatureMove(creature, newPos, newTile->getStackposOfCreature(player, creature), oldPos, stackpos, teleport); @@ -437,7 +437,7 @@ bool Map::canThrowObjectTo(const Position &fromPos, const Position &toPos, const return false; } - int32_t deltaz = Position::getDistanceZ(fromPos, toPos); + const int32_t deltaz = Position::getDistanceZ(fromPos, toPos); if (deltaz > MAP_LAYER_VIEW_LIMIT) { return false; } @@ -639,7 +639,7 @@ std::shared_ptr<Tile> Map::canWalkTo(const std::shared_ptr<Creature> &creature, return tile; } -bool Map::getPathMatching(const std::shared_ptr<Creature> &creature, const Position &__targetPos, std::vector<Direction> &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) { +bool Map::getPathMatching(const std::shared_ptr<Creature> &creature, const Position &_targetPos, std::vector<Direction> &dirList, const FrozenPathingConditionCall &pathCondition, const FindPathParams &fpp) { static int_fast32_t allNeighbors[8][2] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, -1 }, { 1, -1 }, { 1, 1 }, { -1, 1 } }; @@ -657,7 +657,7 @@ bool Map::getPathMatching(const std::shared_ptr<Creature> &creature, const Posit const bool withoutCreature = creature == nullptr; - Position pos = withoutCreature ? __targetPos : creature->getPosition(); + Position pos = withoutCreature ? _targetPos : creature->getPosition(); Position endPos; AStarNodes nodes(pos.x, pos.y, AStarNodes::getTileWalkCost(creature, getTile(pos.x, pos.y, pos.z))); @@ -665,14 +665,14 @@ bool Map::getPathMatching(const std::shared_ptr<Creature> &creature, const Posit int32_t bestMatch = 0; const auto &startPos = pos; - const auto &targetPos = withoutCreature ? pathCondition.getTargetPos() : __targetPos; + const auto &targetPos = withoutCreature ? pathCondition.getTargetPos() : _targetPos; const int_fast32_t sX = std::abs(targetPos.getX() - pos.getX()); const int_fast32_t sY = std::abs(targetPos.getY() - pos.getY()); uint_fast16_t cntDirs = 0; - AStarNode* found = nullptr; + const AStarNode* found = nullptr; do { AStarNode* n = nodes.getBestNode(); if (!n) { @@ -786,8 +786,8 @@ bool Map::getPathMatching(const std::shared_ptr<Creature> &creature, const Posit pos.x = found->x; pos.y = found->y; - int_fast32_t dx = pos.getX() - prevx; - int_fast32_t dy = pos.getY() - prevy; + const int_fast32_t dx = pos.getX() - prevx; + const int_fast32_t dy = pos.getY() - prevy; prevx = pos.x; prevy = pos.y; @@ -852,7 +852,7 @@ bool Map::getPathMatchingCond(const std::shared_ptr<Creature> &creature, const P uint_fast16_t cntDirs = 0; - AStarNode* found = nullptr; + const AStarNode* found = nullptr; do { AStarNode* n = nodes.getBestNode(); if (!n) { @@ -974,8 +974,8 @@ bool Map::getPathMatchingCond(const std::shared_ptr<Creature> &creature, const P pos.x = found->x; pos.y = found->y; - int_fast32_t dx = pos.getX() - prevx; - int_fast32_t dy = pos.getY() - prevy; + const int_fast32_t dx = pos.getX() - prevx; + const int_fast32_t dy = pos.getY() - prevy; prevx = pos.x; prevy = pos.y; @@ -1006,8 +1006,8 @@ bool Map::getPathMatchingCond(const std::shared_ptr<Creature> &creature, const P return true; } -uint32_t Map::clean() { - uint64_t start = OTSYS_TIME(); +uint32_t Map::clean() const { + const uint64_t start = OTSYS_TIME(); size_t qntTiles = 0; if (g_game().getGameState() == GAME_STATE_NORMAL) { @@ -1022,7 +1022,7 @@ uint32_t Map::clean() { continue; } - if (const auto items = tile->getItemList()) { + if (const auto &items = tile->getItemList()) { ++qntTiles; for (const auto &item : *items) { if (item->isCleanable()) { @@ -1043,7 +1043,7 @@ uint32_t Map::clean() { g_game().setGameState(GAME_STATE_NORMAL); } - uint64_t end = OTSYS_TIME(); + const uint64_t end = OTSYS_TIME(); g_logger().info("CLEAN: Removed {} item{} from {} tile{} in {} seconds", count, (count != 1 ? "s" : ""), qntTiles, (qntTiles != 1 ? "s" : ""), (end - start) / (1000.f)); return count; } diff --git a/src/map/map.hpp b/src/map/map.hpp index 787eb584570..d4e8774c5e4 100644 --- a/src/map/map.hpp +++ b/src/map/map.hpp @@ -31,9 +31,9 @@ class FrozenPathingConditionCall; * Map class. * Holds all the actual map-data */ -class Map : public MapCache { +class Map final : public MapCache { public: - uint32_t clean(); + uint32_t clean() const; std::filesystem::path getPath() const { return path; diff --git a/src/map/mapcache.cpp b/src/map/mapcache.cpp index 6d05b68a76b..dab88ca8f90 100644 --- a/src/map/mapcache.cpp +++ b/src/map/mapcache.cpp @@ -35,12 +35,12 @@ std::shared_ptr<BasicTile> static_tryGetTileFromCache(const std::shared_ptr<Basi return ref ? tiles.try_emplace(ref->hash(), ref).first->second : nullptr; } -void MapCache::flush() { +void MapCache::flush() const { items.clear(); tiles.clear(); } -void MapCache::parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const std::shared_ptr<Item> &item) { +void MapCache::parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const std::shared_ptr<Item> &item) const { if (BasicItem->charges > 0) { item->setSubType(BasicItem->charges); } @@ -54,7 +54,7 @@ void MapCache::parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const } if (item->getTeleport() && (BasicItem->destX != 0 || BasicItem->destY != 0 || BasicItem->destZ != 0)) { - auto dest = Position(BasicItem->destX, BasicItem->destY, BasicItem->destZ); + const auto dest = Position(BasicItem->destX, BasicItem->destY, BasicItem->destZ); item->getTeleport()->setDestPos(dest); } @@ -75,7 +75,7 @@ void MapCache::parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const } std::shared_ptr<Item> MapCache::createItem(const std::shared_ptr<BasicItem> &BasicItem, Position position) { - auto item = Item::CreateItem(BasicItem->id, position); + const auto &item = Item::CreateItem(BasicItem->id, position); if (!item) { return nullptr; } @@ -103,7 +103,7 @@ std::shared_ptr<Item> MapCache::createItem(const std::shared_ptr<BasicItem> &Bas } std::shared_ptr<Tile> MapCache::getOrCreateTileFromCache(const std::unique_ptr<Floor> &floor, uint16_t x, uint16_t y) { - const auto cachedTile = floor->getTileCache(x, y); + const auto &cachedTile = floor->getTileCache(x, y); if (!cachedTile) { return floor->getTile(x, y); } @@ -112,11 +112,11 @@ std::shared_ptr<Tile> MapCache::getOrCreateTileFromCache(const std::unique_ptr<F const uint8_t z = floor->getZ(); - auto map = dynamic_cast<Map*>(this); + const auto map = dynamic_cast<Map*>(this); std::shared_ptr<Tile> tile = nullptr; if (cachedTile->isHouse()) { - const auto house = map->houses.getHouse(cachedTile->houseId); + const auto &house = map->houses.getHouse(cachedTile->houseId); tile = std::make_shared<HouseTile>(x, y, z, house); house->addTile(std::static_pointer_cast<HouseTile>(tile)); } else if (cachedTile->isStatic) { @@ -159,7 +159,7 @@ void MapCache::setBasicTile(uint16_t x, uint16_t y, uint8_t z, const std::shared return; } - const auto tile = static_tryGetTileFromCache(newTile); + const auto &tile = static_tryGetTileFromCache(newTile); if (const auto sector = getMapSector(x, y)) { sector->createFloor(z)->setTileCache(x, y, tile); } else { @@ -167,7 +167,7 @@ void MapCache::setBasicTile(uint16_t x, uint16_t y, uint8_t z, const std::shared } } -std::shared_ptr<BasicItem> MapCache::tryReplaceItemFromCache(const std::shared_ptr<BasicItem> &ref) { +std::shared_ptr<BasicItem> MapCache::tryReplaceItemFromCache(const std::shared_ptr<BasicItem> &ref) const { return static_tryGetItemFromCache(ref); } @@ -212,7 +212,7 @@ MapSector* MapCache::getBestMapSector(uint32_t x, uint32_t y) { } void BasicTile::hash(size_t &h) const { - std::array<uint32_t, 4> arr = { flags, houseId, type, isStatic }; + const std::array<uint32_t, 4> arr = { flags, houseId, type, isStatic }; for (const auto v : arr) { if (v > 0) { stdext::hash_combine(h, v); diff --git a/src/map/mapcache.hpp b/src/map/mapcache.hpp index 1fea84885b5..932575b602d 100644 --- a/src/map/mapcache.hpp +++ b/src/map/mapcache.hpp @@ -15,7 +15,7 @@ class Map; class Tile; class Item; -class Position; +struct Position; class FileStream; #pragma pack(1) @@ -47,7 +47,7 @@ struct BasicItem { private: void hash(size_t &h) const; - friend class BasicTile; + friend struct BasicTile; }; struct BasicTile { @@ -85,9 +85,9 @@ class MapCache { void setBasicTile(uint16_t x, uint16_t y, uint8_t z, const std::shared_ptr<BasicTile> &BasicTile); - std::shared_ptr<BasicItem> tryReplaceItemFromCache(const std::shared_ptr<BasicItem> &ref); + std::shared_ptr<BasicItem> tryReplaceItemFromCache(const std::shared_ptr<BasicItem> &ref) const; - void flush(); + void flush() const; /** * Creates a map sector. @@ -116,6 +116,6 @@ class MapCache { std::unordered_map<uint32_t, MapSector> mapSectors; private: - void parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const std::shared_ptr<Item> &item); + void parseItemAttr(const std::shared_ptr<BasicItem> &BasicItem, const std::shared_ptr<Item> &item) const; std::shared_ptr<Item> createItem(const std::shared_ptr<BasicItem> &BasicItem, Position position); }; diff --git a/src/map/spectators.hpp b/src/map/spectators.hpp index 9e998da2bfa..41487b7996a 100644 --- a/src/map/spectators.hpp +++ b/src/map/spectators.hpp @@ -44,7 +44,7 @@ class Spectators { template <typename T> requires std::is_base_of_v<Creature, T> - Spectators filter(); + Spectators filter() const; Spectators insert(const std::shared_ptr<Creature> &creature); Spectators insertAll(const CreatureVector &list); @@ -91,7 +91,7 @@ class Spectators { template <typename T> requires std::is_base_of_v<Creature, T> -Spectators Spectators::filter() { +Spectators Spectators::filter() const { auto specs = Spectators(); specs.creatures.reserve(creatures.size()); diff --git a/src/map/town.hpp b/src/map/town.hpp index d6529fa30ef..911a683c70d 100644 --- a/src/map/town.hpp +++ b/src/map/town.hpp @@ -55,16 +55,16 @@ class Towns { } std::shared_ptr<Town> getTown(const std::string &townName) const { - for (const auto &it : townMap) { - if (strcasecmp(townName.c_str(), it.second->getName().c_str()) == 0) { - return it.second; + for (const auto &[fst, snd] : townMap) { + if (strcasecmp(townName.c_str(), snd->getName().c_str()) == 0) { + return snd; } } return nullptr; } std::shared_ptr<Town> getTown(uint32_t townId) const { - auto it = townMap.find(townId); + const auto it = townMap.find(townId); if (it == townMap.end()) { return nullptr; } diff --git a/src/map/utils/astarnodes.cpp b/src/map/utils/astarnodes.cpp index e8df3ce9c32..220843fc44e 100644 --- a/src/map/utils/astarnodes.cpp +++ b/src/map/utils/astarnodes.cpp @@ -57,7 +57,7 @@ bool AStarNodes::createOpenNode(AStarNode* parent, uint32_t x, uint32_t y, int_f return false; } - int32_t retNode = curNode++; + const int32_t retNode = curNode++; openNodes[retNode] = true; AStarNode &node = nodes[retNode]; @@ -120,8 +120,8 @@ AStarNode* AStarNodes::getBestNode() { alignas(32) int32_t indices_array[8]; _mm256_store_si256(reinterpret_cast<__m256i*>(indices_array), minindices); - int32_t best_node = indices_array[(_mm_ctz(_mm256_movemask_epi8(_mm256_cmpeq_epi32(minvalues, res))) >> 2)]; - return (openNodes[best_node] ? &nodes[best_node] : NULL); + int32_t best_node = indices_array[(mm_ctz(_mm256_movemask_epi8(_mm256_cmpeq_epi32(minvalues, res))) >> 2)]; + return (openNodes[best_node] ? &nodes[best_node] : nullptr); #elif defined(__SSE4_1__) const __m128i increment = _mm_set1_epi32(4); __m128i indices = _mm_setr_epi32(0, 1, 2, 3); @@ -140,7 +140,7 @@ AStarNode* AStarNodes::getBestNode() { alignas(16) int32_t indices_array[4]; _mm_store_si128(reinterpret_cast<__m128i*>(indices_array), minindices); - int32_t best_node = indices_array[(_mm_ctz(_mm_movemask_epi8(_mm_cmpeq_epi32(minvalues, res))) >> 2)]; + int32_t best_node = indices_array[(mm_ctz(_mm_movemask_epi8(_mm_cmpeq_epi32(minvalues, res))) >> 2)]; return (openNodes[best_node] ? &nodes[best_node] : NULL); #elif defined(__SSE2__) auto _mm_sse2_min_epi32 = [](const __m128i a, const __m128i b) { @@ -170,7 +170,7 @@ AStarNode* AStarNodes::getBestNode() { alignas(16) int32_t indices_array[4]; _mm_store_si128(reinterpret_cast<__m128i*>(indices_array), minindices); - int32_t best_node = indices_array[(_mm_ctz(_mm_movemask_epi8(_mm_cmpeq_epi32(minvalues, res))) >> 2)]; + int32_t best_node = indices_array[(mm_ctz(_mm_movemask_epi8(_mm_cmpeq_epi32(minvalues, res))) >> 2)]; return (openNodes[best_node] ? &nodes[best_node] : nullptr); #else int32_t best_node_f = std::numeric_limits<int32_t>::max(); @@ -227,7 +227,7 @@ AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) { v[3] = _mm_cmpeq_epi32(_mm_load_si128(reinterpret_cast<const __m128i*>(&nodesTable[pos + 12])), key); const uint32_t mask = _mm_movemask_epi8(_mm_packs_epi16(_mm_packs_epi32(v[0], v[1]), _mm_packs_epi32(v[2], v[3]))); if (mask != 0) { - return &nodes[pos + _mm_ctz(mask)]; + return &nodes[pos + mm_ctz(mask)]; } } curRound = curNode - 8; @@ -237,7 +237,7 @@ AStarNode* AStarNodes::getNodeByPosition(uint32_t x, uint32_t y) { v[1] = _mm_cmpeq_epi32(_mm_load_si128(reinterpret_cast<const __m128i*>(&nodesTable[pos + 4])), key); const uint32_t mask = _mm_movemask_epi8(_mm_packs_epi32(v[0], v[1])); if (mask != 0) { - return &nodes[pos + (_mm_ctz(mask) >> 1)]; + return &nodes[pos + (mm_ctz(mask) >> 1)]; } pos += 8; } @@ -271,7 +271,7 @@ int_fast32_t AStarNodes::getTileWalkCost(const std::shared_ptr<Creature> &creatu cost += MAP_NORMALWALKCOST * 4; } if (const auto &field = tile->getFieldItem()) { - CombatType_t combatType = field->getCombatType(); + const CombatType_t combatType = field->getCombatType(); if (!creature->isImmune(combatType) && !creature->hasCondition(Combat::DamageToConditionType(combatType)) && (creature->getMonster() && !creature->getMonster()->canWalkOnFieldType(combatType))) { cost += MAP_NORMALWALKCOST * 18; } diff --git a/src/map/utils/mapsector.cpp b/src/map/utils/mapsector.cpp index de036728b76..37fe6bcec0d 100644 --- a/src/map/utils/mapsector.cpp +++ b/src/map/utils/mapsector.cpp @@ -22,7 +22,7 @@ void MapSector::addCreature(const std::shared_ptr<Creature> &c) { } void MapSector::removeCreature(const std::shared_ptr<Creature> &c) { - auto iter = std::find(creature_list.begin(), creature_list.end(), c); + auto iter = std::ranges::find(creature_list, c); if (iter == creature_list.end()) { g_logger().error("[{}]: Creature not found in creature_list!", __FUNCTION__); return; @@ -33,7 +33,7 @@ void MapSector::removeCreature(const std::shared_ptr<Creature> &c) { creature_list.pop_back(); if (c->getPlayer()) { - iter = std::find(player_list.begin(), player_list.end(), c); + iter = std::ranges::find(player_list, c); if (iter == player_list.end()) { g_logger().error("[{}]: Player not found in player_list!", __FUNCTION__); return; diff --git a/src/pch.hpp b/src/pch.hpp index e69c27016a4..26a88d2ea48 100644 --- a/src/pch.hpp +++ b/src/pch.hpp @@ -172,9 +172,9 @@ struct fmt::formatter<E, std::enable_if_t<std::is_enum_v<E>, char>> : formatter< #include "lua/global/shared_object.hpp" constexpr std::string_view methodName(const char* s) { - std::string_view prettyFunction(s); - size_t bracket = prettyFunction.rfind('('); - size_t space = prettyFunction.rfind(' ', bracket) + 1; + const std::string_view prettyFunction(s); + const size_t bracket = prettyFunction.rfind('('); + const size_t space = prettyFunction.rfind(' ', bracket) + 1; return prettyFunction.substr(space, bracket - space); } diff --git a/src/security/argon.cpp b/src/security/argon.cpp index c788ee91d17..c6bae844949 100644 --- a/src/security/argon.cpp +++ b/src/security/argon.cpp @@ -48,8 +48,8 @@ bool Argon2::verifyPassword(const std::string &password, const std::string &phas return false; } - std::vector<uint8_t> salt = base64_decode(match[1]); - std::vector<uint8_t> hash = base64_decode(match[2]); + const std::vector<uint8_t> salt = base64_decode(match[1]); + const std::vector<uint8_t> hash = base64_decode(match[2]); // Hash the password std::vector<uint8_t> computed_hash(hash.size()); @@ -67,12 +67,12 @@ std::vector<uint8_t> Argon2::base64_decode(const std::string &input) { std::vector<uint8_t> ret; int i = 0; uint32_t val = 0; - for (char c : input) { + for (const char c : input) { if (isspace(c) || c == '=') { continue; } - size_t pos = base64_chars.find(c); + const size_t pos = base64_chars.find(c); if (pos == std::string::npos) { g_logger().warn("Invalid character in base64 string"); } else if (pos > std::numeric_limits<uint32_t>::max()) { @@ -82,9 +82,9 @@ std::vector<uint8_t> Argon2::base64_decode(const std::string &input) { } if (++i % 4 == 0) { - ret.push_back((val >> 16) & 0xFF); - ret.push_back((val >> 8) & 0xFF); - ret.push_back(val & 0xFF); + ret.emplace_back((val >> 16) & 0xFF); + ret.emplace_back((val >> 8) & 0xFF); + ret.emplace_back(val & 0xFF); } } @@ -93,11 +93,11 @@ std::vector<uint8_t> Argon2::base64_decode(const std::string &input) { g_logger().warn("Invalid length for base64 string"); break; case 2: - ret.push_back((val >> 4) & 0xFF); + ret.emplace_back((val >> 4) & 0xFF); break; case 3: - ret.push_back((val >> 10) & 0xFF); - ret.push_back((val >> 2) & 0xFF); + ret.emplace_back((val >> 10) & 0xFF); + ret.emplace_back((val >> 2) & 0xFF); break; default: g_logger().warn("Unexpected remainder when dividing string length by 4"); diff --git a/src/security/rsa.cpp b/src/security/rsa.cpp index 2b8948afa07..f152cb45c51 100644 --- a/src/security/rsa.cpp +++ b/src/security/rsa.cpp @@ -28,8 +28,8 @@ RSA &RSA::getInstance() { } void RSA::start() { - const char* p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113"); - const char* q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101"); + const auto p("14299623962416399520070177382898895550795403345466153217470516082934737582776038882967213386204600674145392845853859217990626450972452084065728686565928113"); + const auto q("7630979195970404721891201847792002125535401292779123937207447574596692788513647179235335529307251350570728407373705564708871762033017096809910315212884101"); try { if (!loadPEM("key.pem")) { // file doesn't exist - switch to base10-hardcoded keys @@ -97,7 +97,7 @@ void RSA::decrypt(char* msg) const { // m = c^d mod n mpz_powm(m, c, d, n); - size_t count = (mpz_sizeinbase(m, 2) + 7) / 8; + const size_t count = (mpz_sizeinbase(m, 2) + 7) / 8; memset(msg, 0, 128 - count); mpz_export(msg + (128 - count), nullptr, 1, 1, 0, 0, m); @@ -109,13 +109,17 @@ std::string RSA::base64Decrypt(const std::string &input) const { auto posOfCharacter = [](const uint8_t chr) -> uint16_t { if (chr >= 'A' && chr <= 'Z') { return chr - 'A'; - } else if (chr >= 'a' && chr <= 'z') { + } + if (chr >= 'a' && chr <= 'z') { return chr - 'a' + ('Z' - 'A') + 1; - } else if (chr >= '0' && chr <= '9') { + } + if (chr >= '0' && chr <= '9') { return chr - '0' + ('Z' - 'A') + ('z' - 'a') + 2; - } else if (chr == '+' || chr == '-') { + } + if (chr == '+' || chr == '-') { return 62; - } else if (chr == '/' || chr == '_') { + } + if (chr == '/' || chr == '_') { return 63; } g_logger().error("[RSA::base64Decrypt] - Invalid base6409"); @@ -126,16 +130,16 @@ std::string RSA::base64Decrypt(const std::string &input) const { return {}; } - size_t length = input.length(); + const size_t length = input.length(); size_t pos = 0; std::string output; output.reserve(length / 4 * 3); while (pos < length) { - uint16_t pos1 = posOfCharacter(input[pos + 1]); + const uint16_t pos1 = posOfCharacter(input[pos + 1]); output.push_back(static_cast<std::string::value_type>(((posOfCharacter(input[pos])) << 2) + ((pos1 & 0x30) >> 4))); if (input[pos + 2] != '=' && input[pos + 2] != '.') { - uint16_t pos2 = posOfCharacter(input[pos + 2]); + const uint16_t pos2 = posOfCharacter(input[pos + 2]); output.push_back(static_cast<std::string::value_type>(((pos1 & 0x0f) << 4) + ((pos2 & 0x3c) >> 2))); if (input[pos + 3] != '=' && input[pos + 3] != '.') { output.push_back(static_cast<std::string::value_type>(((pos2 & 0x03) << 6) + posOfCharacter(input[pos + 3]))); @@ -183,7 +187,7 @@ uint16_t RSA::decodeLength(char*&pos) const { } #if defined(__SSE2__) - __m128i temp = _mm_loadu_si128(reinterpret_cast<const __m128i*>(buffer)); + const __m128i temp = _mm_loadu_si128(reinterpret_cast<const __m128i*>(buffer)); length = _mm_cvtsi128_si32(temp); #else std::memcpy(&length, buffer, sizeof(length)); @@ -195,7 +199,7 @@ uint16_t RSA::decodeLength(char*&pos) const { void RSA::readHexString(char*&pos, uint16_t length, std::string &output) const { output.reserve(static_cast<size_t>(length) * 2); for (uint16_t i = 0; i < length; ++i) { - auto hex = static_cast<uint8_t>(*pos++); + const auto hex = static_cast<uint8_t>(*pos++); output.push_back("0123456789ABCDEF"[(hex >> 4) & 15]); output.push_back("0123456789ABCDEF"[hex & 15]); } diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index 4a4732ba711..a2626d91b97 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -133,35 +133,33 @@ void Connection::parseProxyIdentification(const std::error_code &error) { } uint8_t* msgBuffer = msg.getBuffer(); - auto charData = static_cast<char*>(static_cast<void*>(msgBuffer)); - std::string serverName = g_configManager().getString(SERVER_NAME, __FUNCTION__) + "\n"; + const auto charData = static_cast<char*>(static_cast<void*>(msgBuffer)); + const std::string serverName = g_configManager().getString(SERVER_NAME, __FUNCTION__) + "\n"; if (connectionState == CONNECTION_STATE_IDENTIFYING) { if (msgBuffer[1] == 0x00 || strncasecmp(charData, &serverName[0], 2) != 0) { // Probably not proxy identification so let's try standard parsing method connectionState = CONNECTION_STATE_OPEN; parseHeader(error); return; - } else { - size_t remainder = serverName.length() - 2; - if (remainder > 0) { - connectionState = CONNECTION_STATE_READINGS; - try { - readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); - readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { Connection::handleTimeout(self, error); }); - - // Read the remainder of proxy identification - asio::async_read(socket, asio::buffer(msg.getBuffer(), remainder), [self = shared_from_this()](const std::error_code &error, std::size_t N) { self->parseProxyIdentification(error); }); - } catch (const std::system_error &e) { - g_logger().error("Connection::parseProxyIdentification] - error: {}", e.what()); - close(FORCE_CLOSE); - } - return; - } else { - connectionState = CONNECTION_STATE_OPEN; + } + const size_t remainder = serverName.length() - 2; + if (remainder > 0) { + connectionState = CONNECTION_STATE_READINGS; + try { + readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); + readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { Connection::handleTimeout(self, error); }); + + // Read the remainder of proxy identification + asio::async_read(socket, asio::buffer(msg.getBuffer(), remainder), [self = shared_from_this()](const std::error_code &error, std::size_t N) { self->parseProxyIdentification(error); }); + } catch (const std::system_error &e) { + g_logger().error("Connection::parseProxyIdentification] - error: {}", e.what()); + close(FORCE_CLOSE); } + return; } + connectionState = CONNECTION_STATE_OPEN; } else if (connectionState == CONNECTION_STATE_READINGS) { - size_t remainder = serverName.length() - 2; + const size_t remainder = serverName.length() - 2; if (strncasecmp(charData, &serverName[2], remainder) == 0) { connectionState = CONNECTION_STATE_OPEN; } else { @@ -184,11 +182,12 @@ void Connection::parseHeader(const std::error_code &error) { } close(FORCE_CLOSE); return; - } else if (connectionState == CONNECTION_STATE_CLOSED) { + } + if (connectionState == CONNECTION_STATE_CLOSED) { return; } - uint32_t timePassed = std::max<uint32_t>(1, (time(nullptr) - timeConnected) + 1); + const uint32_t timePassed = std::max<uint32_t>(1, (time(nullptr) - timeConnected) + 1); if ((++packetsSent / timePassed) > static_cast<uint32_t>(g_configManager().getNumber(MAX_PACKETS_PER_SECOND, __FUNCTION__))) { g_logger().warn("[Connection::parseHeader] - {} disconnected for exceeding packet per second limit.", convertIPToString(getIP())); close(); @@ -200,7 +199,7 @@ void Connection::parseHeader(const std::error_code &error) { packetsSent = 0; } - uint16_t size = msg.getLengthHeader(); + const uint16_t size = msg.getLengthHeader(); if (size == 0 || size > INPUTMESSAGE_MAXSIZE) { close(FORCE_CLOSE); return; @@ -240,14 +239,14 @@ void Connection::parsePacket(const std::error_code &error) { if (!protocol) { // Check packet checksum uint32_t checksum; - if (int32_t len = msg.getLength() - msg.getBufferPosition() - CHECKSUM_LENGTH; + if (const int32_t len = msg.getLength() - msg.getBufferPosition() - CHECKSUM_LENGTH; len > 0) { checksum = adlerChecksum(msg.getBuffer() + msg.getBufferPosition() + CHECKSUM_LENGTH, len); } else { checksum = 0; } - auto recvChecksum = msg.get<uint32_t>(); + const auto recvChecksum = msg.get<uint32_t>(); if (recvChecksum != checksum) { // it might not have been the checksum, step back msg.skipBytes(-CHECKSUM_LENGTH); @@ -305,7 +304,7 @@ void Connection::send(const OutputMessage_ptr &outputMessage) { return; } - bool noPendingWrite = messageQueue.empty(); + const bool noPendingWrite = messageQueue.empty(); messageQueue.emplace_back(outputMessage); if (noPendingWrite) { @@ -337,7 +336,13 @@ void Connection::internalWorker() { protocol->onSendMessage(outputMessage); lock.lock(); - internalSend(outputMessage); + try { + asio::post(socket.get_executor(), [self = shared_from_this(), outputMessage] { self->internalSend(outputMessage); }); + } catch (std::system_error& e) { + g_logger().error("[Connection::internalWorker] - error: {}", e.what()); + messageQueue.clear(); + close(FORCE_CLOSE); + } } uint32_t Connection::getIP() { @@ -345,7 +350,7 @@ uint32_t Connection::getIP() { if (ip == 1) { std::error_code error; - asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(error); + const asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(error); if (error) { g_logger().error("[Connection::getIP] - Failed to get remote endpoint: {}", error.message()); ip = 0; @@ -386,7 +391,13 @@ void Connection::onWriteOperation(const std::error_code &error) { lock.unlock(); protocol->onSendMessage(outputMessage); lock.lock(); - internalSend(outputMessage); + try { + asio::post(socket.get_executor(), [self = shared_from_this(), outputMessage] { self->internalSend(outputMessage); }); + } catch (std::system_error& e) { + g_logger().error("[Connection::onWriteOperation] - error: {}", e.what()); + messageQueue.clear(); + close(FORCE_CLOSE); + } } else if (connectionState == CONNECTION_STATE_CLOSED) { closeSocket(); } @@ -397,7 +408,7 @@ void Connection::handleTimeout(const ConnectionWeak_ptr &connectionWeak, const s return; } - if (auto connection = connectionWeak.lock()) { + if (const auto connection = connectionWeak.lock()) { if (!error) { g_logger().debug("Connection Timeout, IP: {}", convertIPToString(connection->getIP())); } else { diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index 6f461004e34..e607225fa76 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -13,7 +13,7 @@ #include "items/containers/container.hpp" int32_t NetworkMessage::decodeHeader() { - int32_t newSize = buffer[0] | buffer[1] << 8; + const int32_t newSize = buffer[0] | buffer[1] << 8; info.length = newSize; return info.length; } @@ -24,10 +24,10 @@ std::string NetworkMessage::getString(uint16_t stringLen /* = 0*/) { } if (!canRead(stringLen)) { - return std::string(); + return {}; } - char* v = reinterpret_cast<char*>(buffer) + info.position; // does not break strict aliasing + const char* v = reinterpret_cast<char*>(buffer) + info.position; // does not break strict aliasing info.position += stringLen; return std::string(v, stringLen); } diff --git a/src/server/network/message/outputmessage.cpp b/src/server/network/message/outputmessage.cpp index 68daee2afd9..b1882a7c306 100644 --- a/src/server/network/message/outputmessage.cpp +++ b/src/server/network/message/outputmessage.cpp @@ -47,7 +47,7 @@ void OutputMessagePool::addProtocolToAutosend(const Protocol_ptr &protocol) { void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr &protocol) { // dispatcher thread - auto it = std::ranges::find(bufferedProtocols.begin(), bufferedProtocols.end(), protocol); + const auto it = std::ranges::find(bufferedProtocols.begin(), bufferedProtocols.end(), protocol); if (it != bufferedProtocols.end()) { *it = bufferedProtocols.back(); bufferedProtocols.pop_back(); diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index ecfd21d8cca..c48f1ddd361 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -14,6 +14,12 @@ #include "security/rsa.hpp" #include "game/scheduling/dispatcher.hpp" +#ifdef _WIN32 + #include <malloc.h> // Para _aligned_malloc e _aligned_free no Windows +#else + #include <cstdlib> // Para std::aligned_alloc e std::free em Linux +#endif + void Protocol::onSendMessage(const OutputMessage_ptr &msg) { if (!rawMessages) { const uint32_t sendMessageChecksum = msg->getLength() >= 128 && compression(*msg) ? (1U << 31) : 0; @@ -45,8 +51,8 @@ bool Protocol::sendRecvMessageCallback(NetworkMessage &msg) { } g_dispatcher().addEvent([&msg, protocolWeak = std::weak_ptr<Protocol>(shared_from_this())]() { - if (auto protocol = protocolWeak.lock()) { - if (auto protocolConnection = protocol->getConnection()) { + if (const auto protocol = protocolWeak.lock()) { + if (const auto protocolConnection = protocol->getConnection()) { protocol->parsePacket(msg); protocolConnection->resumeWork(); } @@ -57,7 +63,7 @@ bool Protocol::sendRecvMessageCallback(NetworkMessage &msg) { bool Protocol::onRecvMessage(NetworkMessage &msg) { if (checksumMethod != CHECKSUM_METHOD_NONE) { - auto recvChecksum = msg.get<uint32_t>(); + const auto recvChecksum = msg.get<uint32_t>(); if (checksumMethod == CHECKSUM_METHOD_SEQUENCE) { if (recvChecksum == 0) { // checksum 0 indicate that the packet should be connection ping - 0x1C packet header @@ -65,8 +71,7 @@ bool Protocol::onRecvMessage(NetworkMessage &msg) { return false; } - uint32_t checksum; - checksum = ++clientSequenceNumber; + const uint32_t checksum = ++clientSequenceNumber; if (clientSequenceNumber >= 0x7FFFFFFF) { clientSequenceNumber = 0; } @@ -77,7 +82,7 @@ bool Protocol::onRecvMessage(NetworkMessage &msg) { } } else { uint32_t checksum; - if (int32_t len = msg.getLength() - msg.getBufferPosition(); + if (const int32_t len = msg.getLength() - msg.getBufferPosition(); len > 0) { checksum = adlerChecksum(msg.getBuffer() + msg.getBufferPosition(), len); } else { @@ -106,10 +111,8 @@ OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) { } void Protocol::XTEA_encrypt(OutputMessage &msg) const { - const uint32_t delta = 0x61C88647; - - // The message must be a multiple of 8 - size_t paddingBytes = msg.getLength() & 7; + // A mensagem deve ser múltiplo de 8 + const size_t paddingBytes = msg.getLength() & 7; if (paddingBytes != 0) { msg.addPaddingBytes(8 - paddingBytes); } @@ -117,104 +120,157 @@ void Protocol::XTEA_encrypt(OutputMessage &msg) const { uint8_t* buffer = msg.getOutputBuffer(); auto messageLength = static_cast<int32_t>(msg.getLength()); int32_t readPos = 0; - const std::array<uint32_t, 4> newKey = { key[0], key[1], key[2], key[3] }; - // TODO: refactor this for not use c-style - uint32_t precachedControlSum[32][2]; - uint32_t sum = 0; - for (auto &i : precachedControlSum) { - i[0] = (sum + newKey[sum & 3]); - sum -= delta; - i[1] = (sum + newKey[(sum >> 11) & 3]); - } - while (readPos < messageLength) { - std::array<uint32_t, 2> vData = {}; - -#if defined(__AVX2__) - __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(buffer + readPos)); - _mm_storeu_si128(reinterpret_cast<__m128i*>(vData.data()), data); -#elif defined(__SSE2__) - __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(buffer + readPos)); - _mm_storel_epi64(reinterpret_cast<__m128i*>(vData.data()), data); + // Precache das somas de controle para criptografia + precacheControlSumsEncrypt(); + + // Alocar memória alinhada +#ifdef _WIN32 + auto* alignedBuffer = static_cast<uint8_t*>(_aligned_malloc(messageLength, 32)); #else - memcpy(vData.data(), buffer + readPos, 8); + uint8_t* alignedBuffer = reinterpret_cast<uint8_t*>(std::aligned_alloc(32, messageLength)); #endif - // XTEA encryption loop - for (auto &i : precachedControlSum) { - vData[0] += ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ i[0]; - vData[1] += ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ i[1]; - } + if (!alignedBuffer) { + throw std::bad_alloc(); // Tratar erro de alocação + } -#if defined(__AVX2__) - data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(vData.data())); - _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + readPos), data); -#elif defined(__SSE2__) - data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(vData.data())); - _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + readPos), data); -#else - memcpy(buffer + readPos, vData.data(), 8); -#endif + // Copiar os dados para o buffer alinhado usando AVX2 + simd_memcpy_avx2(alignedBuffer, buffer, messageLength); + + // Processar em blocos de 64 bits + while (readPos < messageLength) { + // Prefetch para reduzir a latência da memória + _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer + readPos + 64), _MM_HINT_T0); + + // Carregar 64 bits (dois inteiros de 32 bits) do buffer alinhado com AVX2 + __m256i vData = _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer + readPos)); + + auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); + + // Desenrolar o loop em grupos de 8 para melhor uso do pipeline + for (int32_t i = 0; i < 32; i += 8) { + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[i * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[i * 2 + 1]; + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 1) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 1) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 2) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 2) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 3) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 3) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 4) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 4) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 5) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 5) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 6) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 6) * 2 + 1]; + + vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 7) * 2]; + vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 7) * 2 + 1]; + } + + // Armazenar os resultados de volta no buffer alinhado com AVX2 + _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer + readPos), vData); readPos += 8; } + + // Copiar o buffer processado de volta para o buffer original usando AVX2 + simd_memcpy_avx2(buffer, alignedBuffer, messageLength); + + // Liberar memória alinhada +#ifdef _WIN32 + _aligned_free(alignedBuffer); +#else + std::free(alignedBuffer); +#endif } bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { - uint16_t msgLength = msg.getLength() - (checksumMethod == CHECKSUM_METHOD_NONE ? 2 : 6); + const uint16_t msgLength = msg.getLength() - (checksumMethod == CHECKSUM_METHOD_NONE ? 2 : 6); if ((msgLength & 7) != 0) { return false; } - const uint32_t delta = 0x61C88647; - uint8_t* buffer = msg.getBuffer() + msg.getBufferPosition(); auto messageLength = static_cast<int32_t>(msgLength); int32_t readPos = 0; - const std::array<uint32_t, 4> newKey = { key[0], key[1], key[2], key[3] }; - // TODO: refactor this for not use c-style - uint32_t precachedControlSum[32][2]; - uint32_t sum = 0xC6EF3720; - for (auto &i : precachedControlSum) { - i[0] = (sum + newKey[(sum >> 11) & 3]); - sum += delta; - i[1] = (sum + newKey[sum & 3]); - } - while (readPos < messageLength) { - std::array<uint32_t, 2> vData = {}; - -#if defined(__AVX2__) - __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(buffer + readPos)); - _mm_storeu_si128(reinterpret_cast<__m128i*>(vData.data()), data); -#elif defined(__SSE2__) - __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(buffer + readPos)); - _mm_storel_epi64(reinterpret_cast<__m128i*>(vData.data()), data); + // Precache das somas de controle para descriptografia + precacheControlSumsDecrypt(); + + // Alocar memória alinhada +#ifdef _WIN32 + auto* alignedBuffer = reinterpret_cast<uint8_t*>(_aligned_malloc(messageLength, 32)); #else - memcpy(vData.data(), buffer + readPos, 8); + uint8_t* alignedBuffer = reinterpret_cast<uint8_t*>(std::aligned_alloc(32, messageLength)); #endif - // XTEA decryption loop - for (auto &i : precachedControlSum) { - vData[1] -= ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ i[0]; - vData[0] -= ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ i[1]; - } + if (!alignedBuffer) { + throw std::bad_alloc(); // Tratar erro de alocação + } -#if defined(__AVX2__) - data = _mm_loadu_si128(reinterpret_cast<const __m128i*>(vData.data())); - _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + readPos), data); + // Copiar os dados para o buffer alinhado usando AVX2 + simd_memcpy_avx2(alignedBuffer, buffer, messageLength); -#elif defined(__SSE2__) - data = _mm_loadl_epi64(reinterpret_cast<const __m128i*>(vData.data())); - _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + readPos), data); -#else - memcpy(buffer + readPos, vData.data(), 8); -#endif + // Processar em blocos de 64 bits + while (readPos < messageLength) { + // Prefetch para reduzir a latência da memória + _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer + readPos + 64), _MM_HINT_T0); + + // Carregar 64 bits (dois inteiros de 32 bits) do buffer alinhado com AVX2 + __m256i vData = _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer + readPos)); + + auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); + + // Desenrolar o loop em grupos de 8 para melhor uso do pipeline + for (int32_t i = 0; i < 32; i += 8) { + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[i * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[i * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 1) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 1) * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 2) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 2) * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 3) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 3) * 2 + 1]; + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 4) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 4) * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 5) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 5) * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 6) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 6) * 2 + 1]; + + vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 7) * 2]; + vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 7) * 2 + 1]; + } + + // Armazenar os resultados de volta no buffer alinhado com AVX2 + _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer + readPos), vData); readPos += 8; } - auto innerLength = msg.get<uint16_t>(); + // Copiar o buffer processado de volta para o buffer original usando AVX2 + simd_memcpy_avx2(buffer, alignedBuffer, messageLength); + + // Liberar memória alinhada +#ifdef _WIN32 + _aligned_free(alignedBuffer); +#else + std::free(alignedBuffer); +#endif + + const auto innerLength = msg.get<uint16_t>(); if (std::cmp_greater(innerLength, msgLength - 2)) { return false; } @@ -223,19 +279,53 @@ bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { return true; } +inline void Protocol::precacheControlSumsEncrypt() const { + if (cacheEncryptInitialized) { + return; // Cache já está pronto para criptografia + } + + constexpr uint32_t delta = 0x61C88647; + uint32_t sum = 0; + + for (int32_t i = 0; i < 32; ++i) { + cachedControlSumsEncrypt[i * 2] = sum + key[sum & 3]; + sum -= delta; + cachedControlSumsEncrypt[i * 2 + 1] = sum + key[(sum >> 11) & 3]; + } + + cacheEncryptInitialized = true; +} + +inline void Protocol::precacheControlSumsDecrypt() const { + if (cacheDecryptInitialized) { + return; // Cache já está pronto para descriptografia + } + + constexpr uint32_t delta = 0x61C88647; + uint32_t sum = 0xC6EF3720; + + for (int32_t i = 0; i < 32; ++i) { + cachedControlSumsDecrypt[i * 2] = sum + key[(sum >> 11) & 3]; + sum += delta; + cachedControlSumsDecrypt[i * 2 + 1] = sum + key[sum & 3]; + } + + cacheDecryptInitialized = true; +} + bool Protocol::RSA_decrypt(NetworkMessage &msg) { if ((msg.getLength() - msg.getBufferPosition()) < 128) { return false; } - auto charData = static_cast<char*>(static_cast<void*>(msg.getBuffer())); + const auto charData = static_cast<char*>(static_cast<void*>(msg.getBuffer())); // Does not break strict aliasing g_RSA().decrypt(charData + msg.getBufferPosition()); return (msg.getByte() == 0); } uint32_t Protocol::getIP() const { - if (auto protocolConnection = getConnection()) { + if (const auto protocolConnection = getConnection()) { return protocolConnection->getIP(); } diff --git a/src/server/network/protocol/protocol.hpp b/src/server/network/protocol/protocol.hpp index 9a69e09e725..d0ecbd6032a 100644 --- a/src/server/network/protocol/protocol.hpp +++ b/src/server/network/protocol/protocol.hpp @@ -57,7 +57,7 @@ class Protocol : public std::enable_shared_from_this<Protocol> { protected: void disconnect() const { - if (auto connection = getConnection()) { + if (const auto connection = getConnection()) { connection->close(); } } @@ -69,7 +69,7 @@ class Protocol : public std::enable_shared_from_this<Protocol> { uint32_t* dst = this->key.data(); #if defined(__AVX2__) - __m128i avx_key = _mm_loadu_si128(reinterpret_cast<const __m128i*>(newKey)); + const __m128i avx_key = _mm_loadu_si128(reinterpret_cast<const __m128i*>(newKey)); _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), avx_key); #elif defined(__SSE2__) __m128i sse_key = _mm_loadu_si128(reinterpret_cast<const __m128i*>(newKey)); @@ -118,6 +118,21 @@ class Protocol : public std::enable_shared_from_this<Protocol> { std::array<char, NETWORKMESSAGE_MAXSIZE> buffer {}; }; + inline void simd_memcpy_avx2(uint8_t* dest, const uint8_t* src, size_t len) const { + size_t i = 0; + + // Copiar blocos de 32 bytes por vez (256 bits) com AVX2 + for (; i + 32 <= len; i += 32) { + const __m256i data = _mm256_load_si256(reinterpret_cast<const __m256i*>(src + i)); + _mm256_store_si256(reinterpret_cast<__m256i*>(dest + i), data); + } + + // Copiar os bytes restantes que não formam um bloco completo de 32 bytes + for (; i < len; ++i) { + dest[i] = src[i]; + } + } + void XTEA_encrypt(OutputMessage &msg) const; bool XTEA_decrypt(NetworkMessage &msg) const; bool compression(OutputMessage &msg) const; @@ -125,12 +140,20 @@ class Protocol : public std::enable_shared_from_this<Protocol> { OutputMessage_ptr outputBuffer; const ConnectionWeak_ptr connectionPtr; - std::array<uint32_t, 4> key = {}; uint32_t serverSequenceNumber = 0; uint32_t clientSequenceNumber = 0; std::underlying_type_t<ChecksumMethods_t> checksumMethod = CHECKSUM_METHOD_NONE; bool encryptionEnabled = false; bool rawMessages = false; + mutable std::array<uint32_t, 32 * 2> cachedControlSumsEncrypt; // Cache para criptografia + mutable std::array<uint32_t, 32 * 2> cachedControlSumsDecrypt; // Cache para descriptografia + mutable bool cacheEncryptInitialized = false; + mutable bool cacheDecryptInitialized = false; + mutable std::array<uint32_t, 4> key; + + void precacheControlSumsEncrypt() const; + void precacheControlSumsDecrypt() const; + friend class Connection; }; diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 0fe9509523a..02adbe29235 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -1876,7 +1876,7 @@ void ProtocolGame::parseQuickLootBlackWhitelist(NetworkMessage &msg) { listedItems.reserve(size); for (int i = 0; i < size; i++) { - listedItems.push_back(msg.get<uint16_t>()); + listedItems.emplace_back(msg.get<uint16_t>()); } g_game().playerQuickLootBlackWhitelist(player->getID(), filter, listedItems); @@ -4310,7 +4310,7 @@ void ProtocolGame::sendBasicData() { for (uint16_t sid : spellsList) { auto spell = g_spells().getInstantSpellById(sid); if (spell && spell->getSpellId() > 0) { - validSpells.push_back(spell); + validSpells.emplace_back(spell); } } @@ -5664,7 +5664,7 @@ void ProtocolGame::sendForgeHistory(uint8_t page) { uint16_t pageFirstEntry = (0 < historyVectorLen - (currentPage - 1) * 9) ? historyVectorLen - (currentPage - 1) * 9 : 0; uint16_t pageLastEntry = (0 < historyVectorLen - currentPage * 9) ? historyVectorLen - currentPage * 9 : 0; for (uint16_t entry = pageFirstEntry; entry > pageLastEntry; --entry) { - historyPerPage.push_back(historyVector[entry - 1]); + historyPerPage.emplace_back(historyVector[entry - 1]); } auto historyPageToSend = getVectorIterationIncreaseCount(historyPerPage); @@ -6092,9 +6092,9 @@ void ProtocolGame::sendTradeItemRequest(const std::string &traderName, const std for (const std::shared_ptr<Item> &containerItem : container->getItemList()) { std::shared_ptr<Container> tmpContainer = containerItem->getContainer(); if (tmpContainer) { - listContainer.push_back(tmpContainer); + listContainer.emplace_back(tmpContainer); } - itemList.push_back(containerItem); + itemList.emplace_back(containerItem); } } @@ -7070,7 +7070,7 @@ void ProtocolGame::sendOutfitWindow() { std::vector<std::shared_ptr<Mount>> mounts; for (const auto &mount : g_game().mounts.getMounts()) { if (player->hasMount(mount)) { - mounts.push_back(mount); + mounts.emplace_back(mount); } } @@ -7441,7 +7441,7 @@ void ProtocolGame::sendPreyData(const std::unique_ptr<PreySlot> &slot) { std::vector<uint16_t> validRaceIds; for (auto raceId : slot->raceIdList) { if (g_monsters().getMonsterTypeByRaceId(raceId)) { - validRaceIds.push_back(raceId); + validRaceIds.emplace_back(raceId); } else { g_logger().error("[ProtocolGame::sendPreyData] - Unknown monster type raceid: {}, removing prey slot from player {}", raceId, player->getName()); // Remove wrong raceid from slot diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index f1a9ec31acf..0c3ec9e6977 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -19,8 +19,8 @@ #include "core.hpp" #include "enums/account_errors.hpp" -void ProtocolLogin::disconnectClient(const std::string &message) { - auto output = OutputMessagePool::getOutputMessage(); +void ProtocolLogin::disconnectClient(const std::string &message) const { + const auto output = OutputMessagePool::getOutputMessage(); output->addByte(0x0B); output->addString(message, "ProtocolLogin::disconnectClient - message"); @@ -29,14 +29,15 @@ void ProtocolLogin::disconnectClient(const std::string &message) { disconnect(); } -void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const std::string &password) { +void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const std::string &password) const { Account account(accountDescriptor); account.setProtocolCompat(oldProtocol); if (oldProtocol && !g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__)) { disconnectClient(fmt::format("Only protocol version {}.{} is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; - } else if (!oldProtocol) { + } + if (!oldProtocol) { disconnectClient(fmt::format("Only protocol version {}.{} or outdated 11.00 is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; } diff --git a/src/server/network/protocol/protocollogin.hpp b/src/server/network/protocol/protocollogin.hpp index ebddac68c14..d3051119ba3 100644 --- a/src/server/network/protocol/protocollogin.hpp +++ b/src/server/network/protocol/protocollogin.hpp @@ -14,7 +14,7 @@ class NetworkMessage; class OutputMessage; -class ProtocolLogin : public Protocol { +class ProtocolLogin final : public Protocol { public: // static protocol information enum { SERVER_SENDS_FIRST = false }; @@ -30,9 +30,9 @@ class ProtocolLogin : public Protocol { void onRecvFirstMessage(NetworkMessage &msg) override; private: - void disconnectClient(const std::string &message); + void disconnectClient(const std::string &message) const; - void getCharacterList(const std::string &accountDescriptor, const std::string &password); + void getCharacterList(const std::string &accountDescriptor, const std::string &password) const; bool oldProtocol = false; }; diff --git a/src/server/network/protocol/protocolstatus.cpp b/src/server/network/protocol/protocolstatus.cpp index 71b835e7501..15e84c4f458 100644 --- a/src/server/network/protocol/protocolstatus.cpp +++ b/src/server/network/protocol/protocolstatus.cpp @@ -26,11 +26,11 @@ std::map<uint32_t, int64_t> ProtocolStatus::ipConnectMap; const uint64_t ProtocolStatus::start = OTSYS_TIME(true); void ProtocolStatus::onRecvFirstMessage(NetworkMessage &msg) { - uint32_t ip = getIP(); + const uint32_t ip = getIP(); if (ip != 0x0100007F) { - std::string ipStr = convertIPToString(ip); + const std::string ipStr = convertIPToString(ip); if (ipStr != g_configManager().getString(IP, __FUNCTION__)) { - std::map<uint32_t, int64_t>::const_iterator it = ipConnectMap.find(ip); + const std::map<uint32_t, int64_t>::const_iterator it = ipConnectMap.find(ip); if (it != ipConnectMap.end() && (OTSYS_TIME() < (it->second + g_configManager().getNumber(STATUSQUERY_TIMEOUT, __FUNCTION__)))) { disconnect(); return; @@ -75,7 +75,7 @@ void ProtocolStatus::onRecvFirstMessage(NetworkMessage &msg) { } void ProtocolStatus::sendStatusString() { - auto output = OutputMessagePool::getOutputMessage(); + const auto output = OutputMessagePool::getOutputMessage(); setRawMessages(true); @@ -88,7 +88,7 @@ void ProtocolStatus::sendStatusString() { tsqp.append_attribute("version") = "1.0"; pugi::xml_node serverinfo = tsqp.append_child("serverinfo"); - uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000; + const uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000; serverinfo.append_attribute("uptime") = std::to_string(uptime).c_str(); serverinfo.append_attribute("ip") = g_configManager().getString(IP, __FUNCTION__).c_str(); serverinfo.append_attribute("servername") = g_configManager().getString(ConfigKey_t::SERVER_NAME, __FUNCTION__).c_str(); @@ -146,20 +146,20 @@ void ProtocolStatus::sendStatusString() { map.append_attribute("width") = std::to_string(mapWidth).c_str(); map.append_attribute("height") = std::to_string(mapHeight).c_str(); - pugi::xml_node motd = tsqp.append_child("motd"); + const pugi::xml_node motd = tsqp.append_child("motd"); motd.text() = g_configManager().getString(SERVER_MOTD, __FUNCTION__).c_str(); std::ostringstream ss; doc.save(ss, "", pugi::format_raw); - std::string data = ss.str(); + const std::string data = ss.str(); output->addBytes(data.c_str(), data.size()); send(output); disconnect(); } -void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string &characterName) { - auto output = OutputMessagePool::getOutputMessage(); +void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string &characterName) const { + const auto output = OutputMessagePool::getOutputMessage(); if (requestedInfo & REQUEST_BASIC_SERVER_INFO) { output->addByte(0x10); @@ -204,9 +204,9 @@ void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string &charact const auto players = g_game().getPlayers(); output->add<uint32_t>(players.size()); - for (const auto &it : players) { - output->addString(it.second->getName(), "ProtocolStatus::sendInfo - it.second->getName()"); - output->add<uint32_t>(it.second->getLevel()); + for (const auto &[fst, snd] : players) { + output->addString(snd->getName(), "ProtocolStatus::sendInfo - it.second->getName()"); + output->add<uint32_t>(snd->getLevel()); } } diff --git a/src/server/network/protocol/protocolstatus.hpp b/src/server/network/protocol/protocolstatus.hpp index 2902e7eea51..d5600438734 100644 --- a/src/server/network/protocol/protocolstatus.hpp +++ b/src/server/network/protocol/protocolstatus.hpp @@ -28,7 +28,7 @@ class ProtocolStatus final : public Protocol { void onRecvFirstMessage(NetworkMessage &msg) override; void sendStatusString(); - void sendInfo(uint16_t requestedInfo, const std::string &characterName); + void sendInfo(uint16_t requestedInfo, const std::string &characterName) const; static const uint64_t start; diff --git a/src/server/network/webhook/webhook.cpp b/src/server/network/webhook/webhook.cpp index a617b114389..bc091805a5b 100644 --- a/src/server/network/webhook/webhook.cpp +++ b/src/server/network/webhook/webhook.cpp @@ -46,7 +46,7 @@ void Webhook::run() { void Webhook::sendPayload(const std::string &payload, const std::string &url) { std::scoped_lock lock { taskLock }; - webhooks.push_back(std::make_shared<WebhookTask>(payload, url)); + webhooks.emplace_back(std::make_shared<WebhookTask>(payload, url)); } void Webhook::sendMessage(const std::string &title, const std::string &message, int color, std::string url, bool embed) { @@ -89,7 +89,7 @@ int Webhook::sendRequest(const char* url, const char* payload, std::string* resp curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); curl_easy_setopt(curl, CURLOPT_USERAGENT, "canary (https://github.com/opentibiabr/canary)"); - CURLcode res = curl_easy_perform(curl); + const CURLcode res = curl_easy_perform(curl); if (res != CURLE_OK) { g_logger().error("Failed to send webhook message with the error: {}", curl_easy_strerror(res)); @@ -107,15 +107,15 @@ int Webhook::sendRequest(const char* url, const char* payload, std::string* resp } size_t Webhook::writeCallback(void* contents, size_t size, size_t nmemb, void* userp) { - size_t real_size = size * nmemb; - auto* str = reinterpret_cast<std::string*>(userp); - str->append(reinterpret_cast<char*>(contents), real_size); + const size_t real_size = size * nmemb; + auto* str = static_cast<std::string*>(userp); + str->append(static_cast<char*>(contents), real_size); return real_size; } std::string Webhook::getPayload(const std::string &title, const std::string &message, int color, bool embed) const { - std::time_t now = getTimeNow(); - std::string time_buf = formatDate(now); + const std::time_t now = getTimeNow(); + const std::string time_buf = formatDate(now); std::stringstream footer_text; footer_text @@ -125,19 +125,19 @@ std::string Webhook::getPayload(const std::string &title, const std::string &mes std::stringstream payload; if (embed) { payload << "{ \"embeds\": [{ "; - payload << "\"title\": \"" << title << "\", "; + payload << R"("title": ")" << title << "\", "; if (!message.empty()) { - payload << "\"description\": \"" << message << "\", "; + payload << R"("description": ")" << message << "\", "; } if (g_configManager().getBoolean(DISCORD_SEND_FOOTER, __FUNCTION__)) { - payload << "\"footer\": { \"text\": \"" << footer_text.str() << "\" }, "; + payload << R"("footer": { "text": ")" << footer_text.str() << "\" }, "; } if (color >= 0) { payload << "\"color\": " << color; } payload << " }] }"; } else { - payload << "{ \"content\": \"" << (!message.empty() ? message : title) << "\" }"; + payload << R"({ "content": ")" << (!message.empty() ? message : title) << "\" }"; } return payload.str(); @@ -149,7 +149,7 @@ void Webhook::sendWebhook() { return; } - auto task = webhooks.front(); + const auto task = webhooks.front(); std::string response_body; auto response_code = sendRequest(task->url.c_str(), task->payload.c_str(), &response_body); diff --git a/src/server/server.cpp b/src/server/server.cpp index fc8690468fe..4fce80ab75e 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include <memory> + #include "pch.hpp" #include "server/network/message/outputmessage.hpp" @@ -71,7 +73,7 @@ bool ServicePort::is_single_socket() const { std::string ServicePort::get_protocol_names() const { if (services.empty()) { - return std::string(); + return {}; } std::string str = services.front()->get_protocol_name(); @@ -92,15 +94,15 @@ void ServicePort::accept() { acceptor->async_accept(connection->getSocket(), [self = shared_from_this(), connection](const std::error_code &error) { self->onAccept(connection, error); }); } -void ServicePort::onAccept(Connection_ptr connection, const std::error_code &error) { +void ServicePort::onAccept(const Connection_ptr& connection, const std::error_code &error) { if (!error) { if (services.empty()) { return; } - auto remote_ip = connection->getIP(); + const auto remote_ip = connection->getIP(); if (remote_ip != 0 && inject<Ban>().acceptConnection(remote_ip)) { - Service_ptr service = services.front(); + const Service_ptr service = services.front(); if (service->is_single_socket()) { connection->accept(service->make_protocol(connection)); } else { @@ -123,7 +125,7 @@ void ServicePort::onAccept(Connection_ptr connection, const std::error_code &err } Protocol_ptr ServicePort::make_protocol(bool checksummed, NetworkMessage &msg, const Connection_ptr &connection) const { - uint8_t protocolID = msg.getByte(); + const uint8_t protocolID = msg.getByte(); for (auto &service : services) { if (protocolID != service->get_protocol_identifier()) { continue; @@ -136,12 +138,12 @@ Protocol_ptr ServicePort::make_protocol(bool checksummed, NetworkMessage &msg, c return nullptr; } -void ServicePort::onStopServer() { +void ServicePort::onStopServer() const { close(); } -void ServicePort::openAcceptor(std::weak_ptr<ServicePort> weak_service, uint16_t port) { - if (auto service = weak_service.lock()) { +void ServicePort::openAcceptor(const std::weak_ptr<ServicePort>& weak_service, uint16_t port) { + if (const auto service = weak_service.lock()) { service->open(port); } } @@ -154,9 +156,9 @@ void ServicePort::open(uint16_t port) { try { if (g_configManager().getBoolean(BIND_ONLY_GLOBAL_ADDRESS, __FUNCTION__)) { - acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4::from_string(g_configManager().getString(IP, __FUNCTION__))), serverPort))); + acceptor = std::make_unique<asio::ip::tcp::acceptor>(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4::from_string(g_configManager().getString(IP, __FUNCTION__))), serverPort)); } else { - acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4(INADDR_ANY)), serverPort))); + acceptor = std::make_unique<asio::ip::tcp::acceptor>(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4(INADDR_ANY)), serverPort)); } acceptor->set_option(asio::ip::tcp::no_delay(true)); @@ -173,7 +175,7 @@ void ServicePort::open(uint16_t port) { } } -void ServicePort::close() { +void ServicePort::close() const { if (acceptor && acceptor->is_open()) { std::error_code error; acceptor->close(error); @@ -185,6 +187,6 @@ bool ServicePort::add_service(const Service_ptr &new_svc) { return false; } - services.push_back(new_svc); + services.emplace_back(new_svc); return true; } diff --git a/src/server/server.hpp b/src/server/server.hpp index 2fb36fdb01c..fbe0a578a38 100644 --- a/src/server/server.hpp +++ b/src/server/server.hpp @@ -58,17 +58,17 @@ class ServicePort : public std::enable_shared_from_this<ServicePort> { ServicePort(const ServicePort &) = delete; ServicePort &operator=(const ServicePort &) = delete; - static void openAcceptor(std::weak_ptr<ServicePort> weak_service, uint16_t port); + static void openAcceptor(const std::weak_ptr<ServicePort>& weak_service, uint16_t port); void open(uint16_t port); - void close(); + void close() const; bool is_single_socket() const; std::string get_protocol_names() const; bool add_service(const Service_ptr &new_svc); Protocol_ptr make_protocol(bool checksummed, NetworkMessage &msg, const Connection_ptr &connection) const; - void onStopServer(); - void onAccept(Connection_ptr connection, const std::error_code &error); + void onStopServer() const; + void onAccept(const Connection_ptr& connection, const std::error_code &error); private: void accept(); @@ -122,7 +122,7 @@ bool ServiceManager::add(uint16_t port) { ServicePort_ptr service_port; - auto foundServicePort = acceptors.find(port); + const auto foundServicePort = acceptors.find(port); if (foundServicePort == acceptors.end()) { service_port = std::make_shared<ServicePort>(io_service); diff --git a/src/utils/arraylist.hpp b/src/utils/arraylist.hpp index da507e68480..2c9a6a6aac3 100644 --- a/src/utils/arraylist.hpp +++ b/src/utils/arraylist.hpp @@ -27,17 +27,17 @@ namespace stdext { reserve(reserveSize); } - explicit arraylist(std::initializer_list<T> _Ilist) { - backContainer.assign(_Ilist); + arraylist(std::initializer_list<T> Ilist) { + backContainer.assign(Ilist); } - arraylist &operator=(std::initializer_list<T> _Ilist) { - backContainer.assign(_Ilist); + arraylist &operator=(std::initializer_list<T> Ilist) { + backContainer.assign(Ilist); return *this; } - void assign(std::initializer_list<T> _Ilist) { - backContainer.assign(_Ilist); + void assign(std::initializer_list<T> Ilist) { + backContainer.assign(Ilist); } bool contains(const T &v) { @@ -91,31 +91,31 @@ namespace stdext { void push_front(const T &v) { needUpdate = true; - frontContainer.push_back(v); + frontContainer.emplace_back(v); } - void push_front(T &&_Val) { + void push_front(T &&Val) { needUpdate = true; - frontContainer.push_back(std::move(_Val)); + frontContainer.emplace_back(std::move(Val)); } - template <class... _Valty> - decltype(auto) emplace_front(_Valty &&... v) { + template <class... Valty> + decltype(auto) emplace_front(Valty &&... v) { needUpdate = true; - return frontContainer.emplace_back(std::forward<_Valty>(v)...); + return frontContainer.emplace_back(std::forward<Valty>(v)...); } - void push_back(const T &v) { - backContainer.push_back(v); + void emplace_back(const T &v) { + backContainer.emplace_back(v); } - void push_back(T &&_Val) { - backContainer.push_back(std::move(_Val)); + void emplace_back(T &&Val) { + backContainer.emplace_back(std::move(Val)); } - template <class... _Valty> - decltype(auto) emplace_back(_Valty &&... v) { - return backContainer.emplace_back(std::forward<_Valty>(v)...); + template <class... Valty> + decltype(auto) emplace_back(Valty &&... v) { + return backContainer.emplace_back(std::forward<Valty>(v)...); } bool empty() const noexcept { diff --git a/src/utils/benchmark.hpp b/src/utils/benchmark.hpp index 39e4f1874ca..2524866a6a8 100644 --- a/src/utils/benchmark.hpp +++ b/src/utils/benchmark.hpp @@ -9,7 +9,6 @@ #pragma once -#include <ctime> #include <cstdint> #include <chrono> diff --git a/src/utils/hash.hpp b/src/utils/hash.hpp index 6b819c9bb7d..7acee5551e7 100644 --- a/src/utils/hash.hpp +++ b/src/utils/hash.hpp @@ -1,8 +1,8 @@ #pragma once namespace stdext { - template <class _Kty> - using hash = phmap::Hash<_Kty>; + template <class Kty> + using hash = phmap::Hash<Kty>; // Robin Hood lib inline size_t hash_int(uint64_t x) noexcept { @@ -17,19 +17,19 @@ namespace stdext { seed ^= h + 0x9e3779b9 + (seed << 6) + (seed >> 2); } - void hash_combine(size_t &seed, uint64_t v) { + inline void hash_combine(size_t &seed, uint64_t v) { hash_union(seed, hash_int(v)); } - void hash_combine(size_t &seed, uint32_t v) { + inline void hash_combine(size_t &seed, uint32_t v) { hash_union(seed, hash_int(v)); } - void hash_combine(size_t &seed, uint16_t v) { + inline void hash_combine(size_t &seed, uint16_t v) { hash_union(seed, hash_int(v)); } - void hash_combine(size_t &seed, uint8_t v) { + inline void hash_combine(size_t &seed, uint8_t v) { hash_union(seed, hash_int(v)); } diff --git a/src/utils/lockfree.hpp b/src/utils/lockfree.hpp index cb27890ef58..28cfec4c824 100644 --- a/src/utils/lockfree.hpp +++ b/src/utils/lockfree.hpp @@ -96,7 +96,7 @@ class LockfreePoolingAllocator : public std::allocator<T> { void deallocate(T* p, size_t) const { if (localCache.size() < LOCAL_CACHE_LIMIT) { - localCache.push_back(p); + localCache.emplace_back(p); } else { auto &inst = LockfreeFreeList<sizeof(T), CAPACITY>::get(); inst.push(p); diff --git a/src/utils/pugicast.hpp b/src/utils/pugicast.hpp index d09532a2d5c..b59e95d37ab 100644 --- a/src/utils/pugicast.hpp +++ b/src/utils/pugicast.hpp @@ -19,7 +19,7 @@ namespace pugi { T value; // Set the last character to parse - std::string_view string(str); + const std::string_view string(str); const auto last = str + string.size(); // Convert the string to the specified type diff --git a/src/utils/simd.hpp b/src/utils/simd.hpp index 7e57e75bfad..d7b7f7f2166 100644 --- a/src/utils/simd.hpp +++ b/src/utils/simd.hpp @@ -56,7 +56,7 @@ #ifdef _MSC_VER #include <intrin.h> -__forceinline unsigned int _mm_ctz(unsigned int value) { +__forceinline unsigned int mm_ctz(unsigned int value) { unsigned long i = 0; _BitScanForward(&i, value); return static_cast<unsigned int>(i); diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index 58337e83e86..1a6796375cf 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -25,14 +25,14 @@ void printXMLError(const std::string &where, const std::string &fileName, const uint32_t currentLine = 1; std::string line; - auto offset = static_cast<size_t>(result.offset); + const auto offset = static_cast<size_t>(result.offset); size_t lineOffsetPosition = 0; size_t index = 0; size_t bytes; do { bytes = fread(buffer, 1, 32768, file); for (size_t i = 0; i < bytes; ++i) { - char ch = buffer[i]; + const char ch = buffer[i]; if (ch == '\n') { if ((index + i) >= offset) { lineOffsetPosition = line.length() - ((index + i) - offset); @@ -135,7 +135,7 @@ std::string transformToSHA1(const std::string &input) { uint32_t length_low = 0; uint32_t length_high = 0; - for (char ch : input) { + for (const char ch : input) { messageBlock[index++] = ch; length_low += 8; @@ -177,7 +177,7 @@ std::string transformToSHA1(const std::string &input) { processSHA1MessageBlock(messageBlock, H); char hexstring[41]; - static const char hexDigits[] = { "0123456789abcdef" }; + static constexpr char hexDigits[] = { "0123456789abcdef" }; for (int hashByte = 20; --hashByte >= 0;) { const uint8_t byte = H[hashByte >> 2] >> (((3 - hashByte) & 3) << 3); index = hashByte << 1; @@ -189,8 +189,8 @@ std::string transformToSHA1(const std::string &input) { uint16_t getStashSize(const StashItemList &itemList) { uint16_t size = 0; - for (auto item : itemList) { - size += ceil(item.second / (float_t)Item::items[item.first].stackSize); + for (const auto &[fst, snd] : itemList) { + size += ceil(snd / static_cast<float_t>(Item::items[fst].stackSize)); } return size; } @@ -226,14 +226,14 @@ std::string generateToken(const std::string &key, uint32_t ticks) { message.assign(transformToSHA1(oKeyPad)); // calculate hmac offset - uint32_t offset = static_cast<uint32_t>(std::stol(message.substr(39, 1), nullptr, 16) & 0xF); + const uint32_t offset = static_cast<uint32_t>(std::stol(message.substr(39, 1), nullptr, 16) & 0xF); // get truncated hash - uint32_t truncHash = std::stol(message.substr(2 * offset, 8), nullptr, 16) & 0x7FFFFFFF; + const uint32_t truncHash = std::stol(message.substr(2 * offset, 8), nullptr, 16) & 0x7FFFFFFF; message.assign(std::to_string(truncHash)); // return only last AUTHENTICATOR_DIGITS (default 6) digits, also asserts exactly 6 digits - uint32_t hashLen = message.length(); + const uint32_t hashLen = message.length(); message.assign(message.substr(hashLen - std::min(hashLen, AUTHENTICATOR_DIGITS))); message.insert(0, AUTHENTICATOR_DIGITS - std::min(hashLen, AUTHENTICATOR_DIGITS), '0'); return message; @@ -258,7 +258,7 @@ void trim_left(std::string &source, char t) { } std::string keepFirstWordOnly(std::string &str) { - size_t spacePos = str.find(' '); + const size_t spacePos = str.find(' '); if (spacePos != std::string::npos) { str.erase(spacePos); } @@ -267,7 +267,7 @@ std::string keepFirstWordOnly(std::string &str) { } void toLowerCaseString(std::string &source) { - std::transform(source.begin(), source.end(), source.begin(), tolower); + std::ranges::transform(source, source.begin(), tolower); } std::string asLowerCaseString(std::string source) { @@ -276,7 +276,7 @@ std::string asLowerCaseString(std::string source) { } std::string asUpperCaseString(std::string source) { - std::transform(source.begin(), source.end(), source.begin(), toupper); + std::ranges::transform(source, source.begin(), toupper); return source; } @@ -284,7 +284,7 @@ std::string toCamelCase(const std::string &str) { std::string result; bool capitalizeNext = false; - for (char ch : str) { + for (const char ch : str) { if (ch == '_' || std::isspace(ch) || ch == '-') { capitalizeNext = true; } else { @@ -304,7 +304,7 @@ std::string toPascalCase(const std::string &str) { std::string result; bool capitalizeNext = true; - for (char ch : str) { + for (const char ch : str) { if (ch == '_' || std::isspace(ch) || ch == '-') { capitalizeNext = true; } else { @@ -322,7 +322,7 @@ std::string toPascalCase(const std::string &str) { std::string toSnakeCase(const std::string &str) { std::string result; - for (char ch : str) { + for (const char ch : str) { if (std::isupper(ch)) { result += '_'; result += std::tolower(ch); @@ -338,7 +338,7 @@ std::string toSnakeCase(const std::string &str) { std::string toKebabCase(const std::string &str) { std::string result; - for (char ch : str) { + for (const char ch : str) { if (std::isupper(ch)) { result += '-'; result += std::tolower(ch); @@ -355,7 +355,7 @@ std::string toKebabCase(const std::string &str) { std::string toStartCaseWithSpace(const std::string &str) { std::string result; for (size_t i = 0; i < str.length(); ++i) { - char ch = str[i]; + const char ch = str[i]; if (i == 0 || std::isupper(ch)) { if (i > 0) { result += ' '; @@ -373,18 +373,18 @@ StringVector explodeString(const std::string &inString, const std::string &separ std::string::size_type start = 0, end = 0; while (--limit != -1 && (end = inString.find(separator, start)) != std::string::npos) { - returnVector.push_back(inString.substr(start, end - start)); + returnVector.emplace_back(inString.substr(start, end - start)); start = end + separator.size(); } - returnVector.push_back(inString.substr(start)); + returnVector.emplace_back(inString.substr(start)); return returnVector; } IntegerVector vectorAtoi(const StringVector &stringVector) { IntegerVector returnVector; for (const auto &string : stringVector) { - returnVector.push_back(std::stoi(string)); + returnVector.emplace_back(std::stoi(string)); } return returnVector; } @@ -399,7 +399,8 @@ int32_t uniform_random(int32_t minNumber, int32_t maxNumber) { static std::uniform_int_distribution<int32_t> uniformRand; if (minNumber == maxNumber) { return minNumber; - } else if (minNumber > maxNumber) { + } + if (minNumber > maxNumber) { std::swap(minNumber, maxNumber); } return uniformRand(getRandomGenerator(), std::uniform_int_distribution<int32_t>::param_type(minNumber, maxNumber)); @@ -461,8 +462,8 @@ std::string formatTime(time_t time) { std::string formatEnumName(std::string_view name) { std::string result { name.begin(), name.end() }; - std::replace(result.begin(), result.end(), '_', ' '); - std::transform(result.begin(), result.end(), result.begin(), [](unsigned char c) { return std::tolower(c); }); + std::ranges::replace(result, '_', ' '); + std::ranges::transform(result, result.begin(), [](unsigned char c) { return std::tolower(c); }); return result; } @@ -471,19 +472,20 @@ std::time_t getTimeNow() { } int64_t getTimeMsNow() { - auto duration = std::chrono::system_clock::now().time_since_epoch(); + const auto duration = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::milliseconds>(duration).count(); } int64_t getTimeUsNow() { - auto duration = std::chrono::system_clock::now().time_since_epoch(); + const auto duration = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::microseconds>(duration).count(); } BedItemPart_t getBedPart(const std::string_view string) { if (string == "pillow" || string == "1") { return BED_PILLOW_PART; - } else if (string == "blanket" || string == "2") { + } + if (string == "blanket" || string == "2") { return BED_BLANKET_PART; } return BED_NONE_PART; @@ -559,12 +561,12 @@ Position getNextPosition(Direction direction, Position pos) { } Direction getDirectionTo(const Position &from, const Position &to, bool exactDiagonalOnly /* =true*/) { - int_fast32_t dx = Position::getOffsetX(from, to); - int_fast32_t dy = Position::getOffsetY(from, to); + const int_fast32_t dx = Position::getOffsetX(from, to); + const int_fast32_t dy = Position::getOffsetY(from, to); if (exactDiagonalOnly) { - int_fast32_t absDx = std::abs(dx); - int_fast32_t absDy = std::abs(dy); + const int_fast32_t absDx = std::abs(dx); + const int_fast32_t absDy = std::abs(dy); /* * Only consider diagonal if dx and dy are equal (exact diagonal). @@ -885,7 +887,7 @@ SpawnTypeNames spawnTypeNames = { }; MagicEffectClasses getMagicEffect(const std::string &strValue) { - auto magicEffect = magicEffectNames.find(strValue); + const auto magicEffect = magicEffectNames.find(strValue); if (magicEffect != magicEffectNames.end()) { return magicEffect->second; } @@ -893,7 +895,7 @@ MagicEffectClasses getMagicEffect(const std::string &strValue) { } ShootType_t getShootType(const std::string &strValue) { - auto shootType = shootTypeNames.find(strValue); + const auto shootType = shootTypeNames.find(strValue); if (shootType != shootTypeNames.end()) { return shootType->second; } @@ -901,7 +903,7 @@ ShootType_t getShootType(const std::string &strValue) { } Ammo_t getAmmoType(const std::string &strValue) { - auto ammoType = ammoTypeNames.find(strValue); + const auto ammoType = ammoTypeNames.find(strValue); if (ammoType != ammoTypeNames.end()) { return ammoType->second; } @@ -909,7 +911,7 @@ Ammo_t getAmmoType(const std::string &strValue) { } WeaponAction_t getWeaponAction(const std::string &strValue) { - auto weaponAction = weaponActionNames.find(strValue); + const auto weaponAction = weaponActionNames.find(strValue); if (weaponAction != weaponActionNames.end()) { return weaponAction->second; } @@ -917,7 +919,7 @@ WeaponAction_t getWeaponAction(const std::string &strValue) { } Skulls_t getSkullType(const std::string &strValue) { - auto skullType = skullNames.find(strValue); + const auto skullType = skullNames.find(strValue); if (skullType != skullNames.end()) { return skullType->second; } @@ -925,7 +927,7 @@ Skulls_t getSkullType(const std::string &strValue) { } ImbuementTypes_t getImbuementType(const std::string &strValue) { - auto imbuementType = imbuementTypeNames.find(strValue); + const auto imbuementType = imbuementTypeNames.find(strValue); if (imbuementType != imbuementTypeNames.end()) { return imbuementType->second; } @@ -937,7 +939,7 @@ ImbuementTypes_t getImbuementType(const std::string &strValue) { * It will be dropped with monsters. Use RespawnPeriod_t instead. */ SpawnType_t getSpawnType(const std::string &strValue) { - auto spawnType = spawnTypeNames.find(strValue); + const auto spawnType = spawnTypeNames.find(strValue); if (spawnType != spawnTypeNames.end()) { return spawnType->second; } @@ -1001,7 +1003,7 @@ uint32_t adlerChecksum(const uint8_t* data, size_t length) { return 0; } - const uint16_t adler = 65521; + constexpr uint16_t adler = 65521; uint32_t a = 1, b = 0; @@ -1032,7 +1034,7 @@ std::string ucfirst(std::string str) { } std::string ucwords(std::string str) { - size_t strLength = str.length(); + const size_t strLength = str.length(); if (strLength == 0) { return str; } @@ -1052,7 +1054,7 @@ bool booleanString(const std::string &str) { return false; } - char ch = tolower(str.front()); + const char ch = tolower(str.front()); return ch != 'f' && ch != 'n' && ch != '0'; } @@ -1090,7 +1092,7 @@ WeaponType_t getWeaponType(const std::string &name) { { "missile", WeaponType_t::WEAPON_MISSILE } }; - auto it = type_mapping.find(name); + const auto it = type_mapping.find(name); if (it != type_mapping.end()) { return it->second; } @@ -1110,7 +1112,7 @@ MoveEvent_t getMoveEventType(const std::string &name) { { "removeitemitemtile", MOVE_EVENT_REMOVE_ITEM_ITEMTILE } }; - auto it = move_event_type_mapping.find(name); + const auto it = move_event_type_mapping.find(name); if (it != move_event_type_mapping.end()) { return it->second; } @@ -1119,7 +1121,7 @@ MoveEvent_t getMoveEventType(const std::string &name) { } std::string getCombatName(CombatType_t combatType) { - auto combatName = combatTypeNames.find(combatType); + const auto combatName = combatTypeNames.find(combatType); if (combatName != combatTypeNames.end()) { return combatName->second; } @@ -1127,7 +1129,7 @@ std::string getCombatName(CombatType_t combatType) { } CombatType_t getCombatTypeByName(const std::string &combatname) { - auto it = std::find_if(combatTypeNames.begin(), combatTypeNames.end(), [combatname](const std::pair<CombatType_t, std::string> &pair) { + const auto it = std::ranges::find_if(combatTypeNames, [combatname](const std::pair<CombatType_t, std::string> &pair) { return pair.second == combatname; }); @@ -1135,7 +1137,7 @@ CombatType_t getCombatTypeByName(const std::string &combatname) { } size_t combatTypeToIndex(CombatType_t combatType) { - auto enum_index_opt = magic_enum::enum_index(combatType); + const auto enum_index_opt = magic_enum::enum_index(combatType); if (enum_index_opt.has_value() && enum_index_opt.value() < COMBAT_COUNT) { return enum_index_opt.value(); } else { @@ -1148,7 +1150,7 @@ size_t combatTypeToIndex(CombatType_t combatType) { } std::string combatTypeToName(CombatType_t combatType) { - std::string_view name = magic_enum::enum_name(combatType); + const std::string_view name = magic_enum::enum_name(combatType); if (!name.empty() && combatType < COMBAT_COUNT) { return formatEnumName(name); } else { @@ -1167,59 +1169,86 @@ CombatType_t indexToCombatType(size_t v) { ItemAttribute_t stringToItemAttribute(const std::string &str) { if (str == "store") { return ItemAttribute_t::STORE; - } else if (str == "aid") { + } + if (str == "aid") { return ItemAttribute_t::ACTIONID; - } else if (str == "uid") { + } + if (str == "uid") { return ItemAttribute_t::UNIQUEID; - } else if (str == "description") { + } + if (str == "description") { return ItemAttribute_t::DESCRIPTION; - } else if (str == "text") { + } + if (str == "text") { return ItemAttribute_t::TEXT; - } else if (str == "date") { + } + if (str == "date") { return ItemAttribute_t::DATE; - } else if (str == "writer") { + } + if (str == "writer") { return ItemAttribute_t::WRITER; - } else if (str == "name") { + } + if (str == "name") { return ItemAttribute_t::NAME; - } else if (str == "article") { + } + if (str == "article") { return ItemAttribute_t::ARTICLE; - } else if (str == "pluralname") { + } + if (str == "pluralname") { return ItemAttribute_t::PLURALNAME; - } else if (str == "weight") { + } + if (str == "weight") { return ItemAttribute_t::WEIGHT; - } else if (str == "attack") { + } + if (str == "attack") { return ItemAttribute_t::ATTACK; - } else if (str == "defense") { + } + if (str == "defense") { return ItemAttribute_t::DEFENSE; - } else if (str == "extradefense") { + } + if (str == "extradefense") { return ItemAttribute_t::EXTRADEFENSE; - } else if (str == "armor") { + } + if (str == "armor") { return ItemAttribute_t::ARMOR; - } else if (str == "hitchance") { + } + if (str == "hitchance") { return ItemAttribute_t::HITCHANCE; - } else if (str == "shootrange") { + } + if (str == "shootrange") { return ItemAttribute_t::SHOOTRANGE; - } else if (str == "owner") { + } + if (str == "owner") { return ItemAttribute_t::OWNER; - } else if (str == "duration") { + } + if (str == "duration") { return ItemAttribute_t::DURATION; - } else if (str == "decaystate") { + } + if (str == "decaystate") { return ItemAttribute_t::DECAYSTATE; - } else if (str == "corpseowner") { + } + if (str == "corpseowner") { return ItemAttribute_t::CORPSEOWNER; - } else if (str == "charges") { + } + if (str == "charges") { return ItemAttribute_t::CHARGES; - } else if (str == "fluidtype") { + } + if (str == "fluidtype") { return ItemAttribute_t::FLUIDTYPE; - } else if (str == "doorid") { + } + if (str == "doorid") { return ItemAttribute_t::DOORID; - } else if (str == "timestamp") { + } + if (str == "timestamp") { return ItemAttribute_t::DURATION_TIMESTAMP; - } else if (str == "amount") { + } + if (str == "amount") { return ItemAttribute_t::AMOUNT; - } else if (str == "tier") { + } + if (str == "tier") { return ItemAttribute_t::TIER; - } else if (str == "lootmessagesuffix") { + } + if (str == "lootmessagesuffix") { return ItemAttribute_t::LOOTMESSAGE_SUFFIX; } @@ -1523,20 +1552,26 @@ int64_t OTSYS_TIME(bool useTime) { } SpellGroup_t stringToSpellGroup(const std::string &value) { - std::string tmpStr = asLowerCaseString(value); + const std::string tmpStr = asLowerCaseString(value); if (tmpStr == "attack" || tmpStr == "1") { return SPELLGROUP_ATTACK; - } else if (tmpStr == "healing" || tmpStr == "2") { + } + if (tmpStr == "healing" || tmpStr == "2") { return SPELLGROUP_HEALING; - } else if (tmpStr == "support" || tmpStr == "3") { + } + if (tmpStr == "support" || tmpStr == "3") { return SPELLGROUP_SUPPORT; - } else if (tmpStr == "special" || tmpStr == "4") { + } + if (tmpStr == "special" || tmpStr == "4") { return SPELLGROUP_SPECIAL; - } else if (tmpStr == "crippling" || tmpStr == "6") { + } + if (tmpStr == "crippling" || tmpStr == "6") { return SPELLGROUP_CRIPPLING; - } else if (tmpStr == "focus" || tmpStr == "7") { + } + if (tmpStr == "focus" || tmpStr == "7") { return SPELLGROUP_FOCUS; - } else if (tmpStr == "ultimatestrikes" || tmpStr == "8") { + } + if (tmpStr == "ultimatestrikes" || tmpStr == "8") { return SPELLGROUP_ULTIMATESTRIKES; } @@ -1551,10 +1586,10 @@ SpellGroup_t stringToSpellGroup(const std::string &value) { */ void capitalizeWords(std::string &source) { toLowerCaseString(source); - auto size = (uint8_t)source.size(); + const auto size = static_cast<uint8_t>(source.size()); for (uint8_t i = 0; i < size; i++) { if (i == 0) { - source[i] = (char)toupper(source[i]); + source[i] = static_cast<char>(toupper(source[i])); } else if (source[i - 1] == ' ' || source[i - 1] == '\'') { source[i] = (char)toupper(source[i]); } @@ -1563,8 +1598,8 @@ void capitalizeWords(std::string &source) { void capitalizeWordsIgnoringString(std::string &source, const std::string &stringToIgnore) { toLowerCaseString(source); - auto size = static_cast<uint8_t>(source.size()); - auto indexFound = source.find(stringToIgnore); + const auto size = static_cast<uint8_t>(source.size()); + const auto indexFound = source.find(stringToIgnore); for (uint8_t i = 0; i < size; i++) { if (indexFound != std::string::npos && indexFound > 0 && std::cmp_greater(i, static_cast<uint8_t>(indexFound - 1)) && i < (indexFound + stringToIgnore.size())) { @@ -1591,11 +1626,11 @@ void consoleHandlerExit() { NameEval_t validateName(const std::string &name) { StringVector prohibitedWords = { "owner", "gamemaster", "hoster", "admin", "staff", "tibia", "account", "god", "anal", "ass", "fuck", "sex", "hitler", "pussy", "dick", "rape", "cm", "gm", "tutor", "counsellor", "god" }; StringVector toks; - std::regex regexValidChars("^[a-zA-Z' ]+$"); + const std::regex regexValidChars("^[a-zA-Z' ]+$"); std::stringstream ss(name); - std::istream_iterator<std::string> begin(ss); - std::istream_iterator<std::string> end; + const std::istream_iterator<std::string> begin(ss); + const std::istream_iterator<std::string> end; std::copy(begin, end, std::back_inserter(toks)); if (name.length() < 3 || name.length() > 18) { @@ -1611,7 +1646,7 @@ NameEval_t validateName(const std::string &name) { return INVALID_TOKEN_LENGTH; } - if (std::find(prohibitedWords.begin(), prohibitedWords.end(), str) != prohibitedWords.end()) { // searching for prohibited words + if (std::ranges::find(prohibitedWords, str) != prohibitedWords.end()) { // searching for prohibited words return INVALID_FORBIDDEN; } } @@ -1721,31 +1756,31 @@ uint8_t forgeBonus(int32_t number) { return 0; } // Dust not consumed - else if (number >= 7400 && number < 9000) { + if (number >= 7400 && number < 9000) { return 1; } // Cores not consumed - else if (number >= 9000 && number < 9500) { + if (number >= 9000 && number < 9500) { return 2; } // Gold not consumed - else if (number >= 9500 && number < 9525) { + if (number >= 9500 && number < 9525) { return 3; } // Second item retained with decreased tier - else if (number >= 9525 && number < 9550) { + if (number >= 9525 && number < 9550) { return 4; } // Second item retained with unchanged tier - else if (number >= 9550 && number < 9950) { + if (number >= 9550 && number < 9950) { return 5; } // Second item retained with increased tier - else if (number >= 9950 && number < 9975) { + if (number >= 9950 && number < 9975) { return 6; } // Gain two tiers - else if (number >= 9975) { + if (number >= 9975) { return 7; } @@ -1870,15 +1905,15 @@ std::vector<std::string> split(const std::string &str, char delimiter /* = ','*/ while (std::getline(tokenStream, token, delimiter)) { auto trimedToken = token; trimString(trimedToken); - tokens.push_back(trimedToken); + tokens.emplace_back(trimedToken); } return tokens; } std::string getFormattedTimeRemaining(uint32_t time) { - time_t timeRemaining = time - getTimeNow(); + const time_t timeRemaining = time - getTimeNow(); - int days = static_cast<int>(std::floor(timeRemaining / 86400)); + const int days = static_cast<int>(std::floor(timeRemaining / 86400)); std::stringstream output; if (days > 1) { @@ -1886,9 +1921,9 @@ std::string getFormattedTimeRemaining(uint32_t time) { return output.str(); } - int hours = static_cast<int>(std::floor((timeRemaining % 86400) / 3600)); - int minutes = static_cast<int>(std::floor((timeRemaining % 3600) / 60)); - int seconds = static_cast<int>(timeRemaining % 60); + const int hours = static_cast<int>(std::floor((timeRemaining % 86400) / 3600)); + const int minutes = static_cast<int>(std::floor((timeRemaining % 3600) / 60)); + const int seconds = static_cast<int>(timeRemaining % 60); if (hours == 0 && minutes == 0 && seconds > 0) { output << " less than 1 minute"; @@ -1935,8 +1970,8 @@ void sleep_for(uint64_t ms) { */ std::string toKey(const std::string &str) { std::string key = asLowerCaseString(str); - std::replace(key.begin(), key.end(), ' ', '-'); - key.erase(std::remove_if(key.begin(), key.end(), [](char c) { return std::isspace(c); }), key.end()); + std::ranges::replace(key, ' ', '-'); + key.erase(std::ranges::remove_if(key, [](char c) { return std::isspace(c); }).begin(), key.end()); return key; } diff --git a/src/utils/tools.hpp b/src/utils/tools.hpp index 4803dfc393a..04e554d12ce 100644 --- a/src/utils/tools.hpp +++ b/src/utils/tools.hpp @@ -16,7 +16,7 @@ #include "enums/object_category.hpp" namespace pugi { - class xml_parse_result; + struct xml_parse_result; } #ifndef USE_PRECOMPILED_HEADERS diff --git a/src/utils/vectorset.hpp b/src/utils/vectorset.hpp index 0f81ce3960d..9ca56583fba 100644 --- a/src/utils/vectorset.hpp +++ b/src/utils/vectorset.hpp @@ -48,8 +48,8 @@ namespace stdext { return container.push_back(v); } - template <class... _Valty> - auto emplace(_Valty &&... v) { + template <class... Valty> + auto emplace(Valty &&... v) { needUpdate = true; return container.emplace_back(v...); } @@ -64,20 +64,20 @@ namespace stdext { return container.insert(container.end(), list.begin(), list.end()); } - constexpr auto insert(std::vector<T>::const_iterator _Where, const T &_Val) { + constexpr auto insert(typename std::vector<T>::const_iterator Where, const T &Val) { needUpdate = true; - return container.insert(_Where, _Val); + return container.insert(Where, Val); } - constexpr auto insert(std::vector<T>::const_iterator _Where, T &&_Val) { + constexpr auto insert(typename std::vector<T>::const_iterator Where, T &&Val) { needUpdate = true; - return container.insert(_Where, std::move(_Val)); + return container.insert(Where, std::move(Val)); } - template <std::forward_iterator _Iter> - constexpr auto insert(std::vector<T>::const_iterator _Where, _Iter _First, _Iter _Last) { + template <std::forward_iterator Iter> + constexpr auto insert(typename std::vector<T>::const_iterator Where, Iter First, Iter Last) { needUpdate = true; - return container.insert(_Where, _First, _Last); + return container.insert(Where, First, Last); } bool empty() const noexcept { diff --git a/src/utils/vectorsort.hpp b/src/utils/vectorsort.hpp index 0a3618b963f..dfe21d6b076 100644 --- a/src/utils/vectorsort.hpp +++ b/src/utils/vectorsort.hpp @@ -68,14 +68,14 @@ namespace stdext { return container.back(); } - void push_back(const T &v) { + void emplace_back(const T &v) { needUpdate = true; - container.push_back(v); + container.emplace_back(v); } - void push_back(T &&_Val) { + void emplace_back(T &&Val) { needUpdate = true; - container.push_back(std::move(_Val)); + container.emplace_back(std::move(Val)); } // Copy all content list to this @@ -106,10 +106,10 @@ namespace stdext { return res; } - template <class... _Valty> - decltype(auto) emplace_back(_Valty &&... v) { + template <class... Valty> + decltype(auto) emplace_back(Valty &&... v) { needUpdate = true; - return container.emplace_back(std::forward<_Valty>(v)...); + return container.emplace_back(std::forward<Valty>(v)...); } void partial_sort(size_t begin, size_t end = 0) { diff --git a/src/utils/wildcardtree.cpp b/src/utils/wildcardtree.cpp index 4fd830b64cb..9686074c2e9 100644 --- a/src/utils/wildcardtree.cpp +++ b/src/utils/wildcardtree.cpp @@ -12,7 +12,7 @@ #include "utils/wildcardtree.hpp" std::shared_ptr<WildcardTreeNode> WildcardTreeNode::getChild(char ch) { - auto it = children.find(ch); + const auto it = children.find(ch); if (it == children.end()) { return nullptr; } @@ -20,7 +20,7 @@ std::shared_ptr<WildcardTreeNode> WildcardTreeNode::getChild(char ch) { } std::shared_ptr<WildcardTreeNode> WildcardTreeNode::getChild(char ch) const { - auto it = children.find(ch); + const auto it = children.find(ch); if (it == children.end()) { return nullptr; } @@ -28,22 +28,22 @@ std::shared_ptr<WildcardTreeNode> WildcardTreeNode::getChild(char ch) const { } std::shared_ptr<WildcardTreeNode> WildcardTreeNode::addChild(char ch, bool breakp) { - std::shared_ptr<WildcardTreeNode> child = getChild(ch); + auto child = getChild(ch); if (child) { if (breakp && !child->breakpoint) { child->breakpoint = true; } } else { - auto pair = children.emplace(std::piecewise_construct, std::forward_as_tuple(ch), std::forward_as_tuple(std::make_shared<WildcardTreeNode>(breakp))); - child = pair.first->second; + const auto [fst, snd] = children.emplace(std::piecewise_construct, std::forward_as_tuple(ch), std::forward_as_tuple(std::make_shared<WildcardTreeNode>(breakp))); + child = fst->second; } return child; } void WildcardTreeNode::insert(const std::string &str) { - std::shared_ptr<WildcardTreeNode> cur = static_self_cast<WildcardTreeNode>(); + auto cur = static_self_cast<WildcardTreeNode>(); - size_t length = str.length() - 1; + const size_t length = str.length() - 1; for (size_t pos = 0; pos < length; ++pos) { cur = cur->addChild(str[pos], false); } @@ -52,7 +52,7 @@ void WildcardTreeNode::insert(const std::string &str) { } void WildcardTreeNode::remove(const std::string &str) { - std::shared_ptr<WildcardTreeNode> cur = static_self_cast<WildcardTreeNode>(); + auto cur = static_self_cast<WildcardTreeNode>(); std::stack<std::shared_ptr<WildcardTreeNode>> path; path.push(cur); @@ -86,7 +86,7 @@ void WildcardTreeNode::remove(const std::string &str) { ReturnValue WildcardTreeNode::findOne(const std::string &query, std::string &result) const { auto cur = static_self_cast<const WildcardTreeNode>(); - for (char pos : query) { + for (const char &pos : query) { cur = cur->getChild(pos); if (!cur) { return RETURNVALUE_PLAYERWITHTHISNAMEISNOTONLINE; @@ -96,14 +96,14 @@ ReturnValue WildcardTreeNode::findOne(const std::string &query, std::string &res result = query; do { - size_t size = cur->children.size(); + const size_t size = cur->children.size(); if (size == 0) { return RETURNVALUE_NOERROR; } else if (size > 1 || cur->breakpoint) { return RETURNVALUE_NAMEISTOOAMBIGUOUS; } - auto it = cur->children.begin(); + const auto it = cur->children.begin(); result += it->first; cur = it->second; } while (true); diff --git a/src/utils/wildcardtree.hpp b/src/utils/wildcardtree.hpp index 9f3d2cf8ece..ccbad316ebd 100644 --- a/src/utils/wildcardtree.hpp +++ b/src/utils/wildcardtree.hpp @@ -11,7 +11,7 @@ #include "declarations.hpp" -class WildcardTreeNode : public SharedObject { +class WildcardTreeNode final : public SharedObject { public: explicit WildcardTreeNode(bool initBreakpoint) : breakpoint(initBreakpoint) { } From 5311e2b9c873e3e048f8896e5dfdecbe1d86cf22 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Tue, 10 Sep 2024 20:52:16 -0400 Subject: [PATCH 24/34] add atomic-queue connection --- cmake/modules/CanaryLib.cmake | 1 + data/XML/groups.xml | 6 +- src/server/network/connection/connection.cpp | 159 +++++++++--------- src/server/network/connection/connection.hpp | 11 +- src/server/network/protocol/protocollogin.cpp | 3 +- src/server/server.cpp | 2 - vcpkg.json | 1 + 7 files changed, 96 insertions(+), 87 deletions(-) diff --git a/cmake/modules/CanaryLib.cmake b/cmake/modules/CanaryLib.cmake index a3f5410b9d8..a14ee98fd79 100644 --- a/cmake/modules/CanaryLib.cmake +++ b/cmake/modules/CanaryLib.cmake @@ -82,6 +82,7 @@ target_include_directories(${PROJECT_NAME}_lib ${GMP_INCLUDE_DIRS} ${LUAJIT_INCLUDE_DIRS} ${PARALLEL_HASHMAP_INCLUDE_DIRS} + ${ATOMIC_QUEUE_INCLUDE_DIRS} ) # ***************************************************************************** diff --git a/data/XML/groups.xml b/data/XML/groups.xml index 9618a09cd91..66989d1ac86 100644 --- a/data/XML/groups.xml +++ b/data/XML/groups.xml @@ -108,13 +108,13 @@ <flag cannotusecombat="0" /> <!-- Is combat not allowed? Set to 0 to enable the two flags below. If set to 1 these two flags below will be ignored. --> <flag cannotattackplayer="1" /> <!-- If combat is allowed (set to 0 above), attack players is not allowed? --> <flag cannotattackmonster="0" /> <!-- If combat is allowed (set to 0 above), attack monsters is not allowed? --> - <flag cannotbeattacked="1" /> + <flag cannotbeattacked="0" /> <flag canconvinceall="1" /> <flag cansummonall="1" /> <flag canillusionall="1" /> <flag cansenseinvisibility="1" /> - <flag ignoredbymonsters="1" /> - <flag ignoredbynpcs="1" /> + <flag ignoredbymonsters="0" /> + <flag ignoredbynpcs="0" /> <flag notgaininfight="1" /> <flag hasinfinitemana="1" /> <flag hasinfinitesoul="1" /> diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index a2626d91b97..b925f3e7b11 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -44,6 +44,7 @@ void ConnectionManager::closeAll() { } Connection::Connection(asio::io_service &initIoService, ConstServicePort_ptr initservicePort) : + msg(), readTimer(initIoService), writeTimer(initIoService), service_port(std::move(initservicePort)), @@ -53,19 +54,19 @@ Connection::Connection(asio::io_service &initIoService, ConstServicePort_ptr ini void Connection::close(bool force) { ConnectionManager::getInstance().releaseConnection(shared_from_this()); - std::scoped_lock lock(connectionLock); - ip = 0; + ip.store(0, std::memory_order_relaxed); - if (connectionState == CONNECTION_STATE_CLOSED) { + ConnectionState_t expectedState = CONNECTION_STATE_OPEN; + if (!connectionState.compare_exchange_weak(expectedState, CONNECTION_STATE_CLOSED)) { return; } - connectionState = CONNECTION_STATE_CLOSED; if (protocol) { g_dispatcher().addEvent([protocol = protocol] { protocol->release(); }, "Protocol::release", std::chrono::milliseconds(CONNECTION_WRITE_TIMEOUT * 1000).count()); } - if (messageQueue.empty() || force) { + // Verificamos se a fila está vazia usando a fila lock-free + if (messageQueue.was_empty() || force) { closeSocket(); } } @@ -120,11 +121,11 @@ void Connection::acceptInternal(bool toggleParseHeader) { close(FORCE_CLOSE); } } + void Connection::parseProxyIdentification(const std::error_code &error) { - std::scoped_lock lock(connectionLock); readTimer.cancel(); - if (error || connectionState == CONNECTION_STATE_CLOSED) { + if (error || connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_CLOSED) { if (error != asio::error::operation_aborted && error != asio::error::eof && error != asio::error::connection_reset) { g_logger().error("[Connection::parseProxyIdentification] - Read error: {}", error.message()); } @@ -135,35 +136,40 @@ void Connection::parseProxyIdentification(const std::error_code &error) { uint8_t* msgBuffer = msg.getBuffer(); const auto charData = static_cast<char*>(static_cast<void*>(msgBuffer)); const std::string serverName = g_configManager().getString(SERVER_NAME, __FUNCTION__) + "\n"; - if (connectionState == CONNECTION_STATE_IDENTIFYING) { + + if (connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_IDENTIFYING) { if (msgBuffer[1] == 0x00 || strncasecmp(charData, &serverName[0], 2) != 0) { - // Probably not proxy identification so let's try standard parsing method - connectionState = CONNECTION_STATE_OPEN; + connectionState.store(CONNECTION_STATE_OPEN, std::memory_order_relaxed); parseHeader(error); return; - } - const size_t remainder = serverName.length() - 2; - if (remainder > 0) { - connectionState = CONNECTION_STATE_READINGS; - try { - readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); - readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { Connection::handleTimeout(self, error); }); - - // Read the remainder of proxy identification - asio::async_read(socket, asio::buffer(msg.getBuffer(), remainder), [self = shared_from_this()](const std::error_code &error, std::size_t N) { self->parseProxyIdentification(error); }); - } catch (const std::system_error &e) { - g_logger().error("Connection::parseProxyIdentification] - error: {}", e.what()); - close(FORCE_CLOSE); + } else { + const size_t remainder = serverName.length() - 2; + if (remainder > 0) { + connectionState.store(CONNECTION_STATE_READINGS, std::memory_order_relaxed); + try { + readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); + readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { + Connection::handleTimeout(self, error); + }); + + asio::async_read(socket, asio::buffer(msg.getBuffer(), remainder), [self = shared_from_this()](const std::error_code &error, std::size_t N) { + self->parseProxyIdentification(error); + }); + } catch (const std::system_error &e) { + g_logger().error("[Connection::parseProxyIdentification] - Error: {}", e.what()); + close(FORCE_CLOSE); + } + return; + } else { + connectionState.store(CONNECTION_STATE_OPEN, std::memory_order_relaxed); } - return; } - connectionState = CONNECTION_STATE_OPEN; - } else if (connectionState == CONNECTION_STATE_READINGS) { + } else if (connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_READINGS) { const size_t remainder = serverName.length() - 2; if (strncasecmp(charData, &serverName[2], remainder) == 0) { - connectionState = CONNECTION_STATE_OPEN; + connectionState.store(CONNECTION_STATE_OPEN, std::memory_order_relaxed); } else { - g_logger().error("Connection::parseProxyIdentification] Invalid Client Login! Server Name mismatch!"); + g_logger().error("[Connection::parseProxyIdentification] Invalid Client Login! Server Name mismatch!"); close(FORCE_CLOSE); return; } @@ -173,7 +179,6 @@ void Connection::parseProxyIdentification(const std::error_code &error) { } void Connection::parseHeader(const std::error_code &error) { - std::scoped_lock lock(connectionLock); readTimer.cancel(); if (error) { @@ -182,8 +187,7 @@ void Connection::parseHeader(const std::error_code &error) { } close(FORCE_CLOSE); return; - } - if (connectionState == CONNECTION_STATE_CLOSED) { + } else if (connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_CLOSED) { return; } @@ -207,12 +211,16 @@ void Connection::parseHeader(const std::error_code &error) { try { readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); - readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { Connection::handleTimeout(self, error); }); + readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { + Connection::handleTimeout(self, error); + }); // Read packet content msg.setLength(size + HEADER_LENGTH); - // Read the remainder of proxy identification - asio::async_read(socket, asio::buffer(msg.getBodyBuffer(), size), [self = shared_from_this()](const std::error_code &error, std::size_t N) { self->parsePacket(error); }); + + asio::async_read(socket, asio::buffer(msg.getBodyBuffer(), size), [self = shared_from_this()](const std::error_code &error, std::size_t N) { + self->parsePacket(error); + }); } catch (const std::system_error &e) { g_logger().error("[Connection::parseHeader] - error: {}", e.what()); close(FORCE_CLOSE); @@ -220,10 +228,9 @@ void Connection::parseHeader(const std::error_code &error) { } void Connection::parsePacket(const std::error_code &error) { - std::scoped_lock lock(connectionLock); readTimer.cancel(); - if (error || connectionState == CONNECTION_STATE_CLOSED) { + if (error || connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_CLOSED) { if (error) { g_logger().error("[Connection::parsePacket] - Read error: {}", error.message()); } @@ -232,6 +239,7 @@ void Connection::parsePacket(const std::error_code &error) { } bool skipReadingNextPacket = false; + if (!receivedFirst) { // First message received receivedFirst = true; @@ -274,11 +282,15 @@ void Connection::parsePacket(const std::error_code &error) { try { readTimer.expires_from_now(std::chrono::seconds(CONNECTION_READ_TIMEOUT)); - readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { Connection::handleTimeout(self, error); }); + readTimer.async_wait([self = std::weak_ptr<Connection>(shared_from_this())](const std::error_code &error) { + Connection::handleTimeout(self, error); + }); if (!skipReadingNextPacket) { // Wait to the next packet - asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), [self = shared_from_this()](const std::error_code &error, std::size_t N) { self->parseHeader(error); }); + asio::async_read(socket, asio::buffer(msg.getBuffer(), HEADER_LENGTH), [self = shared_from_this()](const std::error_code &error, std::size_t N) { + self->parseHeader(error); + }); } } catch (const std::system_error &e) { g_logger().error("[Connection::parsePacket] - error: {}", e.what()); @@ -299,66 +311,64 @@ void Connection::resumeWork() { } void Connection::send(const OutputMessage_ptr &outputMessage) { - std::scoped_lock lock(connectionLock); - if (connectionState == CONNECTION_STATE_CLOSED) { + if (connectionState.load(std::memory_order_relaxed) == CONNECTION_STATE_CLOSED) { return; } - const bool noPendingWrite = messageQueue.empty(); - messageQueue.emplace_back(outputMessage); + // Inserir a mensagem na fila lock-free + if (!messageQueue.try_push(outputMessage)) { + g_logger().error("[Connection::send] - Queue is full. Dropping message."); + return; + } - if (noPendingWrite) { - if (socket.is_open()) { - try { - asio::post(socket.get_executor(), [self = shared_from_this()] { self->internalWorker(); }); - } catch (const std::system_error &e) { - g_logger().error("[Connection::send] - Exception in posting write operation: {}", e.what()); - close(FORCE_CLOSE); - } - } else { - g_logger().error("[Connection::send] - Socket is not open for writing."); + if (socket.is_open()) { + try { + asio::post(socket.get_executor(), [self = shared_from_this()] { self->internalWorker(); }); + } catch (const std::system_error &e) { + g_logger().error("[Connection::send] - Exception in posting write operation: {}", e.what()); close(FORCE_CLOSE); } + } else { + g_logger().error("[Connection::send] - Socket is not open for writing."); + close(FORCE_CLOSE); } } void Connection::internalWorker() { - std::unique_lock lock(connectionLock); - if (messageQueue.empty()) { + OutputMessage_ptr outputMessage; + if (!messageQueue.try_pop(outputMessage)) { if (connectionState == CONNECTION_STATE_CLOSED) { closeSocket(); } return; } - const auto &outputMessage = messageQueue.front(); - lock.unlock(); protocol->onSendMessage(outputMessage); - lock.lock(); try { asio::post(socket.get_executor(), [self = shared_from_this(), outputMessage] { self->internalSend(outputMessage); }); - } catch (std::system_error& e) { - g_logger().error("[Connection::internalWorker] - error: {}", e.what()); - messageQueue.clear(); + } catch (std::system_error &e) { + g_logger().error("[Connection::internalWorker] - Exception: {}", e.what()); close(FORCE_CLOSE); } } uint32_t Connection::getIP() { - std::scoped_lock lock(connectionLock); + uint32_t currentIP = ip.load(std::memory_order_relaxed); - if (ip == 1) { + if (currentIP == 1) { std::error_code error; const asio::ip::tcp::endpoint endpoint = socket.remote_endpoint(error); if (error) { g_logger().error("[Connection::getIP] - Failed to get remote endpoint: {}", error.message()); - ip = 0; + ip.store(0, std::memory_order_relaxed); } else { - ip = htonl(endpoint.address().to_v4().to_uint()); + currentIP = htonl(endpoint.address().to_v4().to_uint()); + ip.store(currentIP, std::memory_order_relaxed); } } - return ip; + + return ip.load(std::memory_order_relaxed); } void Connection::internalSend(const OutputMessage_ptr &outputMessage) { @@ -374,32 +384,29 @@ void Connection::internalSend(const OutputMessage_ptr &outputMessage) { } void Connection::onWriteOperation(const std::error_code &error) { - std::unique_lock lock(connectionLock); writeTimer.cancel(); if (error) { g_logger().error("[Connection::onWriteOperation] - Write error: {}", error.message()); - messageQueue.clear(); + while (!messageQueue.was_empty()) { + OutputMessage_ptr discardedMessage; + messageQueue.try_pop(discardedMessage); // Remover as mensagens restantes + } close(FORCE_CLOSE); return; } - messageQueue.pop_front(); - - if (!messageQueue.empty()) { - const auto &outputMessage = messageQueue.front(); - lock.unlock(); + OutputMessage_ptr outputMessage; + if (messageQueue.try_pop(outputMessage)) { protocol->onSendMessage(outputMessage); - lock.lock(); try { asio::post(socket.get_executor(), [self = shared_from_this(), outputMessage] { self->internalSend(outputMessage); }); - } catch (std::system_error& e) { + } catch (std::system_error &e) { g_logger().error("[Connection::onWriteOperation] - error: {}", e.what()); - messageQueue.clear(); close(FORCE_CLOSE); } } else if (connectionState == CONNECTION_STATE_CLOSED) { - closeSocket(); + closeSocket(); // Fechar o socket se a conexão estiver fechada } } diff --git a/src/server/network/connection/connection.hpp b/src/server/network/connection/connection.hpp index 788ae0a3a43..5de60e8a8e9 100644 --- a/src/server/network/connection/connection.hpp +++ b/src/server/network/connection/connection.hpp @@ -13,6 +13,8 @@ #include "lib/di/container.hpp" #include "server/network/message/networkmessage.hpp" +#include "atomic_queue/atomic_queue.h" + static constexpr int32_t CONNECTION_WRITE_TIMEOUT = 30; static constexpr int32_t CONNECTION_READ_TIMEOUT = 30; @@ -91,9 +93,9 @@ class Connection : public std::enable_shared_from_this<Connection> { asio::high_resolution_timer readTimer; asio::high_resolution_timer writeTimer; - std::recursive_mutex connectionLock; - std::list<OutputMessage_ptr> messageQueue; + // Use a fila lock-free com capacidade para 1024 mensagens + atomic_queue::AtomicQueue2<OutputMessage_ptr, 1024> messageQueue; ConstServicePort_ptr service_port; Protocol_ptr protocol; @@ -102,9 +104,10 @@ class Connection : public std::enable_shared_from_this<Connection> { std::time_t timeConnected = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); uint32_t packetsSent = 0; - uint32_t ip = 1; + std::atomic<uint32_t> ip { 1 }; + + std::atomic<ConnectionState_t> connectionState = CONNECTION_STATE_OPEN; - std::underlying_type_t<ConnectionState_t> connectionState = CONNECTION_STATE_OPEN; bool receivedFirst = false; friend class ServicePort; diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index 0c3ec9e6977..57bdfb3580c 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -36,8 +36,7 @@ void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const if (oldProtocol && !g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__)) { disconnectClient(fmt::format("Only protocol version {}.{} is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; - } - if (!oldProtocol) { + }else if (!oldProtocol) { disconnectClient(fmt::format("Only protocol version {}.{} or outdated 11.00 is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; } diff --git a/src/server/server.cpp b/src/server/server.cpp index 4fce80ab75e..b4d38a4ec71 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -7,8 +7,6 @@ * Website: https://docs.opentibiabr.com/ */ -#include <memory> - #include "pch.hpp" #include "server/network/message/outputmessage.hpp" diff --git a/vcpkg.json b/vcpkg.json index 5e0623857a4..1ce3f25b40d 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -18,6 +18,7 @@ "spdlog", "zlib", "bshoshany-thread-pool", + "atomic-queue", { "name": "libmariadb", "features": [ From 5bc695897d37e306aac0388d7f4089eea445a342 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Tue, 10 Sep 2024 20:54:02 -0400 Subject: [PATCH 25/34] update avx2 encrypt, decrypt and fix crash convertIP function --- src/items/item.hpp | 2 +- .../creatures/player/player_functions.hpp | 4 +- src/lua/functions/items/weapon_functions.hpp | 4 +- src/lua/functions/map/house_functions.hpp | 4 +- src/lua/functions/map/map_functions.hpp | 5 +- src/lua/functions/map/position_functions.hpp | 4 +- src/lua/functions/map/teleport_functions.hpp | 4 +- src/lua/functions/map/tile_functions.hpp | 5 +- src/lua/functions/map/town_functions.hpp | 5 +- src/lua/scripts/script_environment.cpp | 2 +- src/server/network/connection/connection.cpp | 2 +- src/server/network/connection/connection.hpp | 1 - src/server/network/protocol/protocol.cpp | 106 +++++++----------- src/server/network/protocol/protocol.hpp | 83 +++++++++++--- src/server/network/protocol/protocollogin.cpp | 2 +- src/server/server.cpp | 4 +- src/server/server.hpp | 4 +- src/utils/tools.cpp | 24 ++-- 18 files changed, 147 insertions(+), 118 deletions(-) diff --git a/src/items/item.hpp b/src/items/item.hpp index 96d90ac8195..e0ff92e2d85 100644 --- a/src/items/item.hpp +++ b/src/items/item.hpp @@ -630,7 +630,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return true; } virtual void onRemoved(); - virtual void onTradeEvent(TradeEvents_t, const std::shared_ptr<Player>&) { } + virtual void onTradeEvent(TradeEvents_t, const std::shared_ptr<Player> &) { } virtual void startDecaying(); virtual void stopDecaying(); diff --git a/src/lua/functions/creatures/player/player_functions.hpp b/src/lua/functions/creatures/player/player_functions.hpp index 722151bc247..ae18784f2c5 100644 --- a/src/lua/functions/creatures/player/player_functions.hpp +++ b/src/lua/functions/creatures/player/player_functions.hpp @@ -17,8 +17,8 @@ #include "lua/functions/creatures/player/vocation_functions.hpp" class PlayerFunctions final : LuaScriptInterface { - explicit PlayerFunctions(lua_State* L) - : LuaScriptInterface("PlayerFunctions") { + explicit PlayerFunctions(lua_State* L) : + LuaScriptInterface("PlayerFunctions") { init(L); } ~PlayerFunctions() override = default; diff --git a/src/lua/functions/items/weapon_functions.hpp b/src/lua/functions/items/weapon_functions.hpp index 2aeef132710..d68146f82bc 100644 --- a/src/lua/functions/items/weapon_functions.hpp +++ b/src/lua/functions/items/weapon_functions.hpp @@ -13,8 +13,8 @@ class WeaponFunctions final : LuaScriptInterface { public: - explicit WeaponFunctions(lua_State* L) - : LuaScriptInterface("WeaponFunctions") { + explicit WeaponFunctions(lua_State* L) : + LuaScriptInterface("WeaponFunctions") { init(L); } ~WeaponFunctions() override = default; diff --git a/src/lua/functions/map/house_functions.hpp b/src/lua/functions/map/house_functions.hpp index addb2e7015c..8d527bf6354 100644 --- a/src/lua/functions/map/house_functions.hpp +++ b/src/lua/functions/map/house_functions.hpp @@ -13,8 +13,8 @@ class HouseFunctions final : LuaScriptInterface { public: - explicit HouseFunctions(lua_State* L) - : LuaScriptInterface("HouseFunctions") { + explicit HouseFunctions(lua_State* L) : + LuaScriptInterface("HouseFunctions") { init(L); } ~HouseFunctions() override = default; diff --git a/src/lua/functions/map/map_functions.hpp b/src/lua/functions/map/map_functions.hpp index 4f1e76097a2..c89ee760d39 100644 --- a/src/lua/functions/map/map_functions.hpp +++ b/src/lua/functions/map/map_functions.hpp @@ -18,9 +18,8 @@ class MapFunctions final : LuaScriptInterface { public: - - explicit MapFunctions(lua_State* L) - : LuaScriptInterface("MapFunctions") { + explicit MapFunctions(lua_State* L) : + LuaScriptInterface("MapFunctions") { init(L); } ~MapFunctions() override = default; diff --git a/src/lua/functions/map/position_functions.hpp b/src/lua/functions/map/position_functions.hpp index debdbd864ec..4bb6917aecc 100644 --- a/src/lua/functions/map/position_functions.hpp +++ b/src/lua/functions/map/position_functions.hpp @@ -13,8 +13,8 @@ class PositionFunctions final : LuaScriptInterface { public: - explicit PositionFunctions(lua_State* L) - : LuaScriptInterface("PositionFunctions") { + explicit PositionFunctions(lua_State* L) : + LuaScriptInterface("PositionFunctions") { init(L); } ~PositionFunctions() override = default; diff --git a/src/lua/functions/map/teleport_functions.hpp b/src/lua/functions/map/teleport_functions.hpp index a2751ab04be..57f59a70315 100644 --- a/src/lua/functions/map/teleport_functions.hpp +++ b/src/lua/functions/map/teleport_functions.hpp @@ -13,8 +13,8 @@ class TeleportFunctions final : LuaScriptInterface { public: - explicit TeleportFunctions(lua_State* L) - : LuaScriptInterface("TeleportFunctions") { + explicit TeleportFunctions(lua_State* L) : + LuaScriptInterface("TeleportFunctions") { init(L); } ~TeleportFunctions() override = default; diff --git a/src/lua/functions/map/tile_functions.hpp b/src/lua/functions/map/tile_functions.hpp index 2ce32cf18dd..a1183508b45 100644 --- a/src/lua/functions/map/tile_functions.hpp +++ b/src/lua/functions/map/tile_functions.hpp @@ -13,9 +13,8 @@ class TileFunctions final : LuaScriptInterface { public: - - explicit TileFunctions(lua_State* L) - : LuaScriptInterface("TileFunctions") { + explicit TileFunctions(lua_State* L) : + LuaScriptInterface("TileFunctions") { init(L); } ~TileFunctions() override = default; diff --git a/src/lua/functions/map/town_functions.hpp b/src/lua/functions/map/town_functions.hpp index efc6e849259..a3e41ec67ae 100644 --- a/src/lua/functions/map/town_functions.hpp +++ b/src/lua/functions/map/town_functions.hpp @@ -13,8 +13,8 @@ class TownFunctions final : LuaScriptInterface { public: - explicit TownFunctions(lua_State* L) - : LuaScriptInterface("TownFunctions") { + explicit TownFunctions(lua_State* L) : + LuaScriptInterface("TownFunctions") { init(L); } ~TownFunctions() override = default; @@ -34,4 +34,3 @@ class TownFunctions final : LuaScriptInterface { static int luaTownGetName(lua_State* L); static int luaTownGetTemplePosition(lua_State* L); }; - diff --git a/src/lua/scripts/script_environment.cpp b/src/lua/scripts/script_environment.cpp index bd4d2aac934..66bb26fa5d2 100644 --- a/src/lua/scripts/script_environment.cpp +++ b/src/lua/scripts/script_environment.cpp @@ -53,7 +53,7 @@ bool ScriptEnvironment::setCallbackId(int32_t newCallbackId, LuaScriptInterface* return true; } -void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface* &retScriptInterface, int32_t &retCallbackId, bool &retTimerEvent) const { +void ScriptEnvironment::getEventInfo(int32_t &retScriptId, LuaScriptInterface*&retScriptInterface, int32_t &retCallbackId, bool &retTimerEvent) const { retScriptId = this->scriptId; retScriptInterface = interface; retCallbackId = this->callbackId; diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index b925f3e7b11..4a93b7cc633 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -406,7 +406,7 @@ void Connection::onWriteOperation(const std::error_code &error) { close(FORCE_CLOSE); } } else if (connectionState == CONNECTION_STATE_CLOSED) { - closeSocket(); // Fechar o socket se a conexão estiver fechada + closeSocket(); // Fechar o socket se a conexão estiver fechada } } diff --git a/src/server/network/connection/connection.hpp b/src/server/network/connection/connection.hpp index 5de60e8a8e9..5877170a16a 100644 --- a/src/server/network/connection/connection.hpp +++ b/src/server/network/connection/connection.hpp @@ -93,7 +93,6 @@ class Connection : public std::enable_shared_from_this<Connection> { asio::high_resolution_timer readTimer; asio::high_resolution_timer writeTimer; - // Use a fila lock-free com capacidade para 1024 mensagens atomic_queue::AtomicQueue2<OutputMessage_ptr, 1024> messageQueue; diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index c48f1ddd361..2538b0f5460 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -14,12 +14,6 @@ #include "security/rsa.hpp" #include "game/scheduling/dispatcher.hpp" -#ifdef _WIN32 - #include <malloc.h> // Para _aligned_malloc e _aligned_free no Windows -#else - #include <cstdlib> // Para std::aligned_alloc e std::free em Linux -#endif - void Protocol::onSendMessage(const OutputMessage_ptr &msg) { if (!rawMessages) { const uint32_t sendMessageChecksum = msg->getLength() >= 128 && compression(*msg) ? (1U << 31) : 0; @@ -111,44 +105,39 @@ OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) { } void Protocol::XTEA_encrypt(OutputMessage &msg) const { - // A mensagem deve ser múltiplo de 8 const size_t paddingBytes = msg.getLength() & 7; if (paddingBytes != 0) { msg.addPaddingBytes(8 - paddingBytes); } uint8_t* buffer = msg.getOutputBuffer(); - auto messageLength = static_cast<int32_t>(msg.getLength()); - int32_t readPos = 0; + const auto messageLength = static_cast<int32_t>(msg.getLength()); - // Precache das somas de controle para criptografia precacheControlSumsEncrypt(); - // Alocar memória alinhada -#ifdef _WIN32 - auto* alignedBuffer = static_cast<uint8_t*>(_aligned_malloc(messageLength, 32)); -#else - uint8_t* alignedBuffer = reinterpret_cast<uint8_t*>(std::aligned_alloc(32, messageLength)); -#endif + // Alocar memória alinhada usando std::unique_ptr para garantir liberação + const std::unique_ptr<uint8_t, AlignedFreeDeleter> alignedBuffer( + aligned_alloc_memory(messageLength, 32), AlignedFreeDeleter() + ); if (!alignedBuffer) { - throw std::bad_alloc(); // Tratar erro de alocação + g_logger().error("[] - Error alianhamento memory", __FUNCTION__); } - // Copiar os dados para o buffer alinhado usando AVX2 - simd_memcpy_avx2(alignedBuffer, buffer, messageLength); + // Copiar dados para buffer alinhado usando AVX2 + simd_memcpy_avx2(alignedBuffer.get(), buffer, messageLength); - // Processar em blocos de 64 bits + int32_t readPos = 0; while (readPos < messageLength) { - // Prefetch para reduzir a latência da memória - _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer + readPos + 64), _MM_HINT_T0); + // Usar prefetch otimizado com _MM_HINT_T1 para cache L2 + _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer.get() + readPos + 256), _MM_HINT_T1); - // Carregar 64 bits (dois inteiros de 32 bits) do buffer alinhado com AVX2 - __m256i vData = _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer + readPos)); + __m256i vData = is_aligned(alignedBuffer.get() + readPos, 32) + ? _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)) + : _mm256_loadu_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)); auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); - // Desenrolar o loop em grupos de 8 para melhor uso do pipeline for (int32_t i = 0; i < 32; i += 8) { vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[i * 2]; vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[i * 2 + 1]; @@ -175,20 +164,17 @@ void Protocol::XTEA_encrypt(OutputMessage &msg) const { vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 7) * 2 + 1]; } - // Armazenar os resultados de volta no buffer alinhado com AVX2 - _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer + readPos), vData); + if (is_aligned(alignedBuffer.get() + readPos, 32)) { + _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + } else { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + } + readPos += 8; } - // Copiar o buffer processado de volta para o buffer original usando AVX2 - simd_memcpy_avx2(buffer, alignedBuffer, messageLength); - - // Liberar memória alinhada -#ifdef _WIN32 - _aligned_free(alignedBuffer); -#else - std::free(alignedBuffer); -#endif + // Copiar de volta para o buffer original + simd_memcpy_avx2(buffer, alignedBuffer.get(), messageLength); } bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { @@ -198,37 +184,31 @@ bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { } uint8_t* buffer = msg.getBuffer() + msg.getBufferPosition(); - auto messageLength = static_cast<int32_t>(msgLength); - int32_t readPos = 0; + const auto messageLength = static_cast<int32_t>(msgLength); - // Precache das somas de controle para descriptografia precacheControlSumsDecrypt(); - // Alocar memória alinhada -#ifdef _WIN32 - auto* alignedBuffer = reinterpret_cast<uint8_t*>(_aligned_malloc(messageLength, 32)); -#else - uint8_t* alignedBuffer = reinterpret_cast<uint8_t*>(std::aligned_alloc(32, messageLength)); -#endif + // Alocar memória alinhada usando std::unique_ptr para garantir liberação + const std::unique_ptr<uint8_t, AlignedFreeDeleter> alignedBuffer( + aligned_alloc_memory(messageLength, 32), AlignedFreeDeleter() + ); if (!alignedBuffer) { - throw std::bad_alloc(); // Tratar erro de alocação + g_logger().error("[] - Error alianhamento memory", __FUNCTION__); } - // Copiar os dados para o buffer alinhado usando AVX2 - simd_memcpy_avx2(alignedBuffer, buffer, messageLength); + simd_memcpy_avx2(alignedBuffer.get(), buffer, messageLength); - // Processar em blocos de 64 bits + int32_t readPos = 0; while (readPos < messageLength) { - // Prefetch para reduzir a latência da memória - _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer + readPos + 64), _MM_HINT_T0); + _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer.get() + readPos + 256), _MM_HINT_T1); - // Carregar 64 bits (dois inteiros de 32 bits) do buffer alinhado com AVX2 - __m256i vData = _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer + readPos)); + __m256i vData = is_aligned(alignedBuffer.get() + readPos, 32) + ? _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)) + : _mm256_loadu_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)); auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); - // Desenrolar o loop em grupos de 8 para melhor uso do pipeline for (int32_t i = 0; i < 32; i += 8) { vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[i * 2]; vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[i * 2 + 1]; @@ -255,20 +235,16 @@ bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 7) * 2 + 1]; } - // Armazenar os resultados de volta no buffer alinhado com AVX2 - _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer + readPos), vData); + if (is_aligned(alignedBuffer.get() + readPos, 32)) { + _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + } else { + _mm256_storeu_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + } + readPos += 8; } - // Copiar o buffer processado de volta para o buffer original usando AVX2 - simd_memcpy_avx2(buffer, alignedBuffer, messageLength); - - // Liberar memória alinhada -#ifdef _WIN32 - _aligned_free(alignedBuffer); -#else - std::free(alignedBuffer); -#endif + simd_memcpy_avx2(buffer, alignedBuffer.get(), messageLength); const auto innerLength = msg.get<uint16_t>(); if (std::cmp_greater(innerLength, msgLength - 2)) { diff --git a/src/server/network/protocol/protocol.hpp b/src/server/network/protocol/protocol.hpp index d0ecbd6032a..5207c396a4a 100644 --- a/src/server/network/protocol/protocol.hpp +++ b/src/server/network/protocol/protocol.hpp @@ -118,21 +118,83 @@ class Protocol : public std::enable_shared_from_this<Protocol> { std::array<char, NETWORKMESSAGE_MAXSIZE> buffer {}; }; - inline void simd_memcpy_avx2(uint8_t* dest, const uint8_t* src, size_t len) const { + struct AlignedFreeDeleter { + void operator()(uint8_t* ptr) const { + if (ptr) { +#ifdef _WIN32 + _aligned_free(ptr); // Liberar memória no Windows +#else + std::free(ptr); // Liberar memória no Linux/Unix +#endif + } + } + }; + + inline uint8_t* aligned_alloc_memory(size_t size, size_t alignment) const { +#ifdef _WIN32 + return static_cast<uint8_t*>(_aligned_malloc(size, alignment)); +#else + uint8_t* originalMemory = nullptr; + + // Tenta alocar memória alinhada com posix_memalign + if (posix_memalign(reinterpret_cast<void**>(&originalMemory), alignment, size) != 0) { + return nullptr; // Alocação falhou + } + + // Verifique se a memória está alinhada + if (!is_aligned(originalMemory, alignment)) { + // A memória não está devidamente alinhada, ajustar manualmente + uintptr_t address = reinterpret_cast<uintptr_t>(originalMemory); + uintptr_t alignedAddress = (address + alignment - 1) & ~(alignment - 1); + return reinterpret_cast<uint8_t*>(alignedAddress); + } + + return originalMemory; // A memória já está alinhada +#endif + } + + // Função para verificar o alinhamento usando SIMD + inline bool is_aligned(const void* ptr, size_t alignment) const { + return _mm_testz_si128(_mm_set1_epi64x(reinterpret_cast<uintptr_t>(ptr)), _mm_set1_epi64x(alignment - 1)); + } + + // Função de cópia usando AVX2 com verificação de alinhamento + inline void simd_memcpy_avx2(uint8_t* __restrict dest, const uint8_t* __restrict src, size_t len) const { size_t i = 0; - // Copiar blocos de 32 bytes por vez (256 bits) com AVX2 - for (; i + 32 <= len; i += 32) { - const __m256i data = _mm256_load_si256(reinterpret_cast<const __m256i*>(src + i)); - _mm256_store_si256(reinterpret_cast<__m256i*>(dest + i), data); + // Verifica se src e dest estão ambos alinhados para 32 bytes + const bool src_aligned = is_aligned(src, 32); + const bool dest_aligned = is_aligned(dest, 32); + + if (src_aligned && dest_aligned) { + // Alinhado: Usar as instruções AVX2 alinhadas + for (; i + 32 <= len; i += 32) { + const __m256i data = _mm256_load_si256(reinterpret_cast<const __m256i*>(src + i)); + _mm256_store_si256(reinterpret_cast<__m256i*>(dest + i), data); + } + } else { + // Desalinhado: Usar as instruções AVX2 desalinhadas + for (; i + 32 <= len; i += 32) { + const __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src + i)); + _mm256_storeu_si256(reinterpret_cast<__m256i*>(dest + i), data); + } } - // Copiar os bytes restantes que não formam um bloco completo de 32 bytes + // Copiar os bytes restantes for (; i < len; ++i) { dest[i] = src[i]; } } + void precacheControlSumsEncrypt() const; + void precacheControlSumsDecrypt() const; + + mutable std::array<uint32_t, 32 * 2> cachedControlSumsEncrypt {}; + mutable std::array<uint32_t, 32 * 2> cachedControlSumsDecrypt {}; + mutable bool cacheEncryptInitialized = false; + mutable bool cacheDecryptInitialized = false; + mutable std::array<uint32_t, 4> key {}; + void XTEA_encrypt(OutputMessage &msg) const; bool XTEA_decrypt(NetworkMessage &msg) const; bool compression(OutputMessage &msg) const; @@ -146,14 +208,5 @@ class Protocol : public std::enable_shared_from_this<Protocol> { bool encryptionEnabled = false; bool rawMessages = false; - mutable std::array<uint32_t, 32 * 2> cachedControlSumsEncrypt; // Cache para criptografia - mutable std::array<uint32_t, 32 * 2> cachedControlSumsDecrypt; // Cache para descriptografia - mutable bool cacheEncryptInitialized = false; - mutable bool cacheDecryptInitialized = false; - mutable std::array<uint32_t, 4> key; - - void precacheControlSumsEncrypt() const; - void precacheControlSumsDecrypt() const; - friend class Connection; }; diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index 57bdfb3580c..409528565ac 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -36,7 +36,7 @@ void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const if (oldProtocol && !g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__)) { disconnectClient(fmt::format("Only protocol version {}.{} is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; - }else if (!oldProtocol) { + } else if (!oldProtocol) { disconnectClient(fmt::format("Only protocol version {}.{} or outdated 11.00 is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; } diff --git a/src/server/server.cpp b/src/server/server.cpp index b4d38a4ec71..d832a090c08 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -92,7 +92,7 @@ void ServicePort::accept() { acceptor->async_accept(connection->getSocket(), [self = shared_from_this(), connection](const std::error_code &error) { self->onAccept(connection, error); }); } -void ServicePort::onAccept(const Connection_ptr& connection, const std::error_code &error) { +void ServicePort::onAccept(const Connection_ptr &connection, const std::error_code &error) { if (!error) { if (services.empty()) { return; @@ -140,7 +140,7 @@ void ServicePort::onStopServer() const { close(); } -void ServicePort::openAcceptor(const std::weak_ptr<ServicePort>& weak_service, uint16_t port) { +void ServicePort::openAcceptor(const std::weak_ptr<ServicePort> &weak_service, uint16_t port) { if (const auto service = weak_service.lock()) { service->open(port); } diff --git a/src/server/server.hpp b/src/server/server.hpp index fbe0a578a38..942dd9ebf5e 100644 --- a/src/server/server.hpp +++ b/src/server/server.hpp @@ -58,7 +58,7 @@ class ServicePort : public std::enable_shared_from_this<ServicePort> { ServicePort(const ServicePort &) = delete; ServicePort &operator=(const ServicePort &) = delete; - static void openAcceptor(const std::weak_ptr<ServicePort>& weak_service, uint16_t port); + static void openAcceptor(const std::weak_ptr<ServicePort> &weak_service, uint16_t port); void open(uint16_t port); void close() const; bool is_single_socket() const; @@ -68,7 +68,7 @@ class ServicePort : public std::enable_shared_from_this<ServicePort> { Protocol_ptr make_protocol(bool checksummed, NetworkMessage &msg, const Connection_ptr &connection) const; void onStopServer() const; - void onAccept(const Connection_ptr& connection, const std::error_code &error); + void onAccept(const Connection_ptr &connection, const std::error_code &error); private: void accept(); diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index 1a6796375cf..7ee9a765246 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -428,9 +428,13 @@ void trimString(std::string &str) { } std::string convertIPToString(uint32_t ip) { - char buffer[17]; - fmt::format_to_n(buffer, sizeof(buffer), "{}.{}.{}.{}", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24)); - return buffer; + char buffer[16]; // 16 bytes: suficiente para 'xxx.xxx.xxx.xxx' + '\0' + auto result = fmt::format_to_n(buffer, sizeof(buffer) - 1, "{}.{}.{}.{}", ip & 0xFF, (ip >> 8) & 0xFF, (ip >> 16) & 0xFF, (ip >> 24)); + + // Garantir que o buffer esteja nulo-terminado + buffer[std::min(result.size, sizeof(buffer) - 1)] = '\0'; + + return std::string(buffer); } std::string formatDate(time_t time) { @@ -1756,31 +1760,31 @@ uint8_t forgeBonus(int32_t number) { return 0; } // Dust not consumed - if (number >= 7400 && number < 9000) { + if (number >= 7400 && number < 9000) { return 1; } // Cores not consumed - if (number >= 9000 && number < 9500) { + if (number >= 9000 && number < 9500) { return 2; } // Gold not consumed - if (number >= 9500 && number < 9525) { + if (number >= 9500 && number < 9525) { return 3; } // Second item retained with decreased tier - if (number >= 9525 && number < 9550) { + if (number >= 9525 && number < 9550) { return 4; } // Second item retained with unchanged tier - if (number >= 9550 && number < 9950) { + if (number >= 9550 && number < 9950) { return 5; } // Second item retained with increased tier - if (number >= 9950 && number < 9975) { + if (number >= 9950 && number < 9975) { return 6; } // Gain two tiers - if (number >= 9975) { + if (number >= 9975) { return 7; } From 7b10cca4628049d32ad03d0393cf328e29200fa7 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Wed, 11 Sep 2024 19:18:09 -0400 Subject: [PATCH 26/34] update player online cycle --- src/creatures/players/player.cpp | 2 - src/database/database.hpp | 24 ++++---- src/game/game.cpp | 56 ++++++++++++++++++- src/game/game.hpp | 16 +++--- src/game/scheduling/dispatcher.hpp | 2 +- src/io/iologindata.cpp | 19 ------- src/io/iologindata.hpp | 1 - .../creatures/player/player_functions.cpp | 2 - src/server/network/protocol/protocolgame.cpp | 1 - 9 files changed, 78 insertions(+), 45 deletions(-) diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 3cf09df3692..351c214a3fd 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -1744,7 +1744,6 @@ void Player::onCreatureAppear(const std::shared_ptr<Creature> &creature, bool is } g_game().checkPlayersRecord(); - IOLoginData::updateOnlineStatus(guid, true); if (getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL, __FUNCTION__) && getVocationId() > VOCATION_NONE) { for (uint8_t i = 2; i <= 6; i++) { if (!hasBlessing(i)) { @@ -1859,7 +1858,6 @@ void Player::onRemoveCreature(const std::shared_ptr<Creature> &creature, bool is g_logger().info("{} has logged out", getName()); g_chat().removeUserFromAllChannels(player); clearPartyInvitations(); - IOLoginData::updateOnlineStatus(guid, false); } if (eventWalk != 0) { diff --git a/src/database/database.hpp b/src/database/database.hpp index c7d568b8919..21523539971 100644 --- a/src/database/database.hpp +++ b/src/database/database.hpp @@ -200,16 +200,20 @@ class DBTransaction { template <typename Func> static bool executeWithinTransaction(const Func &toBeExecuted) { - DBTransaction transaction; - try { - transaction.begin(); - bool result = toBeExecuted(); - transaction.commit(); - return result; - } catch (const std::exception &exception) { - transaction.rollback(); - g_logger().error("[{}] Error occurred committing transaction, error: {}", __FUNCTION__, exception.what()); - return false; + bool changesExpected = toBeExecuted(); + if (changesExpected) { + DBTransaction transaction; + try { + transaction.begin(); + transaction.commit(); + return changesExpected; + } catch (const std::exception &exception) { + transaction.rollback(); + g_logger().error("[{}] Error occurred during transaction, error: {}", __FUNCTION__, exception.what()); + return false; + } + } else { + return true; } } diff --git a/src/game/game.cpp b/src/game/game.cpp index d2a2c5567ff..91697ba5b25 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -534,6 +534,10 @@ void Game::start(ServiceManager* manager) { ); } + g_dispatcher().cycleEvent( + UPDATE_PLAYERS_ONLINE_DB, [this] { updatePlayersOnline(); }, "Game::updatePlayersOnline" + ); + g_dispatcher().cycleEvent( 5000, [this] { teste(); }, "Calling GC" ); @@ -10348,7 +10352,6 @@ void Game::playerCheckActivity(const std::string &playerName, int interval) { if (player->getIP() == 0) { g_game().removePlayerUniqueLogin(playerName); - IOLoginData::updateOnlineStatus(player->guid, false); g_logger().info("Player with name '{}' has logged out due to exited in death screen", player->getName()); player->disconnect(); return; @@ -10364,7 +10367,6 @@ void Game::playerCheckActivity(const std::string &playerName, int interval) { if (player->m_deathTime > (kickAfterMinutes * 60000) + 60000) { g_logger().info("Player with name '{}' has logged out due to inactivity after death", player->getName()); g_game().removePlayerUniqueLogin(playerName); - IOLoginData::updateOnlineStatus(player->guid, false); player->disconnect(); return; } @@ -10678,3 +10680,53 @@ const std::unordered_map<uint16_t, std::string> &Game::getHirelingSkills() { const std::unordered_map<uint16_t, std::string> &Game::getHirelingOutfits() { return m_hirelingOutfits; } + +void Game::updatePlayersOnline() const { + // Função a ser executada dentro da transação + auto updateOperation = [this]() -> bool { + const auto &m_players = getPlayers(); + Database &db = Database::getInstance(); + bool changesMade = false; + + // g_metrics().addUpDownCounter("players_online", 1); + // g_metrics().addUpDownCounter("players_online", -1); + + if (m_players.empty()) { + std::string query = "SELECT COUNT(*) AS count FROM players_online;"; + auto result = g_database().storeQuery(query); + int count = result->getNumber<int>("count"); + if (count > 0) { + db.executeQuery("DELETE FROM `players_online`;"); + changesMade = true; + } + } else { + // Insere os jogadores atuais + DBInsert stmt("INSERT IGNORE INTO `players_online` (player_id) VALUES "); + for (const auto &[key, player] : m_players) { + std::ostringstream playerQuery; + playerQuery << "(" << player->getGUID() << ")"; + stmt.addRow(playerQuery.str()); + } + stmt.execute(); + changesMade = true; + + // Remove os jogadores que não estão mais online + std::ostringstream cleanupQuery; + cleanupQuery << "DELETE FROM `players_online` WHERE `player_id` NOT IN ("; + for (const auto &[key, player] : m_players) { + cleanupQuery << player->getGUID() << ","; + } + cleanupQuery.seekp(-1, std::ostringstream::cur); // Remove a última vírgula + cleanupQuery << ");"; + db.executeQuery(cleanupQuery.str()); + } + + return changesMade; + }; + + // Executar a operação dentro de uma transação + const bool success = DBTransaction::executeWithinTransaction(updateOperation); + if (!success) { + g_logger().error("[Game::updatePlayersOnline] Failed to update players online."); + } +} diff --git a/src/game/game.hpp b/src/game/game.hpp index 8e0cd662c6e..792a0dbcf02 100644 --- a/src/game/game.hpp +++ b/src/game/game.hpp @@ -62,6 +62,7 @@ static constexpr int32_t EVENT_LUA_GARBAGE_COLLECTION = 60000 * 10; // 10min static constexpr std::chrono::minutes CACHE_EXPIRATION_TIME { 10 }; // 10min static constexpr std::chrono::minutes HIGHSCORE_CACHE_EXPIRATION_TIME { 10 }; // 10min +static constexpr int32_t UPDATE_PLAYERS_ONLINE_DB = 60000 * 10; // 10min struct QueryHighscoreCacheEntry { std::string query; @@ -129,7 +130,7 @@ class Game { } const std::unique_ptr<TeamFinder> &getTeamFinder(const std::shared_ptr<Player> &player) const { - auto it = teamFinderMap.find(player->getGUID()); + const auto it = teamFinderMap.find(player->getGUID()); if (it != teamFinderMap.end()) { return it->second; } @@ -138,7 +139,7 @@ class Game { } const std::unique_ptr<TeamFinder> &getOrCreateTeamFinder(const std::shared_ptr<Player> &player) { - auto it = teamFinderMap.find(player->getGUID()); + const auto it = teamFinderMap.find(player->getGUID()); if (it != teamFinderMap.end()) { return it->second; } @@ -205,8 +206,8 @@ class Game { itemsClassifications.push_back(itemsClassification); } ItemClassification* getItemsClassification(uint8_t id, bool create) { - auto it = std::find_if(itemsClassifications.begin(), itemsClassifications.end(), [id](ItemClassification* it) { - return it->id == id; + const auto it = std::ranges::find_if(itemsClassifications, [id](const ItemClassification* item) { + return item->id == id; }); if (it != itemsClassifications.end()) { @@ -614,15 +615,15 @@ class Game { FILELOADER_ERRORS loadAppearanceProtobuf(const std::string &file); bool isMagicEffectRegistered(uint16_t type) const { - return std::find(registeredMagicEffects.begin(), registeredMagicEffects.end(), type) != registeredMagicEffects.end(); + return std::ranges::find(registeredMagicEffects, type) != registeredMagicEffects.end(); } bool isDistanceEffectRegistered(uint16_t type) const { - return std::find(registeredDistanceEffects.begin(), registeredDistanceEffects.end(), type) != registeredDistanceEffects.end(); + return std::ranges::find(registeredDistanceEffects, type) != registeredDistanceEffects.end(); } bool isLookTypeRegistered(uint16_t type) const { - return std::find(registeredLookTypes.begin(), registeredLookTypes.end(), type) != registeredLookTypes.end(); + return std::ranges::find(registeredLookTypes, type) != registeredLookTypes.end(); } void setCreateLuaItems(Position position, uint16_t itemId) { @@ -972,6 +973,7 @@ class Game { std::string generateHighscoreOrGetCachedQueryForEntries(const std::string &categoryName, uint32_t page, uint8_t entriesPerPage, uint32_t vocation); std::string generateHighscoreOrGetCachedQueryForOurRank(const std::string &categoryName, uint8_t entriesPerPage, uint32_t playerGUID, uint32_t vocation); + void updatePlayersOnline() const; void teste() const; }; diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 11f467870cb..0fe180976e7 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -129,7 +129,7 @@ class Dispatcher { void stopEvent(uint64_t eventId); - const auto &context() { + const auto &context() const { return dispacherContext; } diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index 2b2ccdf47ec..2c93fa00910 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -77,25 +77,6 @@ uint8_t IOLoginData::getAccountType(uint32_t accountId) { return result->getNumber<uint8_t>("type"); } -void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) { - static phmap::flat_hash_map<uint32_t, bool> updateOnline; - if ((login && updateOnline.find(guid) != updateOnline.end()) || guid <= 0) { - return; - } - - std::ostringstream query; - if (login) { - g_metrics().addUpDownCounter("players_online", 1); - query << "INSERT INTO `players_online` VALUES (" << guid << ')'; - updateOnline[guid] = true; - } else { - g_metrics().addUpDownCounter("players_online", -1); - query << "DELETE FROM `players_online` WHERE `player_id` = " << guid; - updateOnline.erase(guid); - } - Database::getInstance().executeQuery(query.str()); -} - // The boolean "disableIrrelevantInfo" will deactivate the loading of information that is not relevant to the preload, for example, forge, bosstiary, etc. None of this we need to access if the player is offline bool IOLoginData::loadPlayerById(const std::shared_ptr<Player> &player, uint32_t id, bool disableIrrelevantInfo /* = true*/) { Database &db = Database::getInstance(); diff --git a/src/io/iologindata.hpp b/src/io/iologindata.hpp index da18c4f8c01..29eac0c812f 100644 --- a/src/io/iologindata.hpp +++ b/src/io/iologindata.hpp @@ -19,7 +19,6 @@ class IOLoginData { public: static bool gameWorldAuthentication(const std::string &accountDescriptor, const std::string &sessionOrPassword, std::string &characterName, uint32_t &accountId, bool oldProcotol, const uint32_t ip); static uint8_t getAccountType(uint32_t accountId); - static void updateOnlineStatus(uint32_t guid, bool login); static bool loadPlayerById(const std::shared_ptr<Player> &player, uint32_t id, bool disableIrrelevantInfo = true); static bool loadPlayerByName(const std::shared_ptr<Player> &player, const std::string &name, bool disableIrrelevantInfo = true); static bool loadPlayer(const std::shared_ptr<Player> &player, const DBResult_ptr &result, bool disableIrrelevantInfo = false); diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 5e062872348..af5851b19a3 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -3026,14 +3026,12 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { it.second->vip()->notifyStatusChange(player, VipStatus_t::Offline); } } - IOLoginData::updateOnlineStatus(player->getGUID(), false); } else { for (const auto &it : g_game().getPlayers()) { if (!it.second->isAccessPlayer()) { it.second->vip()->notifyStatusChange(player, player->vip()->getStatus()); } } - IOLoginData::updateOnlineStatus(player->getGUID(), true); } pushBoolean(L, true); return 1; diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index 02adbe29235..a3409c0635e 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -944,7 +944,6 @@ void ProtocolGame::parsePacketDead(uint8_t recvbyte) { g_game().removePlayerUniqueLogin(player->getName()); } disconnect(); - IOLoginData::updateOnlineStatus(player->getGUID(), false); return; } From d3718ac9a6df6460451cb0adfab6cfabdec924e7 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Wed, 11 Sep 2024 19:59:21 -0400 Subject: [PATCH 27/34] fix crash --- src/creatures/creature.cpp | 14 ++++--------- src/creatures/players/player.cpp | 8 ++++---- src/game/game.cpp | 35 ++++++++++++++++++++++---------- src/items/tile.cpp | 14 ++++++++----- 4 files changed, 41 insertions(+), 30 deletions(-) diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 02dda3cab2e..485e49cd643 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -1413,11 +1413,9 @@ void Creature::removeCondition(ConditionType_t type) { continue; } - it = conditions.erase(it); - condition->endCondition(getCreature()); - onEndCondition(type); + it = conditions.erase(it); } } @@ -1442,11 +1440,9 @@ void Creature::removeCondition(ConditionType_t conditionType, ConditionId_t cond } } - it = conditions.erase(it); - condition->endCondition(getCreature()); - onEndCondition(conditionType); + it = conditions.erase(it); } } @@ -1512,12 +1508,10 @@ void Creature::executeConditions(uint32_t interval) { const auto &condition = *it; if (!condition->executeCondition(getCreature(), interval)) { ConditionType_t type = condition->getType(); - - it = conditions.erase(it); - condition->endCondition(getCreature()); - onEndCondition(type); + + it = conditions.erase(it); } else { ++it; } diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 351c214a3fd..f86ee7c1ce9 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -3467,10 +3467,10 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh } if (const auto &subContainer = inventoryItem->getContainer()) { - containers.emplace_back(subContainer); + containers.push_back(subContainer); } } else if (const auto &subContainer = inventoryItem->getContainer()) { - containers.emplace_back(subContainer); + containers.push_back(subContainer); } } else if (queryAdd(slotIndex, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { // empty slot index = slotIndex; @@ -3497,7 +3497,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh for (const auto &tmpContainerItem : tmpContainer->getItemList()) { if (const auto &subContainer = tmpContainerItem->getContainer()) { - containers.emplace_back(subContainer); + containers.push_back(subContainer); } } @@ -3523,7 +3523,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh } if (const auto &subContainer = tmpItem->getContainer()) { - containers.emplace_back(subContainer); + containers.push_back(subContainer); } n++; diff --git a/src/game/game.cpp b/src/game/game.cpp index 91697ba5b25..1cbd59289ef 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -4338,19 +4338,28 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st return; } - std::shared_ptr<Thing> thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_FIND_THING); + const auto &thing = internalGetThing(player, pos, stackPos, itemId, STACKPOS_FIND_THING); if (!thing) { return; } - const auto item = thing->getItem(); - const auto tile = map.getTile(item->getPosition()); - const auto houseTile = tile->dynamic_self_cast<HouseTile>(); + const auto &item = thing->getItem(); + if (!item) { + return; + } + + const auto &tile = map.getTile(item->getPosition()); + if (!tile) { + return; + } + + const auto &houseTile = tile->dynamic_self_cast<HouseTile>(); if (!tile->hasFlag(TILESTATE_PROTECTIONZONE) || !houseTile) { player->sendCancelMessage("You may construct this only inside a house."); return; } - const auto house = houseTile->getHouse(); + + const auto &house = houseTile->getHouse(); if (!house) { player->sendCancelMessage("You may construct this only inside a house."); return; @@ -4381,7 +4390,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher().addEvent([this, playerId = player->getID(), listDir] { playerAutoWalk(playerId, listDir); }, "Game::playerAutoWalk"); - std::shared_ptr<Task> task = createPlayerTask( + const std::shared_ptr<Task> task = createPlayerTask( 400, [this, playerId, pos, stackPos, itemId] { playerWrapableItem(playerId, pos, stackPos, itemId); }, "Game::playerWrapableItem" ); player->setNextWalkActionTask(task); @@ -4391,15 +4400,19 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st return; } - std::shared_ptr<Container> container = item->getContainer(); + const auto &container = item->getContainer(); if (container && container->getItemHoldingCount() > 0) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - auto topItem = tile->getTopTopItem(); - bool unwrappable = item->getHoldingPlayer() && item->getID() == ITEM_DECORATION_KIT; - bool blockedUnwrap = topItem && topItem->canReceiveAutoCarpet() && !item->hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID); + const auto &topItem = tile->getTopTopItem(); + if (!topItem) { + return; + } + + const bool &unwrappable = item->getHoldingPlayer() && item->getID() == ITEM_DECORATION_KIT; + const bool &blockedUnwrap = topItem && topItem->canReceiveAutoCarpet() && !item->hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID); if (unwrappable || blockedUnwrap) { player->sendCancelMessage("You can only wrap/unwrap on the floor."); @@ -4407,7 +4420,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st } std::string itemName = item->getName(); - auto unWrapAttribute = item->getCustomAttribute("unWrapId"); + const auto &unWrapAttribute = item->getCustomAttribute("unWrapId"); uint16_t unWrapId = 0; if (unWrapAttribute != nullptr) { unWrapId = static_cast<uint16_t>(unWrapAttribute->getInteger()); diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 76e727ffb46..017d8637d80 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -1044,9 +1044,9 @@ void Tile::addThing(int32_t, const std::shared_ptr<Thing> &thing) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { const auto &oldSplash = *it; if (Item::items[oldSplash->getID()].isSplash()) { + postRemoveNotification(oldSplash, nullptr, 0); removeThing(oldSplash, 1); oldSplash->resetParent(); - postRemoveNotification(oldSplash, nullptr, 0); break; } } @@ -1072,12 +1072,12 @@ void Tile::addThing(int32_t, const std::shared_ptr<Thing> &thing) { if (itemType.isMagicField() && items) { for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { - std::shared_ptr<MagicField> oldField = (*it)->getMagicField(); + const auto &oldField = (*it)->getMagicField(); if (oldField) { if (oldField->isReplaceable()) { + postRemoveNotification(oldField, nullptr, 0); removeThing(oldField, 1); oldField->resetParent(); - postRemoveNotification(oldField, nullptr, 0); break; } @@ -1530,7 +1530,11 @@ void Tile::postAddNotification(const std::shared_ptr<Thing> &thing, const std::s } void Tile::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - auto spectators = Spectators().find<Player>(getPosition(), true); + if (!thing) { + return; + } + + const auto spectators = Spectators().find<Player>(getPosition(), true); if (getThingCount() > 8) { onUpdateTile(spectators.data()); @@ -1541,7 +1545,7 @@ void Tile::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std } // calling movement scripts - std::shared_ptr<Creature> creature = thing->getCreature(); + const auto &creature = thing->getCreature(); if (creature) { g_moveEvents().onCreatureMove(creature, static_self_cast<Tile>(), MOVE_EVENT_STEP_OUT); } else { From 37b4020e713e09f6f9c79c21465cf0ba99ab2f23 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Wed, 11 Sep 2024 20:10:51 -0400 Subject: [PATCH 28/34] remove SIMD condition --- src/creatures/combat/condition.cpp | 12 ++++---- src/creatures/combat/condition.hpp | 48 ------------------------------ 2 files changed, 6 insertions(+), 54 deletions(-) diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 70f80298cfe..1a6a169bf34 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -443,12 +443,12 @@ void ConditionAttributes::addCondition(std::shared_ptr<Creature> creature, const endCondition(creature); // Apply the new one - simd_memcpy(skills, conditionAttrs->skills, std::size(skills)); - simd_memcpy(skillsPercent, conditionAttrs->skillsPercent, std::size(skillsPercent)); - simd_memcpy(stats, conditionAttrs->stats, std::size(stats)); - simd_memcpy(statsPercent, conditionAttrs->statsPercent, std::size(statsPercent)); - simd_memcpy(buffs, conditionAttrs->buffs, std::size(buffs)); - simd_memcpy(buffsPercent, conditionAttrs->buffsPercent, std::size(buffsPercent)); + memcpy(skills, conditionAttrs->skills, sizeof(skills)); + memcpy(skillsPercent, conditionAttrs->skillsPercent, sizeof(skillsPercent)); + memcpy(stats, conditionAttrs->stats, sizeof(stats)); + memcpy(statsPercent, conditionAttrs->statsPercent, sizeof(statsPercent)); + memcpy(buffs, conditionAttrs->buffs, sizeof(buffs)); + memcpy(buffsPercent, conditionAttrs->buffsPercent, sizeof(buffsPercent)); // Using std::array can only increment to the new instead of use memcpy absorbs = conditionAttrs->absorbs; diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index c2432b5e594..9f346e3f9a1 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -65,54 +65,6 @@ class Condition : public SharedObject { bool isPersistent() const; bool isRemovableOnDeath() const; - template <typename T> - static void simd_memcpy(T* dest, const T* src, size_t count) { - size_t remaining = count * sizeof(T); - auto* dst = reinterpret_cast<unsigned char*>(dest); - const auto* source = reinterpret_cast<const unsigned char*>(src); - -#if defined(__AVX2__) - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(source))); - dst += 32; - source += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(source))); - dst += 16; - source += 16; - remaining -= 16; - } - while (remaining >= 8) { - *reinterpret_cast<uint64_t*>(dst) = *reinterpret_cast<const uint64_t*>(source); - dst += 8; - source += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(source); - dst += 4; - source += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(source); - dst += 2; - source += 2; - remaining -= 2; - } - if (remaining == 1) { - *dst = *source; - } -#else - std::memcpy(dest, src, count * sizeof(T)); -#endif - } - protected: uint8_t drainBodyStage = 0; int64_t endTime {}; From 487f7e1e8325f433716bece7647f1a2a4e0ce3ef Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Thu, 12 Sep 2024 22:34:52 -0400 Subject: [PATCH 29/34] new use atomic_queue in getOutputMessage --- src/game/game.cpp | 6 +- src/server/network/connection/connection.cpp | 4 + src/server/network/message/outputmessage.cpp | 17 +-- src/utils/lockfree.hpp | 128 ++++++------------- 4 files changed, 46 insertions(+), 109 deletions(-) diff --git a/src/game/game.cpp b/src/game/game.cpp index 1cbd59289ef..a468fcaa78e 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -538,9 +538,9 @@ void Game::start(ServiceManager* manager) { UPDATE_PLAYERS_ONLINE_DB, [this] { updatePlayersOnline(); }, "Game::updatePlayersOnline" ); - g_dispatcher().cycleEvent( - 5000, [this] { teste(); }, "Calling GC" - ); + // g_dispatcher().cycleEvent( + // 5000, [this] { teste(); }, "Calling GC" + // ); } void Game::teste() const { diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index 4a93b7cc633..b2cd29f454d 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -384,6 +384,10 @@ void Connection::internalSend(const OutputMessage_ptr &outputMessage) { } void Connection::onWriteOperation(const std::error_code &error) { + if (!socket.is_open()) { + return; + } + writeTimer.cancel(); if (error) { diff --git a/src/server/network/message/outputmessage.cpp b/src/server/network/message/outputmessage.cpp index b1882a7c306..67b53a7211d 100644 --- a/src/server/network/message/outputmessage.cpp +++ b/src/server/network/message/outputmessage.cpp @@ -55,20 +55,5 @@ void OutputMessagePool::removeProtocolFromAutosend(const Protocol_ptr &protocol) } OutputMessage_ptr OutputMessagePool::getOutputMessage() { - LockfreePoolingAllocator<OutputMessage, OUTPUTMESSAGE_FREE_LIST_CAPACITY> allocator; - OutputMessage* rawPtr = allocator.allocate(1); - - try { - new (rawPtr) OutputMessage(); - } catch (...) { - allocator.deallocate(rawPtr, 1); - throw; - } - - return { rawPtr, [&allocator](OutputMessage*&ptr) mutable { - if (ptr) { - ptr->~OutputMessage(); - allocator.deallocate(ptr, 1); - } - } }; + return std::allocate_shared<OutputMessage>(LockfreePoolingAllocator<OutputMessage, OUTPUTMESSAGE_FREE_LIST_CAPACITY>()); } diff --git a/src/utils/lockfree.hpp b/src/utils/lockfree.hpp index 28cfec4c824..5a8fc2fd4d5 100644 --- a/src/utils/lockfree.hpp +++ b/src/utils/lockfree.hpp @@ -8,114 +8,62 @@ */ #pragma once +#include <atomic_queue/atomic_queue.h> -#include <atomic> -#include <memory> -#include <vector> -#include <thread> -#include <spdlog/spdlog.h> - -const int TOTAL_THREADS = static_cast<int>(std::thread::hardware_concurrency()); -const size_t LOCAL_CACHE_LIMIT = std::max(35 / TOTAL_THREADS, 5); -constexpr size_t STATIC_PREALLOCATION_SIZE = 100; - -struct StackNode { - void* data; - StackNode* next; -}; - -template <std::size_t TSize, size_t CAPACITY> -class LockfreeFreeList { -public: - LockfreeFreeList() : - head(nullptr) { } +template <typename T, size_t CAPACITY> +struct LockfreeFreeList { + using FreeList = atomic_queue::AtomicQueue2<T*, CAPACITY>; - static LockfreeFreeList &get() { - static LockfreeFreeList instance; - return instance; + static FreeList &get() { + static FreeList freeList; + return freeList; } - bool pop(void*&result) { - StackNode* old_head = head.load(std::memory_order_acquire); - while (old_head != nullptr) { - if (head.compare_exchange_weak(old_head, old_head->next, std::memory_order_acquire)) { - result = old_head->data; - delete old_head; - return true; + static void preallocate(size_t count) { + auto &freeList = get(); + for (size_t i = 0; i < count; ++i) { + T* p = static_cast<T*>(::operator new(sizeof(T), static_cast<std::align_val_t>(alignof(T)))); + if (!freeList.try_push(p)) { + ::operator delete(p, static_cast<std::align_val_t>(alignof(T))); + break; } - - std::this_thread::yield(); } - return false; } - - bool push(void* data) { - auto* new_node = new StackNode { data, nullptr }; - StackNode* old_head = head.load(std::memory_order_relaxed); - do { - new_node->next = old_head; - } while (!head.compare_exchange_weak(old_head, new_node, std::memory_order_release, std::memory_order_relaxed)); - return true; - } - - void preallocate(const size_t numBlocks) { - for (size_t i = 0; i < numBlocks; ++i) { - void* p = operator new(TSize); - push(p); - } - } - -private: - std::atomic<StackNode*> head; }; template <typename T, size_t CAPACITY> -class LockfreePoolingAllocator : public std::allocator<T> { +class LockfreePoolingAllocator { public: - LockfreePoolingAllocator() = default; - - template <typename U, class = std::enable_if_t<!std::is_same_v<U, T>>> - explicit constexpr LockfreePoolingAllocator(const U &) { } using value_type = T; - T* allocate(size_t) const { - ensurePreallocation(); - if (!localCache.empty()) { - void* p = localCache.back(); - localCache.pop_back(); - return static_cast<T*>(p); - } + LockfreePoolingAllocator() = default; - auto &inst = LockfreeFreeList<sizeof(T), CAPACITY>::get(); - void* p; - if (!inst.pop(p)) { - p = operator new(sizeof(T)); + template <typename U> + explicit LockfreePoolingAllocator(const LockfreePoolingAllocator<U, CAPACITY> &) noexcept { } + + T* allocate(size_t n) { + auto &freeList = LockfreeFreeList<T, CAPACITY>::get(); + if (n == 1) { + T* p; + if (freeList.try_pop(p)) { + return p; + } } - return static_cast<T*>(p); + return static_cast<T*>(::operator new(n * sizeof(T), static_cast<std::align_val_t>(alignof(T)))); } - void deallocate(T* p, size_t) const { - if (localCache.size() < LOCAL_CACHE_LIMIT) { - localCache.emplace_back(p); - } else { - auto &inst = LockfreeFreeList<sizeof(T), CAPACITY>::get(); - inst.push(p); + void deallocate(T* p, size_t n) noexcept { + if (n == 1) { + auto &freeList = LockfreeFreeList<T, CAPACITY>::get(); + if (freeList.try_push(p)) { + return; + } } + ::operator delete(p, static_cast<std::align_val_t>(alignof(T))); } -private: - static thread_local std::vector<void*> localCache; - static std::once_flag preallocationFlag; - - static void ensurePreallocation() { - std::call_once(preallocationFlag, []() { - LockfreeFreeList<sizeof(T), CAPACITY>::get().preallocate(STATIC_PREALLOCATION_SIZE); - }); - } + template <typename U> + struct rebind { + using other = LockfreePoolingAllocator<U, CAPACITY>; + }; }; - -template <typename T, size_t CAPACITY> -thread_local std::vector<void*> LockfreePoolingAllocator<T, CAPACITY>::localCache; - -template <typename T, size_t CAPACITY> -std::once_flag LockfreePoolingAllocator<T, CAPACITY>::preallocationFlag; From 738789892438a6a65caa373b2d4e344a219f03b3 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Sat, 14 Sep 2024 14:25:00 -0400 Subject: [PATCH 30/34] restore changes --- src/creatures/creature.cpp | 4 +- src/creatures/creature.hpp | 2 +- src/creatures/npcs/npcs.cpp | 2 +- src/game/scheduling/dispatcher.cpp | 28 +++++++------- src/game/scheduling/dispatcher.hpp | 12 ++++-- src/io/functions/iologindata_load_player.cpp | 6 +-- src/items/containers/container.cpp | 4 +- src/lua/callbacks/events_callbacks.cpp | 4 +- src/lua/creature/movement.cpp | 10 ++--- src/lua/creature/raids.cpp | 6 +-- .../functions/core/game/global_functions.cpp | 6 +-- src/lua/functions/core/libs/kv_functions.cpp | 2 +- .../creatures/monster/loot_functions.cpp | 2 +- .../monster/monster_type_functions.cpp | 10 ++--- .../creatures/npc/npc_type_functions.cpp | 4 +- .../creatures/npc/shop_functions.cpp | 2 +- .../creatures/player/player_functions.cpp | 2 +- .../events/talk_action_functions.cpp | 3 +- src/lua/scripts/lua_environment.cpp | 4 +- src/lua/scripts/lua_environment.hpp | 2 +- src/map/house/house.cpp | 12 +++--- src/map/map.cpp | 4 +- src/server/network/protocol/protocolgame.cpp | 2 +- src/utils/arraylist.hpp | 38 +++++++++---------- src/utils/tools.cpp | 8 ++-- src/utils/vectorset.hpp | 18 ++++----- src/utils/vectorsort.hpp | 14 +++---- 27 files changed, 107 insertions(+), 104 deletions(-) diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 485e49cd643..d1972238bf1 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -457,7 +457,7 @@ void Creature::checkSummonMove(const Position &newPos, bool teleportSummon) { } if (monster && monster->isSummon() && !monster->isFamiliar() && !teleportSummon && checkRemoveDist) { - despawnMonsterList.emplace_back(summon); + despawnMonsterList.push_back(summon); } } @@ -1110,7 +1110,7 @@ void Creature::goToFollowCreature() { // if we can't get anything then let the A* calculate executeOnFollow = false; } else if (dir != DIRECTION_NONE) { - listDir.emplace_back(dir); + listDir.push_back(dir); hasFollowPath = true; } } diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index a7b31ecec5d..188b6369e9d 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -242,7 +242,7 @@ class Creature : virtual public Thing, public SharedObject { icons.reserve(creatureIcons.size()); for (const auto &[_, icon] : creatureIcons) { if (icon.isSet()) { - icons.emplace_back(icon); + icons.push_back(icon); } } return icons; diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index e46e183d893..db0eaa019d8 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -94,7 +94,7 @@ void NpcType::loadShop(const std::shared_ptr<NpcType> &npcType, ShopBlock shopBl const bool &isContainer = iType.isContainer(); if (isContainer) { for (const ShopBlock &child : shopBlock.childShop) { - shopBlock.childShop.emplace_back(child); + shopBlock.childShop.push_back(child); } } } diff --git a/src/game/scheduling/dispatcher.cpp b/src/game/scheduling/dispatcher.cpp index 059420df278..eaedaa86ac5 100644 --- a/src/game/scheduling/dispatcher.cpp +++ b/src/game/scheduling/dispatcher.cpp @@ -104,7 +104,7 @@ void Dispatcher::asyncWait(size_t requestSize, std::function<void(size_t i)> &&f } void Dispatcher::executeEvents(const TaskGroup startGroup) { - for (auto groupId = static_cast<uint8_t>(startGroup); groupId < static_cast<uint8_t>(TaskGroup::Last); ++groupId) { + for (uint_fast8_t groupId = static_cast<uint8_t>(startGroup); groupId < static_cast<uint8_t>(TaskGroup::Last); ++groupId) { auto &tasks = m_tasks[groupId]; if (tasks.empty()) { return; @@ -135,7 +135,7 @@ void Dispatcher::executeScheduledEvents() { if (task->execute() && task->isCycle()) { task->updateTime(); - threadScheduledTasks.emplace(task); + threadScheduledTasks.emplace_back(task); } else { scheduledTasksRef.erase(task->getId()); } @@ -155,8 +155,8 @@ void Dispatcher::executeScheduledEvents() { // Merge only async thread events with main dispatch events void Dispatcher::mergeAsyncEvents() { - constexpr auto start = static_cast<uint8_t>(TaskGroup::GenericParallel); - constexpr auto end = static_cast<uint8_t>(TaskGroup::Last); + constexpr uint8_t start = static_cast<uint8_t>(TaskGroup::GenericParallel); + constexpr uint8_t end = static_cast<uint8_t>(TaskGroup::Last); for (const auto &thread : threads) { std::scoped_lock lock(thread->mutex); @@ -171,19 +171,17 @@ void Dispatcher::mergeAsyncEvents() { // Merge thread events with main dispatch events void Dispatcher::mergeEvents() { - constexpr auto serial = static_cast<uint8_t>(TaskGroup::Serial); + constexpr uint8_t serial = static_cast<uint8_t>(TaskGroup::Serial); for (const auto &thread : threads) { - { - std::scoped_lock lock(thread->mutex); - if (!thread->tasks[serial].empty()) { - m_tasks[serial].insert(m_tasks[serial].end(), make_move_iterator(thread->tasks[serial].begin()), make_move_iterator(thread->tasks[serial].end())); - thread->tasks[serial].clear(); - } + std::scoped_lock lock(thread->mutex); + if (!thread->tasks[serial].empty()) { + m_tasks[serial].insert(m_tasks[serial].end(), make_move_iterator(thread->tasks[serial].begin()), make_move_iterator(thread->tasks[serial].end())); + thread->tasks[serial].clear(); } if (!thread->scheduledTasks.empty()) { - scheduledTasks.insert(thread->scheduledTasks.begin(), thread->scheduledTasks.end()); + scheduledTasks.insert(make_move_iterator(thread->scheduledTasks.begin()), make_move_iterator(thread->scheduledTasks.end())); thread->scheduledTasks.clear(); } } @@ -213,9 +211,11 @@ void Dispatcher::addEvent(std::function<void(void)> &&f, std::string_view contex uint64_t Dispatcher::scheduleEvent(const std::shared_ptr<Task> &task) { const auto &thread = getThreadTask(); + std::scoped_lock lock(thread->mutex); - thread->scheduledTasks.emplace(task); - auto eventId = scheduledTasksRef.emplace(task->getId(), task).first->first; + auto eventId = scheduledTasksRef + .emplace(task->getId(), thread->scheduledTasks.emplace_back(task)) + .first->first; notify(); return eventId; diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 0fe180976e7..4eef4ab0e76 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -92,6 +92,7 @@ class Dispatcher { scheduledTasksRef.reserve(2000); } + // Ensures that we don't accidentally copy it Dispatcher(const Dispatcher &) = delete; Dispatcher operator=(const Dispatcher &) = delete; @@ -196,8 +197,9 @@ class Dispatcher { ThreadPool &threadPool; std::condition_variable signalSchedule; std::atomic_bool hasPendingTasks = false; - std::mutex dummyMutex; + std::mutex dummyMutex; // This is only used for signaling the condition variable and not as an actual lock. + // Thread Events struct ThreadTask { ThreadTask() { for (auto &task : tasks) { @@ -207,14 +209,16 @@ class Dispatcher { } std::array<std::vector<Task>, static_cast<uint8_t>(TaskGroup::Last)> tasks; - phmap::parallel_flat_hash_set_m<std::shared_ptr<Task>> scheduledTasks; + std::vector<std::shared_ptr<Task>> scheduledTasks; std::mutex mutex; }; std::vector<std::unique_ptr<ThreadTask>> threads; + + // Main Events std::array<std::vector<Task>, static_cast<uint8_t>(TaskGroup::Last)> m_tasks; - phmap::btree_multiset<std::shared_ptr<Task>, Task::Compare> scheduledTasks; - phmap::parallel_flat_hash_map_m<uint64_t, std::shared_ptr<Task>> scheduledTasksRef; + phmap::btree_multiset<std::shared_ptr<Task>, Task::Compare> scheduledTasks {}; + phmap::parallel_flat_hash_map_m<uint64_t, std::shared_ptr<Task>> scheduledTasksRef {}; bool asyncWaitDisabled = false; diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index 75053e57372..372921ea716 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -521,10 +521,10 @@ void IOLoginDataLoad::loadPlayerInventoryItems(const std::shared_ptr<Player> &pl openContainersList.emplace_back(cid, itemContainer); } } - for (bool isLootContainer : { true, false }) { - auto checkAttribute = isLootContainer ? ItemAttribute_t::QUICKLOOTCONTAINER : ItemAttribute_t::OBTAINCONTAINER; + for (const bool isLootContainer : { true, false }) { + const auto checkAttribute = isLootContainer ? ItemAttribute_t::QUICKLOOTCONTAINER : ItemAttribute_t::OBTAINCONTAINER; if (item->hasAttribute(checkAttribute)) { - auto flags = item->getAttribute<uint32_t>(checkAttribute); + const auto flags = item->getAttribute<uint32_t>(checkAttribute); for (uint8_t category = OBJECTCATEGORY_FIRST; category <= OBJECTCATEGORY_LAST; category++) { if (hasBitSet(1 << category, flags)) { diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index 7d36730d060..b87c06eefa8 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -133,8 +133,8 @@ StashContainerList Container::getStowableItems() const { for (const auto &item : itemlist) { if (item->getContainer() != nullptr) { auto subContainer = item->getContainer()->getStowableItems(); - for (const auto &subContItem : subContainer) { - std::shared_ptr<Item> containerItem = subContItem.first; + for (const auto &key : subContainer | std::views::keys) { + std::shared_ptr<Item> containerItem = key; toReturnList.emplace_back(containerItem, static_cast<uint32_t>(containerItem->getItemCount())); } } else if (item->isItemStorable()) { diff --git a/src/lua/callbacks/events_callbacks.cpp b/src/lua/callbacks/events_callbacks.cpp index 51748298781..d8ab997d416 100644 --- a/src/lua/callbacks/events_callbacks.cpp +++ b/src/lua/callbacks/events_callbacks.cpp @@ -29,7 +29,7 @@ EventsCallbacks &EventsCallbacks::getInstance() { } void EventsCallbacks::addCallback(const std::shared_ptr<EventCallback> &callback) { - m_callbacks.emplace_back(callback); + m_callbacks.push_back(callback); } std::vector<std::shared_ptr<EventCallback>> EventsCallbacks::getCallbacks() const { @@ -43,7 +43,7 @@ std::vector<std::shared_ptr<EventCallback>> EventsCallbacks::getCallbacksByType( continue; } - eventCallbacks.emplace_back(callback); + eventCallbacks.push_back(callback); } return eventCallbacks; diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index d0417d709f4..47cf65a28c4 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -123,10 +123,10 @@ bool MoveEvents::registerLuaEvent(const std::shared_ptr<MoveEvent> &moveEvent) { } bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, int32_t id, std::map<int32_t, MoveEventList> &moveListMap) const { - auto it = moveListMap.find(id); + const auto it = moveListMap.find(id); if (it == moveListMap.end()) { MoveEventList moveEventList; - moveEventList.moveEvent[moveEvent->getEventType()].emplace_back(moveEvent); + moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent); moveListMap[id] = moveEventList; return true; } else { @@ -142,7 +142,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, int3 return false; } } - moveEventList.emplace_back(moveEvent); + moveEventList.push_back(moveEvent); return true; } } @@ -245,7 +245,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, cons auto it = moveListMap.find(position); if (it == moveListMap.end()) { MoveEventList moveEventList; - moveEventList.moveEvent[moveEvent->getEventType()].emplace_back(moveEvent); + moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent); moveListMap[position] = moveEventList; return true; } else { @@ -260,7 +260,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, cons return false; } - moveEventList.emplace_back(moveEvent); + moveEventList.push_back(moveEvent); return true; } } diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index 65b21fea7b2..c5c0081a96f 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -83,7 +83,7 @@ bool Raids::loadFromXml() { auto newRaid = std::make_shared<Raid>(name, interval, margin, repeat); if (newRaid->loadFromXml(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/" + file)) { - raidList.emplace_back(newRaid); + raidList.push_back(newRaid); } else { g_logger().error("{} - Failed to load raid: {}", __FUNCTION__, name); } @@ -199,7 +199,7 @@ bool Raid::loadFromXml(const std::string &filename) { } if (event->configureRaidEvent(eventNode)) { - raidEvents.emplace_back(event); + raidEvents.push_back(event); } else { g_logger().error("{} - " "In file: {}, eventNode: {}", @@ -208,7 +208,7 @@ bool Raid::loadFromXml(const std::string &filename) { } // sort by delay time - std::sort(raidEvents.begin(), raidEvents.end(), [](const std::shared_ptr<RaidEvent> &lhs, const std::shared_ptr<RaidEvent> &rhs) { + std::ranges::sort(raidEvents, [](const std::shared_ptr<RaidEvent> &lhs, const std::shared_ptr<RaidEvent> &rhs) { return lhs->getDelay() < rhs->getDelay(); }); diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 840fb71a778..756883a9006 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -586,7 +586,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaData_t type = getNumber<LuaData_t>(L, -1); if (type != LuaData_t::Unknown && type <= LuaData_t::Npc) { - indexes.emplace_back(i, type); + indexes.push_back({ i, type }); } lua_pop(globalState, 2); } @@ -652,7 +652,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaTimerEventDesc eventDesc; for (int i = 0; i < parameters - 2; ++i) { // -2 because addEvent needs at least two parameters - eventDesc.parameters.emplace_back(luaL_ref(globalState, LUA_REGISTRYINDEX)); + eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX)); } uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2)); @@ -858,7 +858,7 @@ bool GlobalFunctions::getArea(lua_State* L, std::list<uint32_t> &list, uint32_t if (!isNumber(L, -1)) { return false; } - list.emplace_back(getNumber<uint32_t>(L, -1)); + list.push_back(getNumber<uint32_t>(L, -1)); lua_pop(L, 1); } diff --git a/src/lua/functions/core/libs/kv_functions.cpp b/src/lua/functions/core/libs/kv_functions.cpp index 0e6200a5858..f145c2c0b5d 100644 --- a/src/lua/functions/core/libs/kv_functions.cpp +++ b/src/lua/functions/core/libs/kv_functions.cpp @@ -138,7 +138,7 @@ std::optional<ValueWrapper> KVFunctions::getValueWrapper(lua_State* L) { g_logger().warn("[{}] invalid param type", __FUNCTION__); return std::nullopt; } - array.emplace_back(value.value()); + array.push_back(value.value()); lua_pop(L, 1); } return ValueWrapper(array); diff --git a/src/lua/functions/creatures/monster/loot_functions.cpp b/src/lua/functions/creatures/monster/loot_functions.cpp index c3beb74d638..47e0d8778e3 100644 --- a/src/lua/functions/creatures/monster/loot_functions.cpp +++ b/src/lua/functions/creatures/monster/loot_functions.cpp @@ -261,7 +261,7 @@ int LootFunctions::luaLootAddChildLoot(lua_State* L) { if (loot) { const auto childLoot = getUserdata<Loot>(L, 2); if (childLoot) { - loot->lootBlock.childLoot.emplace_back(childLoot->lootBlock); + loot->lootBlock.childLoot.push_back(childLoot->lootBlock); pushBoolean(L, true); } else { pushBoolean(L, false); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 005f65c877f..7aa8ae926ec 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -819,7 +819,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { - monsterType->info.attackSpells.emplace_back(std::move(sb)); + monsterType->info.attackSpells.push_back(std::move(sb)); } else { g_logger().warn("Monster: {}, cant load spell: {}", monsterType->name, spell->name); } @@ -881,7 +881,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { - monsterType->info.defenseSpells.emplace_back(std::move(sb)); + monsterType->info.defenseSpells.push_back(std::move(sb)); } else { g_logger().warn("Monster: {}, Cant load spell: {}", monsterType->name, spell->name); } @@ -958,7 +958,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddVoice(lua_State* L) { monsterType->info.yellSpeedTicks = getNumber<uint32_t>(L, 3); monsterType->info.yellChance = getNumber<uint32_t>(L, 4); voice.yellText = getBoolean(L, 5); - monsterType->info.voiceVector.emplace_back(voice); + monsterType->info.voiceVector.push_back(voice); pushBoolean(L, true); } else { lua_pushnil(L); @@ -1109,7 +1109,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSummon(lua_State* L) { summon.speed = getNumber<int32_t>(L, 3); summon.count = getNumber<int32_t>(L, 5, 1); summon.chance = getNumber<int32_t>(L, 4); - monsterType->info.summons.emplace_back(summon); + monsterType->info.summons.push_back(summon); pushBoolean(L, true); } else { lua_pushnil(L); @@ -1654,7 +1654,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddSound(lua_State* L) { return 1; } - monsterType->info.soundVector.emplace_back(getNumber<SoundEffect_t>(L, 2)); + monsterType->info.soundVector.push_back(getNumber<SoundEffect_t>(L, 2)); pushBoolean(L, true); return 1; } diff --git a/src/lua/functions/creatures/npc/npc_type_functions.cpp b/src/lua/functions/creatures/npc/npc_type_functions.cpp index f52e8462232..ef79b671a34 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.cpp @@ -210,7 +210,7 @@ int NpcTypeFunctions::luaNpcTypeAddVoice(lua_State* L) { npcType->info.yellSpeedTicks = getNumber<uint32_t>(L, 3); npcType->info.yellChance = getNumber<uint32_t>(L, 4); voice.yellText = getBoolean(L, 5); - npcType->info.voiceVector.emplace_back(voice); + npcType->info.voiceVector.push_back(voice); pushBoolean(L, true); } else { lua_pushnil(L); @@ -546,7 +546,7 @@ int NpcTypeFunctions::luaNpcTypeAddSound(lua_State* L) { return 1; } - npcType->info.soundVector.emplace_back(getNumber<SoundEffect_t>(L, 2)); + npcType->info.soundVector.push_back(getNumber<SoundEffect_t>(L, 2)); pushBoolean(L, true); return 1; } diff --git a/src/lua/functions/creatures/npc/shop_functions.cpp b/src/lua/functions/creatures/npc/shop_functions.cpp index 5fda97ccbd9..122e249a8db 100644 --- a/src/lua/functions/creatures/npc/shop_functions.cpp +++ b/src/lua/functions/creatures/npc/shop_functions.cpp @@ -139,7 +139,7 @@ int ShopFunctions::luaShopSetStorageValue(lua_State* L) { int ShopFunctions::luaShopAddChildShop(lua_State* L) { // shop:addChildShop(shop) if (const auto &shop = getUserdataShared<Shop>(L, 1)) { - shop->shopBlock.childShop.emplace_back(getUserdataShared<Shop>(L, 2)->shopBlock); + shop->shopBlock.childShop.push_back(getUserdataShared<Shop>(L, 2)->shopBlock); } else { lua_pushnil(L); } diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index af5851b19a3..1e4d8a660cb 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -3095,7 +3095,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { spells.reserve(30); for (auto &[key, spell] : g_spells().getInstantSpells()) { if (spell->canCast(player)) { - spells.emplace_back(spell); + spells.push_back(spell); } } diff --git a/src/lua/functions/events/talk_action_functions.cpp b/src/lua/functions/events/talk_action_functions.cpp index 6ffb3fef652..432b948e4ba 100644 --- a/src/lua/functions/events/talk_action_functions.cpp +++ b/src/lua/functions/events/talk_action_functions.cpp @@ -19,9 +19,8 @@ int TalkActionFunctions::luaCreateTalkAction(lua_State* L) { // TalkAction(words) or TalkAction(word1, word2, word3) std::vector<std::string> wordsVector; - wordsVector.reserve(500); for (int i = 2; i <= lua_gettop(L); i++) { - wordsVector.emplace_back(getString(L, i)); + wordsVector.push_back(getString(L, i)); } const auto talkactionSharedPtr = std::make_shared<TalkAction>(getScriptEnv()->getScriptInterface()); diff --git a/src/lua/scripts/lua_environment.cpp b/src/lua/scripts/lua_environment.cpp index 70b0d5136db..0a41a175f7f 100644 --- a/src/lua/scripts/lua_environment.cpp +++ b/src/lua/scripts/lua_environment.cpp @@ -106,7 +106,7 @@ std::shared_ptr<Combat> LuaEnvironment::getCombatObject(uint32_t id) const { std::shared_ptr<Combat> LuaEnvironment::createCombatObject(LuaScriptInterface* interface) { auto combat = std::make_shared<Combat>(); combatMap[++lastCombatId] = combat; - combatIdMap[interface].emplace_back(lastCombatId); + combatIdMap[interface].push_back(lastCombatId); return combat; } @@ -130,7 +130,7 @@ const std::unique_ptr<AreaCombat> &LuaEnvironment::getAreaObject(uint32_t id) co uint32_t LuaEnvironment::createAreaObject(LuaScriptInterface* interface) { areaMap[++lastAreaId] = std::make_unique<AreaCombat>(); - areaIdMap[interface].emplace_back(lastAreaId); + areaIdMap[interface].push_back(lastAreaId); return lastAreaId; } diff --git a/src/lua/scripts/lua_environment.hpp b/src/lua/scripts/lua_environment.hpp index 7c5b0e5edea..e7751bb4969 100644 --- a/src/lua/scripts/lua_environment.hpp +++ b/src/lua/scripts/lua_environment.hpp @@ -54,7 +54,7 @@ class LuaEnvironment final : public LuaScriptInterface { auto weapon = std::make_shared<T>(interface); const auto weaponId = ++lastWeaponId; weaponMap[weaponId] = weapon; - weaponIdMap[interface].emplace_back(weaponId); + weaponIdMap[interface].push_back(weaponId); return weapon; } diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index 482e89a0f9d..a6771313e46 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -24,7 +24,7 @@ House::House(uint32_t houseId) : void House::addTile(const std::shared_ptr<HouseTile> &tile) { tile->setFlag(TILESTATE_PROTECTIONZONE); - houseTiles.emplace_back(tile); + houseTiles.push_back(tile); updateDoorDescription(); } @@ -297,7 +297,7 @@ bool House::transferToDepot(const std::shared_ptr<Player> &player, const std::sh if (item->isWrapable()) { handleWrapableItem(moveItemList, item, player, tile); } else if (item->isPickupable()) { - moveItemList.emplace_back(item); + moveItemList.push_back(item); } else { handleContainer(moveItemList, item); } @@ -376,13 +376,13 @@ void House::handleWrapableItem(ItemList &moveItemList, const std::shared_ptr<Ite return; } - moveItemList.emplace_back(newItem); + moveItemList.push_back(newItem); } void House::handleContainer(ItemList &moveItemList, const std::shared_ptr<Item> &item) const { if (const auto &container = item->getContainer()) { for (const auto &containerItem : container->getItemList()) { - moveItemList.emplace_back(containerItem); + moveItemList.push_back(containerItem); } } } @@ -405,7 +405,7 @@ bool House::getAccessList(uint32_t listId, std::string &list) const { } void House::addDoor(const std::shared_ptr<Door> &door) { - doorList.emplace_back(door); + doorList.push_back(door); door->setHouse(static_self_cast<House>()); updateDoorDescription(); } @@ -418,7 +418,7 @@ void House::removeDoor(const std::shared_ptr<Door> &door) { } void House::addBed(const std::shared_ptr<BedItem> &bed) { - bedsList.emplace_back(bed); + bedsList.push_back(bed); bed->setHouse(static_self_cast<House>()); } diff --git a/src/map/map.cpp b/src/map/map.cpp index 5e5c2fa9a94..3249e137704 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -373,9 +373,9 @@ void Map::moveCreature(const std::shared_ptr<Creature> &creature, const std::sha oldStackPosVector.reserve(playersSpectators.size()); for (const auto &spec : playersSpectators) { if (spec->canSeeCreature(creature)) { - oldStackPosVector.emplace_back(oldTile->getClientIndexOfCreature(spec->getPlayer(), creature)); + oldStackPosVector.push_back(oldTile->getClientIndexOfCreature(spec->getPlayer(), creature)); } else { - oldStackPosVector.emplace_back(-1); + oldStackPosVector.push_back(-1); } } diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index a3409c0635e..90ddcad340e 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -1875,7 +1875,7 @@ void ProtocolGame::parseQuickLootBlackWhitelist(NetworkMessage &msg) { listedItems.reserve(size); for (int i = 0; i < size; i++) { - listedItems.emplace_back(msg.get<uint16_t>()); + listedItems.push_back(msg.get<uint16_t>()); } g_game().playerQuickLootBlackWhitelist(player->getID(), filter, listedItems); diff --git a/src/utils/arraylist.hpp b/src/utils/arraylist.hpp index 2c9a6a6aac3..da507e68480 100644 --- a/src/utils/arraylist.hpp +++ b/src/utils/arraylist.hpp @@ -27,17 +27,17 @@ namespace stdext { reserve(reserveSize); } - arraylist(std::initializer_list<T> Ilist) { - backContainer.assign(Ilist); + explicit arraylist(std::initializer_list<T> _Ilist) { + backContainer.assign(_Ilist); } - arraylist &operator=(std::initializer_list<T> Ilist) { - backContainer.assign(Ilist); + arraylist &operator=(std::initializer_list<T> _Ilist) { + backContainer.assign(_Ilist); return *this; } - void assign(std::initializer_list<T> Ilist) { - backContainer.assign(Ilist); + void assign(std::initializer_list<T> _Ilist) { + backContainer.assign(_Ilist); } bool contains(const T &v) { @@ -91,31 +91,31 @@ namespace stdext { void push_front(const T &v) { needUpdate = true; - frontContainer.emplace_back(v); + frontContainer.push_back(v); } - void push_front(T &&Val) { + void push_front(T &&_Val) { needUpdate = true; - frontContainer.emplace_back(std::move(Val)); + frontContainer.push_back(std::move(_Val)); } - template <class... Valty> - decltype(auto) emplace_front(Valty &&... v) { + template <class... _Valty> + decltype(auto) emplace_front(_Valty &&... v) { needUpdate = true; - return frontContainer.emplace_back(std::forward<Valty>(v)...); + return frontContainer.emplace_back(std::forward<_Valty>(v)...); } - void emplace_back(const T &v) { - backContainer.emplace_back(v); + void push_back(const T &v) { + backContainer.push_back(v); } - void emplace_back(T &&Val) { - backContainer.emplace_back(std::move(Val)); + void push_back(T &&_Val) { + backContainer.push_back(std::move(_Val)); } - template <class... Valty> - decltype(auto) emplace_back(Valty &&... v) { - return backContainer.emplace_back(std::forward<Valty>(v)...); + template <class... _Valty> + decltype(auto) emplace_back(_Valty &&... v) { + return backContainer.emplace_back(std::forward<_Valty>(v)...); } bool empty() const noexcept { diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index 7ee9a765246..1616443e017 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -373,18 +373,18 @@ StringVector explodeString(const std::string &inString, const std::string &separ std::string::size_type start = 0, end = 0; while (--limit != -1 && (end = inString.find(separator, start)) != std::string::npos) { - returnVector.emplace_back(inString.substr(start, end - start)); + returnVector.push_back(inString.substr(start, end - start)); start = end + separator.size(); } - returnVector.emplace_back(inString.substr(start)); + returnVector.push_back(inString.substr(start)); return returnVector; } IntegerVector vectorAtoi(const StringVector &stringVector) { IntegerVector returnVector; for (const auto &string : stringVector) { - returnVector.emplace_back(std::stoi(string)); + returnVector.push_back(std::stoi(string)); } return returnVector; } @@ -1909,7 +1909,7 @@ std::vector<std::string> split(const std::string &str, char delimiter /* = ','*/ while (std::getline(tokenStream, token, delimiter)) { auto trimedToken = token; trimString(trimedToken); - tokens.emplace_back(trimedToken); + tokens.push_back(trimedToken); } return tokens; } diff --git a/src/utils/vectorset.hpp b/src/utils/vectorset.hpp index 9ca56583fba..0f81ce3960d 100644 --- a/src/utils/vectorset.hpp +++ b/src/utils/vectorset.hpp @@ -48,8 +48,8 @@ namespace stdext { return container.push_back(v); } - template <class... Valty> - auto emplace(Valty &&... v) { + template <class... _Valty> + auto emplace(_Valty &&... v) { needUpdate = true; return container.emplace_back(v...); } @@ -64,20 +64,20 @@ namespace stdext { return container.insert(container.end(), list.begin(), list.end()); } - constexpr auto insert(typename std::vector<T>::const_iterator Where, const T &Val) { + constexpr auto insert(std::vector<T>::const_iterator _Where, const T &_Val) { needUpdate = true; - return container.insert(Where, Val); + return container.insert(_Where, _Val); } - constexpr auto insert(typename std::vector<T>::const_iterator Where, T &&Val) { + constexpr auto insert(std::vector<T>::const_iterator _Where, T &&_Val) { needUpdate = true; - return container.insert(Where, std::move(Val)); + return container.insert(_Where, std::move(_Val)); } - template <std::forward_iterator Iter> - constexpr auto insert(typename std::vector<T>::const_iterator Where, Iter First, Iter Last) { + template <std::forward_iterator _Iter> + constexpr auto insert(std::vector<T>::const_iterator _Where, _Iter _First, _Iter _Last) { needUpdate = true; - return container.insert(Where, First, Last); + return container.insert(_Where, _First, _Last); } bool empty() const noexcept { diff --git a/src/utils/vectorsort.hpp b/src/utils/vectorsort.hpp index dfe21d6b076..0a3618b963f 100644 --- a/src/utils/vectorsort.hpp +++ b/src/utils/vectorsort.hpp @@ -68,14 +68,14 @@ namespace stdext { return container.back(); } - void emplace_back(const T &v) { + void push_back(const T &v) { needUpdate = true; - container.emplace_back(v); + container.push_back(v); } - void emplace_back(T &&Val) { + void push_back(T &&_Val) { needUpdate = true; - container.emplace_back(std::move(Val)); + container.push_back(std::move(_Val)); } // Copy all content list to this @@ -106,10 +106,10 @@ namespace stdext { return res; } - template <class... Valty> - decltype(auto) emplace_back(Valty &&... v) { + template <class... _Valty> + decltype(auto) emplace_back(_Valty &&... v) { needUpdate = true; - return container.emplace_back(std::forward<Valty>(v)...); + return container.emplace_back(std::forward<_Valty>(v)...); } void partial_sort(size_t begin, size_t end = 0) { From baa555ed20b2387fc204e3780938c5079a11e319 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Sat, 14 Sep 2024 17:50:51 -0400 Subject: [PATCH 31/34] up --- src/creatures/creature.cpp | 22 +-- src/creatures/players/player.cpp | 41 ++--- src/creatures/players/player.hpp | 2 +- src/game/game.cpp | 39 ++--- src/game/movement/teleport.cpp | 2 +- src/game/movement/teleport.hpp | 2 +- src/items/containers/container.cpp | 20 +-- src/items/containers/container.hpp | 2 +- src/items/containers/mailbox/mailbox.cpp | 2 +- src/items/containers/mailbox/mailbox.hpp | 2 +- src/items/cylinder.hpp | 4 +- src/items/tile.cpp | 6 +- src/items/tile.hpp | 2 +- src/items/trashholder.cpp | 2 +- src/items/trashholder.hpp | 2 +- src/map/house/housetile.cpp | 4 +- src/map/house/housetile.hpp | 2 +- src/map/map.cpp | 2 +- src/server/network/message/networkmessage.cpp | 154 +---------------- src/server/network/message/networkmessage.hpp | 98 +---------- src/server/network/message/outputmessage.hpp | 125 +------------- src/server/network/protocol/protocol.cpp | 158 +++++------------- 22 files changed, 115 insertions(+), 578 deletions(-) diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index d1972238bf1..ab3735cc8c5 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -485,7 +485,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s stopEventWalk(); } - const bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS, __FUNCTION__); + bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS, __FUNCTION__); checkSummonMove(newPos, configTeleportSummons); if (isLostSummon()) { handleLostSummon(configTeleportSummons); @@ -511,14 +511,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s if (oldPos.y > newPos.y) { // north // shift y south for (int32_t y = mapWalkHeight - 1; --y >= 0;) { -// Copiando linhas usando SIMD -#if defined(__AVX2__) - _mm256_storeu_si256(reinterpret_cast<__m256i*>(localMapCache[y + 1]), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(localMapCache[y]))); -#elif defined(__SSE2__) - _mm_storeu_si128(reinterpret_cast<__m128i*>(localMapCache[y + 1]), _mm_loadu_si128(reinterpret_cast<const __m128i*>(localMapCache[y]))); -#else memcpy(localMapCache[y + 1], localMapCache[y], sizeof(localMapCache[y])); -#endif } // update 0 @@ -529,14 +522,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s } else if (oldPos.y < newPos.y) { // south // shift y north for (int32_t y = 0; y <= mapWalkHeight - 2; ++y) { -// Copiando linhas usando SIMD -#if defined(__AVX2__) - _mm256_storeu_si256(reinterpret_cast<__m256i*>(localMapCache[y]), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(localMapCache[y + 1]))); -#elif defined(__SSE2__) - _mm_storeu_si128(reinterpret_cast<__m128i*>(localMapCache[y]), _mm_loadu_si128(reinterpret_cast<const __m128i*>(localMapCache[y + 1]))); -#else memcpy(localMapCache[y], localMapCache[y + 1], sizeof(localMapCache[y])); -#endif } // update mapWalkHeight - 1 @@ -550,7 +536,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s // shift y west int32_t starty = 0; int32_t endy = mapWalkHeight - 1; - const int32_t dy = Position::getDistanceY(oldPos, newPos); + int32_t dy = Position::getDistanceY(oldPos, newPos); if (dy < 0) { endy += dy; @@ -573,7 +559,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s // shift y east int32_t starty = 0; int32_t endy = mapWalkHeight - 1; - const int32_t dy = Position::getDistanceY(oldPos, newPos); + int32_t dy = Position::getDistanceY(oldPos, newPos); if (dy < 0) { endy += dy; @@ -629,7 +615,7 @@ void Creature::onCreatureMove(const std::shared_ptr<Creature> &creature, const s onCreatureDisappear(attackedCreature, false); } else { if (hasExtraSwing()) { - // our target is moving, let's see if we can get a hit + // our target is moving lets see if we can get in hit g_dispatcher().addEvent([creatureId = getID()] { g_game().checkCreatureAttack(creatureId); }, "Game::checkCreatureAttack"); } diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index f86ee7c1ce9..b9347bb1043 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -3431,16 +3431,16 @@ ReturnValue Player::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t co return RETURNVALUE_NOERROR; } -std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) { +std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) { if (index == 0 /*drop to capacity window*/ || index == INDEX_WHEREEVER) { - *destItem = nullptr; + destItem = nullptr; const auto &item = thing->getItem(); - if (item == nullptr) { + if (!item) { return getPlayer(); } - const bool autoStack = !((flags & FLAG_IGNOREAUTOSTACK) == FLAG_IGNOREAUTOSTACK); + const bool autoStack = !(flags & FLAG_IGNOREAUTOSTACK); const bool isStackable = item->isStackable(); std::vector<std::shared_ptr<Container>> containers; @@ -3448,11 +3448,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh for (uint32_t slotIndex = CONST_SLOT_FIRST; slotIndex <= CONST_SLOT_AMMO; ++slotIndex) { const auto &inventoryItem = inventory[slotIndex]; if (inventoryItem) { - if (inventoryItem == tradeItem) { - continue; - } - - if (inventoryItem == item) { + if (inventoryItem == tradeItem || inventoryItem == item) { continue; } @@ -3461,7 +3457,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh if (queryAdd(slotIndex, item, item->getItemCount(), 0) == RETURNVALUE_NOERROR) { if (inventoryItem->equals(item) && inventoryItem->getItemCount() < inventoryItem->getStackSize()) { index = slotIndex; - *destItem = inventoryItem; + destItem = inventoryItem; return getPlayer(); } } @@ -3474,7 +3470,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh } } else if (queryAdd(slotIndex, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { // empty slot index = slotIndex; - *destItem = nullptr; + destItem = nullptr; return getPlayer(); } } @@ -3482,13 +3478,17 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh size_t i = 0; while (i < containers.size()) { const auto &tmpContainer = containers[i++]; + if (!tmpContainer) { + continue; // Verificar se tmpContainer é válido + } + if (!autoStack || !isStackable) { // we need to find first empty container as fast as we can for non-stackable items uint32_t n = tmpContainer->capacity() - tmpContainer->size(); while (n) { if (tmpContainer->queryAdd(tmpContainer->capacity() - n, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { index = tmpContainer->capacity() - n; - *destItem = nullptr; + destItem = nullptr; return tmpContainer; } @@ -3507,18 +3507,13 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh uint32_t n = 0; for (const auto &tmpItem : tmpContainer->getItemList()) { - if (tmpItem == tradeItem) { - continue; - } - - if (tmpItem == item) { + if (tmpItem == tradeItem || tmpItem == item) { continue; } - // try find an already existing item to stack with if (tmpItem->equals(item) && tmpItem->getItemCount() < tmpItem->getStackSize()) { index = n; - *destItem = tmpItem; + destItem = tmpItem; return tmpContainer; } @@ -3531,7 +3526,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh if (n < tmpContainer->capacity() && tmpContainer->queryAdd(n, item, item->getItemCount(), flags) == RETURNVALUE_NOERROR) { index = n; - *destItem = nullptr; + destItem = nullptr; return tmpContainer; } } @@ -3541,11 +3536,11 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh const auto &destThing = getThing(index); if (destThing) { - *destItem = destThing->getItem(); + destItem = destThing->getItem(); } const auto &item = thing->getItem(); - const bool movingAmmoToQuiver = item && *destItem && (*destItem)->isQuiver() && item->isAmmo(); + const bool movingAmmoToQuiver = item && destItem && (destItem)->isQuiver() && item->isAmmo(); // force shield any slot right to player cylinder if (index == CONST_SLOT_RIGHT && !movingAmmoToQuiver) { return getPlayer(); @@ -3554,7 +3549,7 @@ std::shared_ptr<Cylinder> Player::queryDestination(int32_t &index, const std::sh const auto &subCylinder = std::dynamic_pointer_cast<Cylinder>(destThing); if (subCylinder) { index = INDEX_WHEREEVER; - *destItem = nullptr; + destItem = nullptr; return subCylinder; } else { return getPlayer(); diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 866f639494f..dbad2c50484 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -2697,7 +2697,7 @@ class Player final : public Creature, public Cylinder, public Bankable { ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing>) override { } void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/game/game.cpp b/src/game/game.cpp index a468fcaa78e..a3725c892c3 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -1567,7 +1567,7 @@ ReturnValue Game::internalMoveCreature(const std::shared_ptr<Creature> &creature std::shared_ptr<Tile> fromCylinder = nullptr; uint32_t n = 0; - while ((subCylinder = toCylinder->queryDestination(index, creature, &toItem, flags)->getTile()) != toCylinder) { + while ((subCylinder = toCylinder->queryDestination(index, creature, toItem, flags)->getTile()) != toCylinder) { map.moveCreature(creature, subCylinder); if (creature->getParent() != subCylinder) { @@ -1970,7 +1970,7 @@ ReturnValue Game::internalMoveItem(std::shared_ptr<Cylinder> fromCylinder, std:: std::shared_ptr<Cylinder> subCylinder; int floorN = 0; - while ((subCylinder = toCylinder->queryDestination(index, item, &toItem, flags)) != toCylinder) { + while ((subCylinder = toCylinder->queryDestination(index, item, toItem, flags)) != toCylinder) { toCylinder = subCylinder; flags = 0; @@ -2219,7 +2219,7 @@ ReturnValue Game::internalAddItem(std::shared_ptr<Cylinder> toCylinder, const st std::shared_ptr<Cylinder> destCylinder = toCylinder; std::shared_ptr<Item> toItem = nullptr; - toCylinder = toCylinder->queryDestination(index, item, &toItem, flags); + toCylinder = toCylinder->queryDestination(index, item, toItem, flags); // check if we can add this item ReturnValue ret = toCylinder->queryAdd(index, item, item->getItemCount(), flags); @@ -4343,23 +4343,14 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st return; } - const auto &item = thing->getItem(); - if (!item) { - return; - } - - const auto &tile = map.getTile(item->getPosition()); - if (!tile) { - return; - } - - const auto &houseTile = tile->dynamic_self_cast<HouseTile>(); + const auto item = thing->getItem(); + const auto tile = map.getTile(item->getPosition()); + const auto houseTile = tile->dynamic_self_cast<HouseTile>(); if (!tile->hasFlag(TILESTATE_PROTECTIONZONE) || !houseTile) { player->sendCancelMessage("You may construct this only inside a house."); return; } - - const auto &house = houseTile->getHouse(); + const auto house = houseTile->getHouse(); if (!house) { player->sendCancelMessage("You may construct this only inside a house."); return; @@ -4390,7 +4381,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st if (player->getPathTo(pos, listDir, 0, 1, true, true)) { g_dispatcher().addEvent([this, playerId = player->getID(), listDir] { playerAutoWalk(playerId, listDir); }, "Game::playerAutoWalk"); - const std::shared_ptr<Task> task = createPlayerTask( + std::shared_ptr<Task> task = createPlayerTask( 400, [this, playerId, pos, stackPos, itemId] { playerWrapableItem(playerId, pos, stackPos, itemId); }, "Game::playerWrapableItem" ); player->setNextWalkActionTask(task); @@ -4400,19 +4391,15 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st return; } - const auto &container = item->getContainer(); + std::shared_ptr<Container> container = item->getContainer(); if (container && container->getItemHoldingCount() > 0) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } - const auto &topItem = tile->getTopTopItem(); - if (!topItem) { - return; - } - - const bool &unwrappable = item->getHoldingPlayer() && item->getID() == ITEM_DECORATION_KIT; - const bool &blockedUnwrap = topItem && topItem->canReceiveAutoCarpet() && !item->hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID); + auto topItem = tile->getTopTopItem(); + bool unwrappable = item->getHoldingPlayer() && item->getID() == ITEM_DECORATION_KIT; + bool blockedUnwrap = topItem && topItem->canReceiveAutoCarpet() && !item->hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID); if (unwrappable || blockedUnwrap) { player->sendCancelMessage("You can only wrap/unwrap on the floor."); @@ -4420,7 +4407,7 @@ void Game::playerWrapableItem(uint32_t playerId, const Position &pos, uint8_t st } std::string itemName = item->getName(); - const auto &unWrapAttribute = item->getCustomAttribute("unWrapId"); + auto unWrapAttribute = item->getCustomAttribute("unWrapId"); uint16_t unWrapId = 0; if (unWrapAttribute != nullptr) { unWrapId = static_cast<uint16_t>(unWrapAttribute->getInteger()); diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index 62cae24f909..6f8d3bcbe7a 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -43,7 +43,7 @@ ReturnValue Teleport::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint return RETURNVALUE_NOERROR; } -std::shared_ptr<Cylinder> Teleport::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>*, uint32_t &) { +std::shared_ptr<Cylinder> Teleport::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item> &, uint32_t &) { return getTeleport(); } diff --git a/src/game/movement/teleport.hpp b/src/game/movement/teleport.hpp index 3b4248e2c37..4dbcf47a5f2 100644 --- a/src/game/movement/teleport.hpp +++ b/src/game/movement/teleport.hpp @@ -41,7 +41,7 @@ class Teleport final : public Item, public Cylinder { ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index b87c06eefa8..3b55b1c2a78 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -608,15 +608,15 @@ ReturnValue Container::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t return RETURNVALUE_NOERROR; } -std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) { +std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) { if (!unlocked) { - *destItem = nullptr; + destItem = nullptr; return getContainer(); } if (index == 254 /*move up*/) { index = INDEX_WHEREEVER; - *destItem = nullptr; + destItem = nullptr; std::shared_ptr<Container> parentContainer = std::dynamic_pointer_cast<Container>(getParent()); if (parentContainer) { @@ -627,7 +627,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: if (index == 255 /*add wherever*/) { index = INDEX_WHEREEVER; - *destItem = nullptr; + destItem = nullptr; } else if (index >= static_cast<int32_t>(capacity()) && !hasPagination()) { /* if you have a container, maximize it to show all 20 slots @@ -637,7 +637,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: the client calculates the slot position as if the bag has 20 slots */ index = INDEX_WHEREEVER; - *destItem = nullptr; + destItem = nullptr; } const auto item = thing->getItem(); @@ -648,20 +648,20 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: if (index != INDEX_WHEREEVER) { std::shared_ptr<Item> itemFromIndex = getItemByIndex(index); if (itemFromIndex) { - *destItem = itemFromIndex; + destItem = itemFromIndex; } - std::shared_ptr<Cylinder> subCylinder = std::dynamic_pointer_cast<Cylinder>(*destItem); + std::shared_ptr<Cylinder> subCylinder = std::dynamic_pointer_cast<Cylinder>(destItem); if (subCylinder) { index = INDEX_WHEREEVER; - *destItem = nullptr; + destItem = nullptr; return subCylinder; } } bool autoStack = !hasBitSet(FLAG_IGNOREAUTOSTACK, flags); if (autoStack && item->isStackable() && item->getParent() != getContainer()) { - if (*destItem && (*destItem)->equals(item) && (*destItem)->getItemCount() < (*destItem)->getStackSize()) { + if (destItem && (destItem)->equals(item) && (destItem)->getItemCount() < (destItem)->getStackSize()) { return getContainer(); } @@ -669,7 +669,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: uint32_t n = 0; for (const std::shared_ptr<Item> &listItem : itemlist) { if (listItem != item && listItem->equals(item) && listItem->getItemCount() < listItem->getStackSize()) { - *destItem = listItem; + destItem = listItem; index = n; return getContainer(); } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index 7fa35055305..10eb6bd1b7c 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -141,7 +141,7 @@ class Container : public Item, public Cylinder { virtual ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) final; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) final; void addThing(std::shared_ptr<Thing> thing) final; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) final; diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index 622460419d0..43a93cb1814 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -32,7 +32,7 @@ ReturnValue Mailbox::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint3 return RETURNVALUE_NOTPOSSIBLE; } -std::shared_ptr<Cylinder> Mailbox::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>*, uint32_t &) { +std::shared_ptr<Cylinder> Mailbox::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>&, uint32_t &) { return getMailbox(); } diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index f2734726cec..bcba2ee5ac5 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -29,7 +29,7 @@ class Mailbox final : public Item, public Cylinder { ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/items/cylinder.hpp b/src/items/cylinder.hpp index 07099a0aa8c..c7a12744d4a 100644 --- a/src/items/cylinder.hpp +++ b/src/items/cylinder.hpp @@ -64,7 +64,7 @@ class Cylinder : virtual public Thing { * this method can modify the flags * \returns Cylinder returns the destination cylinder */ - virtual std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) = 0; + virtual std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) = 0; /** * Add the object to the cylinder @@ -186,7 +186,7 @@ class VirtualCylinder final : public Cylinder { virtual ReturnValue queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor = nullptr) override { return RETURNVALUE_NOTPOSSIBLE; } - virtual std::shared_ptr<Cylinder> queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>*, uint32_t &) override { + virtual std::shared_ptr<Cylinder> queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item> &, uint32_t &) override { return nullptr; } diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 017d8637d80..4829e45bcc4 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -871,9 +871,9 @@ ReturnValue Tile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t coun return RETURNVALUE_NOERROR; } -std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &tileFlags) { +std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &tileFlags) { std::shared_ptr<Tile> destTile = nullptr; - *destItem = nullptr; + destItem = nullptr; if (hasFlag(TILESTATE_FLOORCHANGE_DOWN)) { uint16_t dx = tilePos.x; @@ -961,7 +961,7 @@ std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_pt if (destTile) { std::shared_ptr<Thing> destThing = destTile->getTopDownItem(); if (destThing) { - *destItem = destThing->getItem(); + destItem = destThing->getItem(); if (thing->getItem()) { auto destCylinder = destThing->getCylinder(); if (destCylinder && !destCylinder->getContainer()) { diff --git a/src/items/tile.hpp b/src/items/tile.hpp index a9ae3c33d09..af9d7578546 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -210,7 +210,7 @@ class Tile : public Cylinder, public SharedObject { ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) final; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; std::vector<std::shared_ptr<Tile>> getSurroundingTiles(); diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index abba6d3968e..1a0d89b5bbb 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -32,7 +32,7 @@ ReturnValue TrashHolder::queryRemove(const std::shared_ptr<Thing> &, uint32_t, u return RETURNVALUE_NOTPOSSIBLE; } -std::shared_ptr<Cylinder> TrashHolder::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>*, uint32_t &) { +std::shared_ptr<Cylinder> TrashHolder::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item> &, uint32_t &) { return static_self_cast<TrashHolder>(); } diff --git a/src/items/trashholder.hpp b/src/items/trashholder.hpp index 44a0d876f34..b9d1405f36b 100644 --- a/src/items/trashholder.hpp +++ b/src/items/trashholder.hpp @@ -29,7 +29,7 @@ class TrashHolder final : public Item, public Cylinder { ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; ReturnValue queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) override; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; void addThing(std::shared_ptr<Thing> thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index b195302c26b..ee5dc3f048c 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -89,7 +89,7 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr<Thing> &thi return Tile::queryAdd(index, thing, count, tileFlags, actor); } -std::shared_ptr<Cylinder> HouseTile::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &tileFlags) { +std::shared_ptr<Cylinder> HouseTile::queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &tileFlags) { if (const auto &creature = thing->getCreature()) { if (const auto &player = creature->getPlayer()) { if (!house->isInvited(player)) { @@ -107,7 +107,7 @@ std::shared_ptr<Cylinder> HouseTile::queryDestination(int32_t &index, const std: } index = -1; - *destItem = nullptr; + destItem = nullptr; return destTile; } } diff --git a/src/map/house/housetile.hpp b/src/map/house/housetile.hpp index eb71b78f27d..3c35f4e08e9 100644 --- a/src/map/house/housetile.hpp +++ b/src/map/house/housetile.hpp @@ -20,7 +20,7 @@ class HouseTile final : public DynamicTile { // cylinder implementations ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item>* destItem, uint32_t &flags) override; + std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; diff --git a/src/map/map.cpp b/src/map/map.cpp index 3249e137704..c64a81e822a 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -311,7 +311,7 @@ bool Map::placeCreature(const Position ¢erPos, const std::shared_ptr<Creatur uint32_t flags = 0; std::shared_ptr<Item> toItem = nullptr; - const auto toCylinder = tile->queryDestination(index, creature, &toItem, flags); + const auto toCylinder = tile->queryDestination(index, creature, toItem, flags); toCylinder->internalAddThing(creature); const Position &dest = toCylinder->getPosition(); diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index e607225fa76..fa57693bcdf 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -50,60 +50,12 @@ void NetworkMessage::addString(const std::string &value, const std::string &func return; } if (stringLen > NETWORKMESSAGE_MAXSIZE) { - g_logger().error("[NetworkMessage::addString] - Exceeded NetworkMessage max size: {}, actual size: {}, function '{}'", NETWORKMESSAGE_MAXSIZE, stringLen, function); + g_logger().error("[NetworkMessage::addString] - Exceded NetworkMessage max size: {}, actually size: {}, function '{}'", NETWORKMESSAGE_MAXSIZE, stringLen, function); return; } add<uint16_t>(stringLen); - - unsigned char* dst = buffer + info.position; - const auto* src = reinterpret_cast<const unsigned char*>(value.c_str()); - size_t remaining = stringLen; - -#if defined(__AVX2__) - // Use AVX2 to copy 32 bytes at a time - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src))); - src += 32; - dst += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 to copy remaining bytes - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(src))); - src += 16; - dst += 16; - remaining -= 16; - } - while (remaining >= 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src))); - src += 8; - dst += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(src); - src += 4; - dst += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(src); - src += 2; - dst += 2; - remaining -= 2; - } - while (remaining == 1) { - *dst = *src; - remaining -= 1; - } -#else - memcpy(dst, src, remaining); -#endif - + memcpy(buffer + info.position, value.c_str(), stringLen); info.position += stringLen; info.length += stringLen; } @@ -123,115 +75,23 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) { return; } if (size > NETWORKMESSAGE_MAXSIZE) { - g_logger().error("[NetworkMessage::addBytes] - Exceeded NetworkMessage max size: {}, actually size: {}", NETWORKMESSAGE_MAXSIZE, size); + g_logger().error("[NetworkMessage::addBytes] - Exceded NetworkMessage max size: {}, actually size: {}", NETWORKMESSAGE_MAXSIZE, size); return; } - unsigned char* dst = buffer + info.position; - const auto* src = reinterpret_cast<const unsigned char*>(bytes); - size_t remaining = size; - -#if defined(__AVX2__) - // Use AVX2 to copy 32 bytes at a time - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src))); - src += 32; - dst += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 to copy remaining bytes - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(src))); - src += 16; - dst += 16; - remaining -= 16; - } - while (remaining >= 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src))); - src += 8; - dst += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(src); - src += 4; - dst += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(src); - src += 2; - dst += 2; - remaining -= 2; - } - while (remaining == 1) { - *dst = *src; - remaining -= 1; - } -#else - memcpy(dst, src, remaining); -#endif - + memcpy(buffer + info.position, bytes, size); info.position += size; info.length += size; } void NetworkMessage::addPaddingBytes(size_t n) { -#define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) + #define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) if (!canAdd(n)) { return; } -#undef canAdd - - unsigned char* dst = buffer + info.position; - size_t remaining = n; - -#if defined(__AVX2__) - const __m256i padding_avx2 = _mm256_set1_epi8(0x33); // AVX2: 32 bytes de valor de preenchimento - - // Use AVX2 para preencher 32 bytes de cada vez - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), padding_avx2); - dst += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - const __m128i padding_sse2 = _mm_set1_epi8(0x33); // SSE2: 16 bytes de valor de preenchimento - - // Use SSE2 para preencher os bytes restantes - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), padding_sse2); - dst += 16; - remaining -= 16; - } - while (remaining >= 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&padding_sse2))); - dst += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = 0x33333333; // Preencher 4 bytes com 0x33 - dst += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = 0x3333; // Preencher 2 bytes com 0x33 - dst += 2; - remaining -= 2; - } - while (remaining == 1) { - *dst = 0x33; // Preencher 1 byte com 0x33 - remaining -= 1; - } -#else - memset(dst, 0x33, remaining); -#endif + #undef canAdd + memset(buffer + info.position, 0x33, n); info.length += n; } diff --git a/src/server/network/message/networkmessage.hpp b/src/server/network/message/networkmessage.hpp index 7cb69901fba..fa3e7ced502 100644 --- a/src/server/network/message/networkmessage.hpp +++ b/src/server/network/message/networkmessage.hpp @@ -53,55 +53,7 @@ class NetworkMessage { } T v; - const unsigned char* src = buffer + info.position; - auto* dst = reinterpret_cast<unsigned char*>(&v); - - size_t remaining = sizeof(T); - -#if defined(__AVX2__) - // Use AVX2 para carregar 32 bytes por vez - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src))); - src += 32; - dst += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 para carregar os bytes restantes - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(src))); - src += 16; - dst += 16; - remaining -= 16; - } - while (remaining >= 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src))); - src += 8; - dst += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(src); - src += 4; - dst += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(src); - src += 2; - dst += 2; - remaining -= 2; - } - while (remaining == 1) { - *dst = *src; - remaining -= 1; - } -#else memcpy(&v, buffer + info.position, sizeof(T)); -#endif - info.position += sizeof(T); return v; } @@ -130,55 +82,7 @@ class NetworkMessage { return; } - unsigned char* dst = buffer + info.position; - const auto* src = reinterpret_cast<const unsigned char*>(&value); - - size_t remaining = sizeof(T); - -#if defined(__AVX2__) - // Use AVX2 to copy 32 bytes at a time - while (remaining >= 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src))); - src += 32; - dst += 32; - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 to copy remaining bytes - while (remaining >= 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(src))); - src += 16; - dst += 16; - remaining -= 16; - } - while (remaining >= 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src))); - src += 8; - dst += 8; - remaining -= 8; - } - while (remaining >= 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(src); - src += 4; - dst += 4; - remaining -= 4; - } - while (remaining >= 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(src); - src += 2; - dst += 2; - remaining -= 2; - } - while (remaining == 1) { - *dst = *src; - remaining -= 1; - } -#else - memcpy(dst, src, remaining); -#endif - + memcpy(buffer + info.position, &value, sizeof(T)); info.position += sizeof(T); info.length += sizeof(T); } diff --git a/src/server/network/message/outputmessage.hpp b/src/server/network/message/outputmessage.hpp index deb61d6e9df..5b458d6f115 100644 --- a/src/server/network/message/outputmessage.hpp +++ b/src/server/network/message/outputmessage.hpp @@ -39,91 +39,15 @@ class OutputMessage : public NetworkMessage { } void append(const NetworkMessage &msg) { - const auto msgLen = msg.getLength(); - const unsigned char* src = msg.getBuffer() + INITIAL_BUFFER_POSITION; - unsigned char* dst = buffer + info.position; - - size_t remaining = msgLen; - -#if defined(__AVX2__) - // Use AVX2 to copy 32 bytes at a time - while (remaining >= 32) { - copy_block<32>(src, dst); - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 to copy remaining bytes - while (remaining >= 16) { - copy_block<16>(src, dst); - remaining -= 16; - } - while (remaining >= 8) { - copy_block<8>(src, dst); - remaining -= 8; - } - while (remaining >= 4) { - copy_block<4>(src, dst); - remaining -= 4; - } - while (remaining >= 2) { - copy_block<2>(src, dst); - remaining -= 2; - } - while (remaining == 1) { - copy_block<1>(src, dst); - remaining -= 1; - } -#else - memcpy(dst, src, remaining); -#endif - + auto msgLen = msg.getLength(); + memcpy(buffer + info.position, msg.getBuffer() + INITIAL_BUFFER_POSITION, msgLen); info.length += msgLen; info.position += msgLen; } void append(const OutputMessage_ptr &msg) { - const auto msgLen = msg->getLength(); - const unsigned char* src = msg->getBuffer() + INITIAL_BUFFER_POSITION; - unsigned char* dst = buffer + info.position; - - size_t remaining = msgLen; - -#if defined(__AVX2__) - // Use AVX2 to copy 32 bytes at a time - while (remaining >= 32) { - copy_block<32>(src, dst); - remaining -= 32; - } -#endif - -#if defined(__SSE2__) - // Use SSE2 to copy remaining bytes - while (remaining >= 16) { - copy_block<16>(src, dst); - remaining -= 16; - } - while (remaining >= 8) { - copy_block<8>(src, dst); - remaining -= 8; - } - while (remaining >= 4) { - copy_block<4>(src, dst); - remaining -= 4; - } - while (remaining >= 2) { - copy_block<2>(src, dst); - remaining -= 2; - } - while (remaining == 1) { - copy_block<1>(src, dst); - remaining -= 1; - } -#else - memcpy(dst, src, remaining); -#endif - + auto msgLen = msg->getLength(); + memcpy(buffer + info.position, msg->getBuffer() + INITIAL_BUFFER_POSITION, msgLen); info.length += msgLen; info.position += msgLen; } @@ -138,53 +62,12 @@ class OutputMessage : public NetworkMessage { assert(outputBufferStart >= sizeof(T)); outputBufferStart -= sizeof(T); - -#if defined(__SSE2__) - if constexpr (sizeof(T) >= 16) { - // Use SSE2 to copy 16 bytes at a time - _mm_storeu_si128(reinterpret_cast<__m128i*>(buffer + outputBufferStart), _mm_loadu_si128(reinterpret_cast<const __m128i*>(&addHeader))); - } else if constexpr (sizeof(T) >= 8) { - // Use SSE2 to copy 8 bytes - _mm_storel_epi64(reinterpret_cast<__m128i*>(buffer + outputBufferStart), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(&addHeader))); - } else if constexpr (sizeof(T) >= 4) { - // Use SSE2 to copy 4 bytes - *reinterpret_cast<uint32_t*>(buffer + outputBufferStart) = *reinterpret_cast<const uint32_t*>(&addHeader); - } else if constexpr (sizeof(T) >= 2) { - // Use SSE2 to copy 2 bytes - *reinterpret_cast<uint16_t*>(buffer + outputBufferStart) = *reinterpret_cast<const uint16_t*>(&addHeader); - } else { - // Copy 1 byte - *reinterpret_cast<uint8_t*>(buffer + outputBufferStart) = *reinterpret_cast<const uint8_t*>(&addHeader); - } -#else memcpy(buffer + outputBufferStart, &addHeader, sizeof(T)); -#endif - // added header size to the message size info.length += sizeof(T); } MsgSize_t outputBufferStart = INITIAL_BUFFER_POSITION; - - template <size_t N> - static void copy_block(const unsigned char*&src, unsigned char*&dst) { - if constexpr (N == 32) { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(dst), _mm256_loadu_si256(reinterpret_cast<const __m256i*>(src))); - } else if constexpr (N == 16) { - _mm_storeu_si128(reinterpret_cast<__m128i*>(dst), _mm_loadu_si128(reinterpret_cast<const __m128i*>(src))); - } else if constexpr (N == 8) { - _mm_storel_epi64(reinterpret_cast<__m128i*>(dst), _mm_loadl_epi64(reinterpret_cast<const __m128i*>(src))); - } else if constexpr (N == 4) { - *reinterpret_cast<uint32_t*>(dst) = *reinterpret_cast<const uint32_t*>(src); - } else if constexpr (N == 2) { - *reinterpret_cast<uint16_t*>(dst) = *reinterpret_cast<const uint16_t*>(src); - } else if constexpr (N == 1) { - *dst = *src; - } - - src += N; - dst += N; - } }; class OutputMessagePool { diff --git a/src/server/network/protocol/protocol.cpp b/src/server/network/protocol/protocol.cpp index 2538b0f5460..0c158f43b28 100644 --- a/src/server/network/protocol/protocol.cpp +++ b/src/server/network/protocol/protocol.cpp @@ -105,148 +105,70 @@ OutputMessage_ptr Protocol::getOutputBuffer(int32_t size) { } void Protocol::XTEA_encrypt(OutputMessage &msg) const { - const size_t paddingBytes = msg.getLength() & 7; + const uint32_t delta = 0x61C88647; + + // The message must be a multiple of 8 + size_t paddingBytes = msg.getLength() & 7; if (paddingBytes != 0) { msg.addPaddingBytes(8 - paddingBytes); } uint8_t* buffer = msg.getOutputBuffer(); - const auto messageLength = static_cast<int32_t>(msg.getLength()); - - precacheControlSumsEncrypt(); - - // Alocar memória alinhada usando std::unique_ptr para garantir liberação - const std::unique_ptr<uint8_t, AlignedFreeDeleter> alignedBuffer( - aligned_alloc_memory(messageLength, 32), AlignedFreeDeleter() - ); - - if (!alignedBuffer) { - g_logger().error("[] - Error alianhamento memory", __FUNCTION__); - } - - // Copiar dados para buffer alinhado usando AVX2 - simd_memcpy_avx2(alignedBuffer.get(), buffer, messageLength); - + auto messageLength = static_cast<int32_t>(msg.getLength()); int32_t readPos = 0; + const std::array<uint32_t, 4> newKey = { key[0], key[1], key[2], key[3] }; + // TODO: refactor this for not use c-style + uint32_t precachedControlSum[32][2]; + uint32_t sum = 0; + for (int32_t i = 0; i < 32; ++i) { + precachedControlSum[i][0] = (sum + newKey[sum & 3]); + sum -= delta; + precachedControlSum[i][1] = (sum + newKey[(sum >> 11) & 3]); + } while (readPos < messageLength) { - // Usar prefetch otimizado com _MM_HINT_T1 para cache L2 - _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer.get() + readPos + 256), _MM_HINT_T1); - - __m256i vData = is_aligned(alignedBuffer.get() + readPos, 32) - ? _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)) - : _mm256_loadu_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)); - - auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); - - for (int32_t i = 0; i < 32; i += 8) { - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[i * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[i * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 1) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 1) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 2) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 2) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 3) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 3) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 4) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 4) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 5) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 5) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 6) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 6) * 2 + 1]; - - vDataArr[0] += ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsEncrypt[(i + 7) * 2]; - vDataArr[1] += ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsEncrypt[(i + 7) * 2 + 1]; - } - - if (is_aligned(alignedBuffer.get() + readPos, 32)) { - _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); - } else { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + std::array<uint32_t, 2> vData = {}; + memcpy(vData.data(), buffer + readPos, 8); + for (int32_t i = 0; i < 32; ++i) { + vData[0] += ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ precachedControlSum[i][0]; + vData[1] += ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ precachedControlSum[i][1]; } - + memcpy(buffer + readPos, vData.data(), 8); readPos += 8; } - - // Copiar de volta para o buffer original - simd_memcpy_avx2(buffer, alignedBuffer.get(), messageLength); } bool Protocol::XTEA_decrypt(NetworkMessage &msg) const { - const uint16_t msgLength = msg.getLength() - (checksumMethod == CHECKSUM_METHOD_NONE ? 2 : 6); + uint16_t msgLength = msg.getLength() - (checksumMethod == CHECKSUM_METHOD_NONE ? 2 : 6); if ((msgLength & 7) != 0) { return false; } - uint8_t* buffer = msg.getBuffer() + msg.getBufferPosition(); - const auto messageLength = static_cast<int32_t>(msgLength); - - precacheControlSumsDecrypt(); - - // Alocar memória alinhada usando std::unique_ptr para garantir liberação - const std::unique_ptr<uint8_t, AlignedFreeDeleter> alignedBuffer( - aligned_alloc_memory(messageLength, 32), AlignedFreeDeleter() - ); - - if (!alignedBuffer) { - g_logger().error("[] - Error alianhamento memory", __FUNCTION__); - } - - simd_memcpy_avx2(alignedBuffer.get(), buffer, messageLength); + const uint32_t delta = 0x61C88647; + uint8_t* buffer = msg.getBuffer() + msg.getBufferPosition(); + auto messageLength = static_cast<int32_t>(msgLength); int32_t readPos = 0; + const std::array<uint32_t, 4> newKey = { key[0], key[1], key[2], key[3] }; + // TODO: refactor this for not use c-style + uint32_t precachedControlSum[32][2]; + uint32_t sum = 0xC6EF3720; + for (int32_t i = 0; i < 32; ++i) { + precachedControlSum[i][0] = (sum + newKey[(sum >> 11) & 3]); + sum += delta; + precachedControlSum[i][1] = (sum + newKey[sum & 3]); + } while (readPos < messageLength) { - _mm_prefetch(reinterpret_cast<const char*>(alignedBuffer.get() + readPos + 256), _MM_HINT_T1); - - __m256i vData = is_aligned(alignedBuffer.get() + readPos, 32) - ? _mm256_load_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)) - : _mm256_loadu_si256(reinterpret_cast<const __m256i*>(alignedBuffer.get() + readPos)); - - auto* vDataArr = reinterpret_cast<uint32_t*>(&vData); - - for (int32_t i = 0; i < 32; i += 8) { - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[i * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[i * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 1) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 1) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 2) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 2) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 3) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 3) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 4) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 4) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 5) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 5) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 6) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 6) * 2 + 1]; - - vDataArr[1] -= ((vDataArr[0] << 4) ^ (vDataArr[0] >> 5)) + vDataArr[0] ^ cachedControlSumsDecrypt[(i + 7) * 2]; - vDataArr[0] -= ((vDataArr[1] << 4) ^ (vDataArr[1] >> 5)) + vDataArr[1] ^ cachedControlSumsDecrypt[(i + 7) * 2 + 1]; - } - - if (is_aligned(alignedBuffer.get() + readPos, 32)) { - _mm256_store_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); - } else { - _mm256_storeu_si256(reinterpret_cast<__m256i*>(alignedBuffer.get() + readPos), vData); + std::array<uint32_t, 2> vData = {}; + memcpy(vData.data(), buffer + readPos, 8); + for (int32_t i = 0; i < 32; ++i) { + vData[1] -= ((vData[0] << 4 ^ vData[0] >> 5) + vData[0]) ^ precachedControlSum[i][0]; + vData[0] -= ((vData[1] << 4 ^ vData[1] >> 5) + vData[1]) ^ precachedControlSum[i][1]; } - + memcpy(buffer + readPos, vData.data(), 8); readPos += 8; } - simd_memcpy_avx2(buffer, alignedBuffer.get(), messageLength); - - const auto innerLength = msg.get<uint16_t>(); + uint16_t innerLength = msg.get<uint16_t>(); if (std::cmp_greater(innerLength, msgLength - 2)) { return false; } From 769dc1f1202d659bf878ff83723bf5e24d720712 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Sun, 15 Sep 2024 21:50:33 -0400 Subject: [PATCH 32/34] up --- src/creatures/combat/spells.hpp | 2 +- src/creatures/players/player.hpp | 2 +- src/game/movement/position.hpp | 2 +- src/game/movement/teleport.cpp | 2 +- src/game/movement/teleport.hpp | 2 +- src/items/bed.cpp | 24 +- src/items/bed.hpp | 2 +- src/items/containers/container.cpp | 2 +- src/items/containers/container.hpp | 2 +- src/items/containers/mailbox/mailbox.cpp | 2 +- src/items/containers/mailbox/mailbox.hpp | 2 +- src/items/cylinder.hpp | 4 +- src/items/item.cpp | 86 ++--- src/items/item.hpp | 24 +- src/items/items.cpp | 34 +- src/items/items.hpp | 4 +- src/items/items_classification.hpp | 4 +- src/items/items_definitions.hpp | 4 +- src/items/tile.cpp | 173 ++++----- src/items/tile.hpp | 2 +- src/items/trashholder.cpp | 4 +- src/items/trashholder.hpp | 2 +- src/kv/kv.cpp | 6 +- src/kv/kv.hpp | 9 +- src/kv/kv_sql.cpp | 20 +- src/kv/kv_sql.hpp | 4 +- src/kv/value_wrapper.cpp | 4 +- src/kv/value_wrapper_proto.cpp | 4 +- src/kv/value_wrapper_proto.hpp | 10 +- src/lib/di/runtime_provider.hpp | 8 +- src/lib/metrics/metrics.hpp | 12 +- src/lib/thread/thread_pool.cpp | 2 +- src/lib/thread/thread_pool.hpp | 2 +- src/lua/callbacks/creaturecallback.cpp | 6 +- src/lua/callbacks/creaturecallback.hpp | 2 +- src/lua/callbacks/event_callback.cpp | 38 +- src/lua/callbacks/event_callback.hpp | 18 +- src/lua/callbacks/events_callbacks.hpp | 6 +- src/lua/creature/actions.cpp | 50 +-- src/lua/creature/actions.hpp | 24 +- src/lua/creature/creatureevent.cpp | 4 +- src/lua/creature/events.cpp | 40 +- src/lua/creature/events.hpp | 12 +- src/lua/creature/movement.cpp | 38 +- src/lua/creature/movement.hpp | 10 +- src/lua/creature/raids.cpp | 42 +- src/lua/creature/raids.hpp | 2 +- src/lua/creature/talkaction.cpp | 12 +- src/lua/creature/talkaction.hpp | 2 +- src/lua/functions/core/core_functions.hpp | 6 + .../functions/core/game/bank_functions.cpp | 40 +- .../functions/core/game/bank_functions.hpp | 6 + .../functions/core/game/config_functions.cpp | 8 +- .../functions/core/game/config_functions.hpp | 6 + .../core/game/core_game_functions.hpp | 6 + .../functions/core/game/game_functions.cpp | 118 +++--- .../functions/core/game/game_functions.hpp | 6 + .../functions/core/game/global_functions.cpp | 144 +++---- .../functions/core/game/global_functions.hpp | 6 + src/lua/functions/core/game/lua_enums.cpp | 24 +- src/lua/functions/core/game/lua_enums.hpp | 6 + .../core/game/modal_window_functions.hpp | 6 + .../functions/core/game/zone_functions.cpp | 78 ++-- .../functions/core/game/zone_functions.hpp | 6 + src/lua/functions/core/libs/bit_functions.hpp | 6 + .../core/libs/core_libs_functions.hpp | 6 + src/lua/functions/core/libs/db_functions.cpp | 8 +- src/lua/functions/core/libs/db_functions.hpp | 6 + src/lua/functions/core/libs/kv_functions.cpp | 26 +- src/lua/functions/core/libs/kv_functions.hpp | 6 + .../functions/core/libs/logger_functions.hpp | 6 + .../functions/core/libs/metrics_functions.cpp | 6 +- .../functions/core/libs/metrics_functions.hpp | 6 + .../functions/core/libs/result_functions.cpp | 8 +- .../functions/core/libs/result_functions.hpp | 6 + .../core/network/core_network_functions.hpp | 6 + .../network/network_message_functions.cpp | 22 +- .../network/network_message_functions.hpp | 6 + .../core/network/webhook_functions.cpp | 8 +- .../core/network/webhook_functions.hpp | 6 + .../creatures/combat/combat_functions.cpp | 24 +- .../creatures/combat/combat_functions.hpp | 6 + .../creatures/combat/condition_functions.cpp | 52 +-- .../creatures/combat/condition_functions.hpp | 6 + .../creatures/combat/spell_functions.cpp | 186 ++++----- .../creatures/combat/spell_functions.hpp | 6 + .../creatures/combat/variant_functions.cpp | 2 +- .../creatures/combat/variant_functions.hpp | 6 + .../creatures/creature_functions.cpp | 212 +++++----- .../creatures/creature_functions.hpp | 6 + .../creatures/monster/charm_functions.cpp | 26 +- .../creatures/monster/charm_functions.hpp | 6 + .../creatures/monster/loot_functions.cpp | 40 +- .../creatures/monster/loot_functions.hpp | 6 + .../creatures/monster/monster_functions.cpp | 124 +++--- .../creatures/monster/monster_functions.hpp | 6 + .../monster/monster_spell_functions.hpp | 6 + .../monster/monster_type_functions.cpp | 30 +- .../monster/monster_type_functions.hpp | 6 + .../functions/creatures/npc/npc_functions.cpp | 54 +-- .../functions/creatures/npc/npc_functions.hpp | 6 + .../creatures/npc/npc_type_functions.cpp | 2 +- .../creatures/npc/npc_type_functions.hpp | 6 + .../creatures/npc/shop_functions.cpp | 2 +- .../creatures/npc/shop_functions.hpp | 6 + .../creatures/player/group_functions.cpp | 4 +- .../creatures/player/group_functions.hpp | 6 + .../creatures/player/guild_functions.cpp | 14 +- .../creatures/player/guild_functions.hpp | 6 + .../creatures/player/mount_functions.cpp | 2 +- .../creatures/player/mount_functions.hpp | 6 + .../creatures/player/party_functions.cpp | 4 +- .../creatures/player/party_functions.hpp | 6 + .../creatures/player/player_functions.cpp | 361 +++++++++--------- .../creatures/player/vocation_functions.cpp | 10 +- .../creatures/player/vocation_functions.hpp | 6 + src/lua/functions/events/action_functions.cpp | 10 +- src/lua/functions/events/action_functions.hpp | 6 + .../events/creature_event_functions.cpp | 2 +- .../events/creature_event_functions.hpp | 6 + .../events/event_callback_functions.hpp | 8 +- src/lua/functions/events/events_functions.hpp | 8 +- .../events/events_scheduler_functions.hpp | 6 + .../events/global_event_functions.cpp | 10 +- .../events/global_event_functions.hpp | 6 + .../functions/events/move_event_functions.cpp | 10 +- .../functions/events/move_event_functions.hpp | 6 + .../events/talk_action_functions.cpp | 8 +- .../events/talk_action_functions.hpp | 6 + .../functions/items/container_functions.cpp | 26 +- .../functions/items/container_functions.hpp | 7 +- .../functions/items/imbuement_functions.cpp | 20 +- .../functions/items/imbuement_functions.hpp | 6 + .../items/item_classification_functions.hpp | 6 + src/lua/functions/items/item_functions.cpp | 52 ++- src/lua/functions/items/item_functions.hpp | 6 + .../functions/items/item_type_functions.cpp | 12 +- .../functions/items/item_type_functions.hpp | 6 + src/lua/functions/items/weapon_functions.cpp | 50 +-- 139 files changed, 1603 insertions(+), 1313 deletions(-) diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index d3b96b150e6..c0849d1b577 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -463,7 +463,7 @@ class RuneSpell final : public Action, public Spell { bool hasOwnErrorHandler() override { return true; } - std::shared_ptr<Thing> getTarget(const std::shared_ptr<Player> &, std::shared_ptr<Creature> targetCreature, const Position &, uint8_t) const override { + std::shared_ptr<Thing> getTarget(const std::shared_ptr<Player> &, const std::shared_ptr<Creature> &targetCreature, const Position &, uint8_t) const override { return targetCreature; } diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index dbad2c50484..1c15e32d449 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -2699,7 +2699,7 @@ class Player final : public Creature, public Cylinder, public Bankable { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; - void addThing(std::shared_ptr<Thing>) override { } + void addThing(const std::shared_ptr<Thing>&) override { } void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; diff --git a/src/game/movement/position.hpp b/src/game/movement/position.hpp index 87e74ee3e22..9e298ee4792 100644 --- a/src/game/movement/position.hpp +++ b/src/game/movement/position.hpp @@ -119,7 +119,7 @@ struct Position { namespace std { template <> struct hash<Position> { - std::size_t operator()(const Position &p) const { + std::size_t operator()(const Position &p) const noexcept { return static_cast<std::size_t>(p.x) | (static_cast<std::size_t>(p.y) << 16) | (static_cast<std::size_t>(p.z) << 32); } }; diff --git a/src/game/movement/teleport.cpp b/src/game/movement/teleport.cpp index 6f8d3bcbe7a..fed9e218391 100644 --- a/src/game/movement/teleport.cpp +++ b/src/game/movement/teleport.cpp @@ -62,7 +62,7 @@ bool Teleport::checkInfinityLoop(const std::shared_ptr<Tile> &destTile) { return false; } -void Teleport::addThing(std::shared_ptr<Thing> thing) { +void Teleport::addThing(const std::shared_ptr<Thing> &thing) { return addThing(0, thing); } diff --git a/src/game/movement/teleport.hpp b/src/game/movement/teleport.hpp index 4dbcf47a5f2..2346a539f4b 100644 --- a/src/game/movement/teleport.hpp +++ b/src/game/movement/teleport.hpp @@ -43,7 +43,7 @@ class Teleport final : public Item, public Cylinder { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; - void addThing(std::shared_ptr<Thing> thing) override; + void addThing(const std::shared_ptr<Thing> &thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; diff --git a/src/items/bed.cpp b/src/items/bed.cpp index a2af5481de0..9c391f1e020 100644 --- a/src/items/bed.cpp +++ b/src/items/bed.cpp @@ -29,7 +29,7 @@ Attr_ReadValue BedItem::readAttr(AttrTypes_t attr, PropStream &propStream) { } if (guid != 0) { - std::string name = IOLoginData::getNameByGuid(guid); + const std::string name = IOLoginData::getNameByGuid(guid); if (!name.empty()) { setAttribute(ItemAttribute_t::DESCRIPTION, name + " is sleeping there."); g_game().setBedSleeper(static_self_cast<BedItem>(), guid); @@ -69,10 +69,10 @@ void BedItem::serializeAttr(PropWriteStream &propWriteStream) const { } std::shared_ptr<BedItem> BedItem::getNextBedItem() { - Direction dir = Item::items[id].bedPartnerDir; - Position targetPos = getNextPosition(dir, getPosition()); + const Direction dir = Item::items[id].bedPartnerDir; + const Position targetPos = getNextPosition(dir, getPosition()); - std::shared_ptr<Tile> tile = g_game().map.getTile(targetPos); + const auto &tile = g_game().map.getTile(targetPos); if (tile == nullptr) { return nullptr; } @@ -84,7 +84,7 @@ bool BedItem::canUse(const std::shared_ptr<Player> &player) { return false; } - auto nextBedItem = getNextBedItem(); + const auto &nextBedItem = getNextBedItem(); if (nextBedItem == nullptr) { return false; } @@ -106,7 +106,7 @@ bool BedItem::canUse(const std::shared_ptr<Player> &player) { return true; } - auto sleeper = std::make_shared<Player>(nullptr); + const auto sleeper = std::make_shared<Player>(nullptr); if (!IOLoginData::loadPlayerById(sleeper, sleeperGUID)) { return false; } @@ -117,7 +117,7 @@ bool BedItem::canUse(const std::shared_ptr<Player> &player) { return true; } -bool BedItem::isBedComplete(const std::shared_ptr<BedItem> &nextBedItem) { +bool BedItem::isBedComplete(const std::shared_ptr<BedItem> &nextBedItem) const { const ItemType &it = Item::items[id]; if (nextBedItem == nullptr) { @@ -159,7 +159,7 @@ bool BedItem::sleep(const std::shared_ptr<Player> &player) { return false; } - std::shared_ptr<BedItem> nextBedItem = getNextBedItem(); + const auto &nextBedItem = getNextBedItem(); internalSetSleeper(player); @@ -201,7 +201,7 @@ void BedItem::wakeUp(const std::shared_ptr<Player> &player) { if (sleeperGUID != 0) { if (player == nullptr) { - auto regenPlayer = std::make_shared<Player>(nullptr); + const auto ®enPlayer = std::make_shared<Player>(nullptr); if (IOLoginData::loadPlayerById(regenPlayer, sleeperGUID)) { regeneratePlayer(regenPlayer); g_saveManager().savePlayer(regenPlayer); @@ -215,7 +215,7 @@ void BedItem::wakeUp(const std::shared_ptr<Player> &player) { // update the bedSleepersMap g_game().removeBedSleeper(sleeperGUID); - std::shared_ptr<BedItem> nextBedItem = getNextBedItem(); + const auto &nextBedItem = getNextBedItem(); // unset sleep info internalRemoveSleeper(); @@ -235,7 +235,7 @@ void BedItem::wakeUp(const std::shared_ptr<Player> &player) { void BedItem::regeneratePlayer(const std::shared_ptr<Player> &player) const { const uint32_t sleptTime = time(nullptr) - sleepStart; - std::shared_ptr<Condition> condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); + const auto &condition = player->getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT); if (condition != nullptr) { uint32_t regen; if (condition->getTicks() != -1) { @@ -276,7 +276,7 @@ void BedItem::updateAppearance(const std::shared_ptr<Player> &player) { } void BedItem::internalSetSleeper(const std::shared_ptr<Player> &player) { - std::string desc_str = player->getName() + " is sleeping there."; + const std::string desc_str = player->getName() + " is sleeping there."; sleeperGUID = player->getGUID(); sleepStart = time(nullptr); diff --git a/src/items/bed.hpp b/src/items/bed.hpp index 7b62f6edad8..725db01ea1b 100644 --- a/src/items/bed.hpp +++ b/src/items/bed.hpp @@ -39,7 +39,7 @@ class BedItem final : public Item { bool canUse(const std::shared_ptr<Player> &player); - bool isBedComplete(const std::shared_ptr<BedItem> &nextBedItem); + bool isBedComplete(const std::shared_ptr<BedItem> &nextBedItem) const; bool trySleep(const std::shared_ptr<Player> &player); bool sleep(const std::shared_ptr<Player> &player); diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index 3b55b1c2a78..a120310dd6c 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -679,7 +679,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: return getContainer(); } -void Container::addThing(std::shared_ptr<Thing> thing) { +void Container::addThing(const std::shared_ptr<Thing> &thing) { return addThing(0, thing); } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index 10eb6bd1b7c..c373eaa5e43 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -143,7 +143,7 @@ class Container : public Item, public Cylinder { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) final; - void addThing(std::shared_ptr<Thing> thing) final; + void addThing(const std::shared_ptr<Thing> &thing) final; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) final; void addItemBack(const std::shared_ptr<Item> &item); diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index 43a93cb1814..7e5e056ba69 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -36,7 +36,7 @@ std::shared_ptr<Cylinder> Mailbox::queryDestination(int32_t &, const std::shared return getMailbox(); } -void Mailbox::addThing(std::shared_ptr<Thing> thing) { +void Mailbox::addThing(const std::shared_ptr<Thing> &thing) { return addThing(0, thing); } diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index bcba2ee5ac5..353606bfb59 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -31,7 +31,7 @@ class Mailbox final : public Item, public Cylinder { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; - void addThing(std::shared_ptr<Thing> thing) override; + void addThing(const std::shared_ptr<Thing> &thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; diff --git a/src/items/cylinder.hpp b/src/items/cylinder.hpp index c7a12744d4a..b4b606a3965 100644 --- a/src/items/cylinder.hpp +++ b/src/items/cylinder.hpp @@ -70,7 +70,7 @@ class Cylinder : virtual public Thing { * Add the object to the cylinder * \param thing is the object to add */ - virtual void addThing(std::shared_ptr<Thing> thing) = 0; + virtual void addThing(const std::shared_ptr<Thing> &thing) = 0; /** * Add the object to the cylinder @@ -190,7 +190,7 @@ class VirtualCylinder final : public Cylinder { return nullptr; } - virtual void addThing(std::shared_ptr<Thing>) override { } + virtual void addThing(const std::shared_ptr<Thing>&) override { } virtual void addThing(int32_t, const std::shared_ptr<Thing> &) override { } virtual void updateThing(const std::shared_ptr<Thing> &, uint16_t, uint32_t) override { } virtual void replaceThing(uint32_t, const std::shared_ptr<Thing> &) override { } diff --git a/src/items/item.cpp b/src/items/item.cpp index 9c9857ace98..bd8caa95cb9 100644 --- a/src/items/item.cpp +++ b/src/items/item.cpp @@ -69,7 +69,7 @@ std::shared_ptr<Item> Item::CreateItem(const uint16_t type, uint16_t count /*= 0 } else if (it.isBed()) { newItem = std::make_shared<BedItem>(type); } else { - auto itemMap = ItemTransformationMap.find(static_cast<ItemID_t>(it.id)); + const auto itemMap = ItemTransformationMap.find(static_cast<ItemID_t>(it.id)); if (itemMap != ItemTransformationMap.end()) { newItem = std::make_shared<Item>(itemMap->second, count); } else { @@ -77,7 +77,7 @@ std::shared_ptr<Item> Item::CreateItem(const uint16_t type, uint16_t count /*= 0 } } } else if (type > 0 && itemPosition) { - auto position = *itemPosition; + const auto position = *itemPosition; g_logger().warn("[Item::CreateItem] Item with id '{}', in position '{}' not exists in the appearances.dat and cannot be created.", type, position.toString()); } else { g_logger().warn("[Item::CreateItem] Item with id '{}' is not registered and cannot be created.", type); @@ -88,14 +88,14 @@ std::shared_ptr<Item> Item::CreateItem(const uint16_t type, uint16_t count /*= 0 bool Item::getImbuementInfo(uint8_t slot, ImbuementInfo* imbuementInfo) const { const CustomAttribute* attribute = getCustomAttribute(std::to_string(ITEM_IMBUEMENT_SLOT + slot)); - auto info = attribute ? attribute->getAttribute<uint32_t>() : 0; + const auto info = attribute ? attribute->getAttribute<uint32_t>() : 0; imbuementInfo->imbuement = g_imbuements().getImbuement(info & 0xFF); imbuementInfo->duration = info >> 8; return imbuementInfo->duration && imbuementInfo->imbuement; } void Item::setImbuement(uint8_t slot, uint16_t imbuementId, uint32_t duration) { - auto valueDuration = (static_cast<int64_t>(duration > 0 ? (duration << 8) | imbuementId : 0)); + const auto valueDuration = (static_cast<int64_t>(duration > 0 ? (duration << 8) | imbuementId : 0)); setCustomAttribute(std::to_string(ITEM_IMBUEMENT_SLOT + slot), valueDuration); } @@ -153,7 +153,7 @@ std::shared_ptr<Container> Item::CreateItemAsContainer(const uint16_t type, uint return nullptr; } - std::shared_ptr<Container> newItem = std::make_shared<Container>(type, size); + auto newItem = std::make_shared<Container>(type, size); return newItem; } @@ -197,9 +197,9 @@ std::shared_ptr<Item> Item::CreateItem(uint16_t itemId, Position &itemPosition) Item::Item(const uint16_t itemId, uint16_t itemCount /*= 0*/) : id(itemId) { const ItemType &it = items[id]; - auto itemCharges = it.charges; + const auto itemCharges = it.charges; if (it.isFluidContainer() || it.isSplash()) { - auto fluidType = std::clamp<uint16_t>(itemCount, 1, FLUID_INK); + const auto fluidType = std::clamp<uint16_t>(itemCount, 1, FLUID_INK); setAttribute(ItemAttribute_t::FLUIDTYPE, fluidType); } else if (it.stackable) { if (itemCount != 0) { @@ -226,7 +226,7 @@ Item::Item(const std::shared_ptr<Item> &i) : } std::shared_ptr<Item> Item::clone() const { - const auto item = Item::CreateItem(id, count); + const auto &item = Item::CreateItem(id, count); if (item == nullptr) { g_logger().error("[{}] item is nullptr", __FUNCTION__); return nullptr; @@ -284,7 +284,7 @@ void Item::setDefaultSubtype() { setItemCount(1); - auto itemCharges = it.charges; + const auto itemCharges = it.charges; if (itemCharges != 0) { if (it.stackable) { setItemCount(static_cast<uint8_t>(itemCharges)); @@ -307,7 +307,7 @@ void Item::setID(uint16_t newid) { id = newid; const ItemType &it = Item::items[newid]; - uint32_t newDuration = it.decayTime * 1000; + const uint32_t newDuration = it.decayTime * 1000; if (newDuration == 0 && !it.stopTime && it.decayTo < 0) { // We'll get called startDecay anyway so let's schedule it - actually not in all casses @@ -342,8 +342,8 @@ bool Item::isOwner(uint32_t ownerId) const { } std::shared_ptr<Cylinder> Item::getTopParent() { - std::shared_ptr<Cylinder> aux = getParent(); - std::shared_ptr<Cylinder> prevaux = std::dynamic_pointer_cast<Cylinder>(shared_from_this()); + auto aux = getParent(); + auto prevaux = std::dynamic_pointer_cast<Cylinder>(shared_from_this()); if (!aux) { return prevaux; } @@ -360,7 +360,7 @@ std::shared_ptr<Cylinder> Item::getTopParent() { } std::shared_ptr<Tile> Item::getTile() { - std::shared_ptr<Cylinder> cylinder = getTopParent(); + auto cylinder = getTopParent(); // get root cylinder if (cylinder && cylinder->getParent()) { cylinder = cylinder->getParent(); @@ -381,7 +381,7 @@ uint16_t Item::getSubType() const { } std::shared_ptr<Player> Item::getHoldingPlayer() { - std::shared_ptr<Cylinder> p = getParent(); + auto p = getParent(); while (p) { if (p->getCreature()) { return p->getCreature()->getPlayer(); @@ -396,7 +396,7 @@ bool Item::isItemStorable() const { if (isStoreItem() || hasOwner()) { return false; } - auto isContainerAndHasSomethingInside = (getContainer() != nullptr) && (!getContainer()->getItemList().empty()); + const auto isContainerAndHasSomethingInside = (getContainer() != nullptr) && (!getContainer()->getItemList().empty()); return (isStowable() || isContainerAndHasSomethingInside); } @@ -845,7 +845,7 @@ Attr_ReadValue Item::readAttr(AttrTypes_t attr, PropStream &propStream) { bool Item::unserializeAttr(PropStream &propStream) { uint8_t attr_type; while (propStream.read<uint8_t>(attr_type) && attr_type != 0) { - Attr_ReadValue ret = readAttr(static_cast<AttrTypes_t>(attr_type), propStream); + const Attr_ReadValue ret = readAttr(static_cast<AttrTypes_t>(attr_type), propStream); if (ret == ATTR_READ_ERROR) { return false; } else if (ret == ATTR_READ_END) { @@ -861,7 +861,7 @@ bool Item::unserializeItemNode(OTB::Loader &, const OTB::Node &, PropStream &pro void Item::serializeAttr(PropWriteStream &propWriteStream) const { const ItemType &it = items[id]; - if (auto timeStamp = getAttribute<int64_t>(ItemAttribute_t::STORE)) { + if (const auto timeStamp = getAttribute<int64_t>(ItemAttribute_t::STORE)) { propWriteStream.write<uint8_t>(ATTR_STORE); propWriteStream.write<int64_t>(timeStamp); } @@ -870,13 +870,13 @@ void Item::serializeAttr(PropWriteStream &propWriteStream) const { propWriteStream.write<uint8_t>(getSubType()); } - if (auto charges = getAttribute<uint16_t>(ItemAttribute_t::CHARGES)) { + if (const auto charges = getAttribute<uint16_t>(ItemAttribute_t::CHARGES)) { propWriteStream.write<uint8_t>(ATTR_CHARGES); propWriteStream.write<uint16_t>(charges); } if (it.movable) { - if (auto actionId = getAttribute<uint16_t>(ItemAttribute_t::ACTIONID)) { + if (const auto actionId = getAttribute<uint16_t>(ItemAttribute_t::ACTIONID)) { propWriteStream.write<uint8_t>(ATTR_ACTION_ID); propWriteStream.write<uint16_t>(actionId); } @@ -910,7 +910,7 @@ void Item::serializeAttr(PropWriteStream &propWriteStream) const { propWriteStream.write<int32_t>(getDuration()); } - if (auto decayState = getDecaying(); + if (const auto decayState = getDecaying(); decayState == DECAYING_TRUE || decayState == DECAYING_PENDING) { propWriteStream.write<uint8_t>(ATTR_DECAYING_STATE); propWriteStream.write<uint8_t>(decayState); @@ -1061,7 +1061,7 @@ std::string Item::getOwnerName() const { return ""; } - auto creature = g_game().getCreatureByID(getOwnerId()); + const auto &creature = g_game().getCreatureByID(getOwnerId()); if (creature) { return creature->getName(); } @@ -1125,7 +1125,7 @@ void Item::checkDecayMapItemOnMove() { } uint32_t Item::getWeight() const { - uint32_t baseWeight = getBaseWeight(); + const uint32_t baseWeight = getBaseWeight(); if (isStackable()) { return baseWeight * std::max<uint32_t>(1, getItemCount()); } @@ -1929,7 +1929,7 @@ std::string Item::parseImbuementDescription(const std::shared_ptr<Item> &item) { continue; } - int minutes = imbuementInfo.duration / 60; + const int minutes = imbuementInfo.duration / 60; int hours = minutes / 60; s << fmt::format("{} {} {:02}:{:02}h", baseImbuement->name, imbuementInfo.imbuement->getName(), hours, minutes % 60); } @@ -1949,7 +1949,7 @@ SoundEffect_t Item::getMovementSound(const std::shared_ptr<Cylinder> &toCylinder return SoundEffect_t::ITEM_MOVE_DEFAULT; } - if (std::shared_ptr<Container> toContainer = toCylinder->getContainer(); + if (const auto &toContainer = toCylinder->getContainer(); toContainer && toContainer->getHoldingPlayer()) { return SoundEffect_t::ITEM_MOVE_BACKPACK; } @@ -2045,29 +2045,29 @@ std::string Item::parseShowDuration(const std::shared_ptr<Item> &item) { } std::ostringstream description; - uint32_t duration = item->getDuration() / 1000; + const uint32_t duration = item->getDuration() / 1000; if (item && item->hasAttribute(ItemAttribute_t::DURATION) && duration > 0) { description << " that will expire in "; if (duration >= 86400) { - uint16_t days = duration / 86400; - uint16_t hours = (duration % 86400) / 3600; + const uint16_t days = duration / 86400; + const uint16_t hours = (duration % 86400) / 3600; description << days << " day" << (days != 1 ? "s" : ""); if (hours > 0) { description << " and " << hours << " hour" << (hours != 1 ? "s" : ""); } } else if (duration >= 3600) { - uint16_t hours = duration / 3600; - uint16_t minutes = (duration % 3600) / 60; + const uint16_t hours = duration / 3600; + const uint16_t minutes = (duration % 3600) / 60; description << hours << " hour" << (hours != 1 ? "s" : ""); if (minutes > 0) { description << " and " << minutes << " minute" << (minutes != 1 ? "s" : ""); } } else if (duration >= 60) { - uint16_t minutes = duration / 60; + const uint16_t minutes = duration / 60; description << minutes << " minute" << (minutes != 1 ? "s" : ""); - uint16_t seconds = duration % 60; + const uint16_t seconds = duration % 60; if (seconds > 0) { description << " and " << seconds << " second" << (seconds != 1 ? "s" : ""); @@ -2089,7 +2089,7 @@ std::string Item::parseShowAttributesDescription(const std::shared_ptr<Item> &it if (itemType.armor != 0 || (item && item->getArmor() != 0) || itemType.showAttributes) { bool begin = itemType.isQuiver() ? false : true; - int32_t armor = (item ? item->getArmor() : itemType.armor); + const int32_t armor = (item ? item->getArmor() : itemType.armor); if (armor != 0) { if (begin) { itemDescription << " (Arm:" << armor; @@ -2116,7 +2116,7 @@ std::string Item::parseShowAttributesDescription(const std::shared_ptr<Item> &it } for (uint8_t i = SKILL_CRITICAL_HIT_CHANCE; i <= SKILL_LAST; i++) { - auto skill = item ? item->getSkill(static_cast<skills_t>(i)) : itemType.getSkill(static_cast<skills_t>(i)); + const auto skill = item ? item->getSkill(static_cast<skills_t>(i)) : itemType.getSkill(static_cast<skills_t>(i)); if (!skill) { continue; } @@ -2322,7 +2322,7 @@ std::string Item::getDescription(const ItemType &it, int32_t lookDistance, const if (it.isRune()) { if (it.runeLevel > 0 || it.runeMagLevel > 0) { - if (const auto rune = g_spells().getRuneSpell(it.id)) { + if (const auto &rune = g_spells().getRuneSpell(it.id)) { int32_t tmpSubType = subType; if (item) { tmpSubType = item->getSubType(); @@ -3142,7 +3142,7 @@ std::string Item::getWeightDescription(uint32_t weight) const { } std::string Item::getWeightDescription() const { - uint32_t weight = getWeight(); + const uint32_t weight = getWeight(); if (weight == 0) { return {}; } @@ -3228,9 +3228,9 @@ std::shared_ptr<Item> Item::transform(uint16_t itemId, uint16_t itemCount /*= -1 return nullptr; } - std::shared_ptr<Tile> fromTile = cylinder->getTile(); + const auto &fromTile = cylinder->getTile(); if (fromTile) { - auto it = g_game().browseFields.find(fromTile); + const auto it = g_game().browseFields.find(fromTile); if (it != g_game().browseFields.end() && it->second.lock() == cylinder) { cylinder = fromTile; } @@ -3243,8 +3243,8 @@ std::shared_ptr<Item> Item::transform(uint16_t itemId, uint16_t itemCount /*= -1 newItem = Item::CreateItem(itemId, itemCount); } - int32_t itemIndex = cylinder->getThingIndex(static_self_cast<Item>()); - auto duration = getDuration(); + const int32_t itemIndex = cylinder->getThingIndex(static_self_cast<Item>()); + const auto duration = getDuration(); if (duration > 0) { newItem->setDuration(duration); } @@ -3282,16 +3282,16 @@ bool Item::hasMarketAttributes() const { } bool Item::isInsideDepot(bool includeInbox /* = false*/) { - if (std::shared_ptr<Container> thisContainer = getContainer(); thisContainer && (thisContainer->getDepotLocker() || thisContainer->isDepotChest() || (includeInbox && thisContainer->isInbox()))) { + if (const auto &thisContainer = getContainer(); thisContainer && (thisContainer->getDepotLocker() || thisContainer->isDepotChest() || (includeInbox && thisContainer->isInbox()))) { return true; } - std::shared_ptr<Cylinder> cylinder = getParent(); + const auto &cylinder = getParent(); if (!cylinder) { return false; } - std::shared_ptr<Container> container = cylinder->getContainer(); + auto container = cylinder->getContainer(); if (!container) { return false; } @@ -3308,7 +3308,7 @@ bool Item::isInsideDepot(bool includeInbox /* = false*/) { } void Item::updateTileFlags() { - if (auto tile = getTile()) { + if (const auto &tile = getTile()) { tile->updateTileFlags(static_self_cast<Item>()); } } diff --git a/src/items/item.hpp b/src/items/item.hpp index e0ff92e2d85..671367f6ee6 100644 --- a/src/items/item.hpp +++ b/src/items/item.hpp @@ -56,7 +56,7 @@ class ItemProperties { return attributePtr->hasAttribute(type); } - void removeAttribute(ItemAttribute_t type) { + void removeAttribute(ItemAttribute_t type) const { if (attributePtr) { attributePtr->removeAttribute(type); } @@ -104,7 +104,7 @@ class ItemProperties { return !getCustomAttributeMap().empty(); } - bool removeCustomAttribute(const std::string &attributeName) { + bool removeCustomAttribute(const std::string &attributeName) const { if (!attributePtr) { return false; } @@ -117,7 +117,7 @@ class ItemProperties { } int32_t getDuration() const { - ItemDecayState_t decayState = getDecaying(); + const ItemDecayState_t decayState = getDecaying(); if (decayState == DECAYING_TRUE || decayState == DECAYING_STOPPING) { return std::max<int32_t>(0, getAttribute<int32_t>(ItemAttribute_t::DURATION_TIMESTAMP) - static_cast<int32_t>(OTSYS_TIME())); } else { @@ -265,7 +265,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { isLootTrackeable = value; } - bool getIsLootTrackeable() { + bool getIsLootTrackeable() const { return isLootTrackeable; } @@ -387,17 +387,17 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { } int32_t getSpeed() const { - int32_t value = items[id].getSpeed(); + const int32_t value = items[id].getSpeed(); return value; } int32_t getSkill(skills_t skill) const { - int32_t value = items[id].getSkill(skill); + const int32_t value = items[id].getSkill(skill); return value; } int32_t getStat(stats_t stat) const { - int32_t value = items[id].getStat(stat); + const int32_t value = items[id].getStat(stat); return value; } @@ -430,7 +430,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { } std::vector<std::shared_ptr<AugmentInfo>> getAugmentsBySpellNameAndType(const std::string &spellName, Augment_t augmentType) const { std::vector<std::shared_ptr<AugmentInfo>> augments; - for (auto &augment : items[id].augments) { + for (const auto &augment : items[id].augments) { if (strcasecmp(augment->spellName.c_str(), spellName.c_str()) == 0 && augment->type == augmentType) { augments.push_back(augment); } @@ -440,7 +440,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { } std::vector<std::shared_ptr<AugmentInfo>> getAugmentsBySpellName(const std::string &spellName) const { std::vector<std::shared_ptr<AugmentInfo>> augments; - for (auto &augment : items[id].augments) { + for (const auto &augment : items[id].augments) { if (strcasecmp(augment->spellName.c_str(), spellName.c_str()) == 0) { augments.push_back(augment); } @@ -612,7 +612,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { void addUniqueId(uint16_t uniqueId); void setDefaultDuration() { - uint32_t duration = getDefaultDuration(); + const uint32_t duration = getDefaultDuration(); if (duration != 0) { setDuration(duration); } @@ -659,7 +659,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { std::shared_ptr<Cylinder> getTopParent(); std::shared_ptr<Tile> getTile() override; bool isRemoved() override { - auto parent = getParent(); + const auto parent = getParent(); if (parent) { return parent->isRemoved(); } @@ -692,7 +692,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return setImbuement(slot, imbuementId, 0); } bool hasImbuementType(ImbuementTypes_t imbuementType, uint16_t imbuementTier) const { - auto it = items[id].imbuementTypes.find(imbuementType); + const auto it = items[id].imbuementTypes.find(imbuementType); if (it != items[id].imbuementTypes.end()) { return (it->second >= imbuementTier); } diff --git a/src/items/items.cpp b/src/items/items.cpp index 3d453901752..11a9471c859 100644 --- a/src/items/items.cpp +++ b/src/items/items.cpp @@ -59,8 +59,8 @@ LootTypeNames lootTypeNames = { { "unassigned", ITEM_TYPE_UNASSIGNED }, }; -ItemTypes_t Items::getLootType(const std::string &strValue) { - auto lootType = lootTypeNames.find(strValue); +ItemTypes_t Items::getLootType(const std::string &strValue) const { + const auto lootType = lootTypeNames.find(strValue); if (lootType != lootTypeNames.end()) { return lootType->second; } @@ -122,7 +122,7 @@ bool Items::reload() { void Items::loadFromProtobuf() { using namespace Canary::protobuf::appearances; - bool supportAnimation = g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__); + const bool supportAnimation = g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__); for (uint32_t it = 0; it < g_game().m_appearancesPtr->object_size(); ++it) { Appearance object = g_game().m_appearancesPtr->object(it); @@ -238,14 +238,14 @@ void Items::loadFromProtobuf() { bool Items::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/items/items.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/items/items.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; } - for (auto itemNode : doc.child("items").children()) { + for (const auto itemNode : doc.child("items").children()) { if (auto idAttribute = itemNode.attribute("id")) { parseItemNode(itemNode, pugi::cast<uint16_t>(idAttribute.value())); continue; @@ -266,7 +266,7 @@ bool Items::loadFromXml() { } auto id = pugi::cast<uint16_t>(fromIdAttribute.value()); - auto toId = pugi::cast<uint16_t>(toIdAttribute.value()); + const auto toId = pugi::cast<uint16_t>(toIdAttribute.value()); while (id <= toId) { parseItemNode(itemNode, id++); } @@ -282,7 +282,7 @@ void Items::buildInventoryList() { } } inventory.shrink_to_fit(); - std::sort(inventory.begin(), inventory.end()); + std::ranges::sort(inventory); } void Items::parseItemNode(const pugi::xml_node &itemNode, uint16_t id) { @@ -301,10 +301,10 @@ void Items::parseItemNode(const pugi::xml_node &itemNode, uint16_t id) { return; } - if (std::string xmlName = itemNode.attribute("name").as_string(); + if (const std::string xmlName = itemNode.attribute("name").as_string(); !xmlName.empty() && itemType.name != xmlName) { if (!itemType.name.empty()) { - if (auto it = std::find_if(nameToItems.begin(), nameToItems.end(), [id](const auto nameMapIt) { + if (const auto it = std::ranges::find_if(nameToItems, [id](const auto nameMapIt) { return nameMapIt.second == id; }); it != nameToItems.end()) { @@ -317,28 +317,28 @@ void Items::parseItemNode(const pugi::xml_node &itemNode, uint16_t id) { } itemType.loaded = true; - pugi::xml_attribute articleAttribute = itemNode.attribute("article"); + const pugi::xml_attribute articleAttribute = itemNode.attribute("article"); if (articleAttribute) { itemType.article = articleAttribute.as_string(); } - pugi::xml_attribute pluralAttribute = itemNode.attribute("plural"); + const pugi::xml_attribute pluralAttribute = itemNode.attribute("plural"); if (pluralAttribute) { itemType.pluralName = pluralAttribute.as_string(); } - for (auto attributeNode : itemNode.children()) { - pugi::xml_attribute keyAttribute = attributeNode.attribute("key"); + for (const auto &attributeNode : itemNode.children()) { + const pugi::xml_attribute keyAttribute = attributeNode.attribute("key"); if (!keyAttribute) { continue; } - pugi::xml_attribute valueAttribute = attributeNode.attribute("value"); + const pugi::xml_attribute valueAttribute = attributeNode.attribute("value"); if (!valueAttribute) { continue; } - std::string tmpStrValue = asLowerCaseString(keyAttribute.as_string()); + const std::string tmpStrValue = asLowerCaseString(keyAttribute.as_string()); auto parseAttribute = ItemParseAttributesMap.find(tmpStrValue); if (parseAttribute != ItemParseAttributesMap.end()) { ItemParse::initParse(tmpStrValue, attributeNode, valueAttribute, itemType); @@ -368,7 +368,7 @@ const ItemType &Items::getItemType(size_t id) const { } uint16_t Items::getItemIdByName(const std::string &name) { - auto result = nameToItems.find(asLowerCaseString(name)); + const auto result = nameToItems.find(asLowerCaseString(name)); if (result == nameToItems.end()) { return 0; diff --git a/src/items/items.hpp b/src/items/items.hpp index 11ef019de9f..531b4ed4959 100644 --- a/src/items/items.hpp +++ b/src/items/items.hpp @@ -416,7 +416,7 @@ class Items { uint16_t getItemIdByName(const std::string &name); - ItemTypes_t getLootType(const std::string &strValue); + ItemTypes_t getLootType(const std::string &strValue) const; bool loadFromXml(); void parseItemNode(const pugi::xml_node &itemNode, uint16_t id); @@ -455,7 +455,7 @@ class Items { Augment_t::StrongImpact, }; - return std::find(vector.begin(), vector.end(), augmentType) != vector.end(); + return std::ranges::find(vector, augmentType) != vector.end(); } private: diff --git a/src/items/items_classification.hpp b/src/items/items_classification.hpp index f3e783617a6..12a6e40e3d0 100644 --- a/src/items/items_classification.hpp +++ b/src/items/items_classification.hpp @@ -17,7 +17,7 @@ struct TierInfo { }; // Classification class for forging system and market. -class ItemClassification { +class ItemClassification final { public: ItemClassification() = default; explicit ItemClassification(uint8_t id) : @@ -33,5 +33,5 @@ class ItemClassification { } uint8_t id {}; - std::map<uint8_t, TierInfo> tiers; + std::map<uint8_t, TierInfo> tiers{}; }; diff --git a/src/items/items_definitions.hpp b/src/items/items_definitions.hpp index 0c8b62bd48c..073c06e1b74 100644 --- a/src/items/items_definitions.hpp +++ b/src/items/items_definitions.hpp @@ -629,7 +629,7 @@ struct AugmentInfo { AugmentInfo(std::string spellName, Augment_t type, int32_t value) : spellName(std::move(spellName)), type(type), value(value) { } - std::string spellName; + std::string spellName {}; Augment_t type; - int32_t value; + int32_t value {}; }; diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 4829e45bcc4..fdb0360a82c 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -74,7 +74,7 @@ bool Tile::hasProperty(const std::shared_ptr<Item> &exclude, ItemProperty prop) } if (const TileItemVector* items = getItemList()) { - for (auto &item : *items) { + for (const auto &item : *items) { if (!item) { g_logger().error("Tile::hasProperty: tile {} has an item which is nullptr", tilePos.toString()); continue; @@ -102,7 +102,7 @@ bool Tile::hasHeight(uint32_t n) const { } if (const TileItemVector* items = getItemList()) { - for (auto &item : *items) { + for (const auto &item : *items) { if (item->hasProperty(CONST_PROP_HASHEIGHT)) { ++height; } @@ -264,13 +264,13 @@ std::shared_ptr<Creature> Tile::getTopVisibleCreature(const std::shared_ptr<Crea return getTopCreature(); } - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (creature->canSeeCreature(tileCreature)) { return tileCreature; } } } else { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (!tileCreature->isInvisible()) { const auto &player = tileCreature->getPlayer(); if (!player || !player->isInGhostMode()) { @@ -368,9 +368,9 @@ std::shared_ptr<Thing> Tile::getTopVisibleThing(const std::shared_ptr<Creature> void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { if ((item->hasProperty(CONST_PROP_MOVABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { - auto it = g_game().browseFields.find(static_self_cast<Tile>()); + const auto it = g_game().browseFields.find(static_self_cast<Tile>()); if (it != g_game().browseFields.end()) { - auto lockedCylinder = it->second.lock(); + const auto &lockedCylinder = it->second.lock(); if (lockedCylinder) { lockedCylinder->addItemBack(item); item->setParent(getTile()); @@ -382,7 +382,7 @@ void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { const Position &cylinderMapPos = getPosition(); - auto spectators = Spectators().find<Creature>(cylinderMapPos, true); + const auto spectators = Spectators().find<Creature>(cylinderMapPos, true); // send to client for (const auto &spectator : spectators) { @@ -407,7 +407,7 @@ void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { if (getTopTopItem() && getTopTopItem()->canReceiveAutoCarpet()) { return; } - auto house = getHouse(); + const auto &house = getHouse(); if (!house) { return; } @@ -416,12 +416,12 @@ void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { if (!tile || !tile->getGround() || tile->getGround()->getID() != getGround()->getID()) { continue; } - auto topItem = tile->getTopTopItem(); + const auto &topItem = tile->getTopTopItem(); if (!topItem || !topItem->canReceiveAutoCarpet()) { continue; } // Check if tile is part of the same house - if (auto tileHouse = tile->getHouse(); !tileHouse || house != tileHouse) { + if (const auto &tileHouse = tile->getHouse(); !tileHouse || house != tileHouse) { continue; } @@ -432,7 +432,7 @@ void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { } } - auto carpet = item->clone(); + const auto &carpet = item->clone(); carpet->setAttribute(ItemAttribute_t::ACTIONID, IMMOVABLE_ACTION_ID); tile->addThing(carpet); } @@ -441,11 +441,11 @@ void Tile::onAddTileItem(const std::shared_ptr<Item> &item) { void Tile::onUpdateTileItem(const std::shared_ptr<Item> &oldItem, const ItemType &oldType, const std::shared_ptr<Item> &newItem, const ItemType &newType) { if ((newItem->hasProperty(CONST_PROP_MOVABLE) || newItem->getContainer()) || (newItem->isWrapable() && newItem->hasProperty(CONST_PROP_MOVABLE) && !oldItem->hasProperty(CONST_PROP_BLOCKPATH))) { - auto it = g_game().browseFields.find(getTile()); + const auto it = g_game().browseFields.find(getTile()); if (it != g_game().browseFields.end()) { - auto lockedCylinder = it->second.lock(); + const auto &lockedCylinder = it->second.lock(); if (lockedCylinder) { - int32_t index = lockedCylinder->getThingIndex(oldItem); + const int32_t index = lockedCylinder->getThingIndex(oldItem); if (index != -1) { lockedCylinder->replaceThing(index, newItem); newItem->setParent(static_self_cast<Tile>()); @@ -453,11 +453,12 @@ void Tile::onUpdateTileItem(const std::shared_ptr<Item> &oldItem, const ItemType } } } else if ((oldItem->hasProperty(CONST_PROP_MOVABLE) || oldItem->getContainer()) || (oldItem->isWrapable() && !oldItem->hasProperty(CONST_PROP_MOVABLE) && !oldItem->hasProperty(CONST_PROP_BLOCKPATH))) { - auto it = g_game().browseFields.find(getTile()); + const auto it = g_game().browseFields.find(getTile()); if (it != g_game().browseFields.end()) { - auto lockedCylinder = it->second.lock(); + const auto &lockedCylinder = it->second.lock(); if (lockedCylinder) { - std::shared_ptr<Cylinder> oldParent = oldItem->getParent(); + // TODO verificar + const auto &oldParent = oldItem->getParent(); lockedCylinder->removeThing(oldItem, oldItem->getItemCount()); oldItem->setParent(oldParent); } @@ -466,7 +467,7 @@ void Tile::onUpdateTileItem(const std::shared_ptr<Item> &oldItem, const ItemType const Position &cylinderMapPos = getPosition(); - auto spectators = Spectators().find<Creature>(cylinderMapPos, true); + const auto spectators = Spectators().find<Creature>(cylinderMapPos, true); // send to client for (const auto &spectator : spectators) { @@ -483,15 +484,15 @@ void Tile::onUpdateTileItem(const std::shared_ptr<Item> &oldItem, const ItemType void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector<int32_t> &oldStackPosVector, const std::shared_ptr<Item> &item) { if ((item->hasProperty(CONST_PROP_MOVABLE) || item->getContainer()) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) { - auto it = g_game().browseFields.find(getTile()); + const auto it = g_game().browseFields.find(getTile()); if (it != g_game().browseFields.end()) { - auto lockedCylinder = it->second.lock(); + const auto &lockedCylinder = it->second.lock(); if (lockedCylinder) { lockedCylinder->removeThing(item, item->getItemCount()); } } } - for (auto &zone : getZones()) { + for (const auto &zone : getZones()) { zone->itemRemoved(item); } @@ -503,7 +504,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< // send to client size_t i = 0; for (const std::shared_ptr<Creature> &spectator : spectators) { - if (std::shared_ptr<Player> tmpPlayer = spectator->getPlayer()) { + if (const auto &tmpPlayer = spectator->getPlayer()) { tmpPlayer->sendRemoveTileThing(cylinderMapPos, oldStackPosVector[i++]); } } @@ -514,7 +515,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< } if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES, __FUNCTION__)) { - auto items = getItemList(); + const auto items = getItemList(); if (!items || items->empty()) { g_game().removeTileToClean(static_self_cast<Tile>()); return; @@ -537,7 +538,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< if (getTopTopItem() && getTopTopItem()->canReceiveAutoCarpet()) { return; } - auto house = getHouse(); + const auto &house = getHouse(); if (!house) { return; } @@ -546,12 +547,12 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< if (!tile || !tile->getGround() || tile->getGround()->getID() != getGround()->getID()) { continue; } - auto topItem = tile->getTopTopItem(); + const auto &topItem = tile->getTopTopItem(); if (!topItem || !topItem->canReceiveAutoCarpet()) { continue; } // Check if tile is part of the same house - if (auto tileHouse = tile->getHouse(); !tileHouse || house != tileHouse) { + if (const auto &tileHouse = tile->getHouse(); !tileHouse || house != tileHouse) { continue; } @@ -568,7 +569,7 @@ void Tile::onUpdateTile(const CreatureVector &spectators) { const Position &cylinderMapPos = getPosition(); // send to clients - for (const std::shared_ptr<Creature> &spectator : spectators) { + for (const auto &spectator : spectators) { spectator->getPlayer()->sendUpdateTile(getTile(), cylinderMapPos); } } @@ -578,9 +579,9 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ return RETURNVALUE_NOERROR; } - if (auto creature = thing->getCreature()) { + if (const auto &creature = thing->getCreature()) { if (creature->getNpc()) { - ReturnValue returnValue = checkNpcCanWalkIntoTile(); + const ReturnValue returnValue = checkNpcCanWalkIntoTile(); if (returnValue != RETURNVALUE_NOERROR) { return returnValue; } @@ -594,7 +595,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ return RETURNVALUE_NOTPOSSIBLE; } - if (std::shared_ptr<Monster> monster = creature->getMonster()) { + if (const auto &monster = creature->getMonster()) { if (hasFlag(TILESTATE_PROTECTIONZONE | TILESTATE_FLOORCHANGE | TILESTATE_TELEPORT) && (!monster->isFamiliar() || (monster->isFamiliar() && monster->getMaster() && monster->getMaster()->getAttackedCreature()))) { return RETURNVALUE_NOTPOSSIBLE; } @@ -608,19 +609,19 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ const CreatureVector* creatures = getCreatures(); if (monster->canPushCreatures() && !monster->isSummon()) { if (creatures) { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (tileCreature->getPlayer() && tileCreature->getPlayer()->isInGhostMode()) { continue; } - std::shared_ptr<Monster> creatureMonster = tileCreature->getMonster(); + const auto &creatureMonster = tileCreature->getMonster(); if (!creatureMonster || !tileCreature->isPushable() || (creatureMonster->isSummon() && creatureMonster->getMaster()->getPlayer())) { return RETURNVALUE_NOTPOSSIBLE; } } } } else if (creatures && !creatures->empty()) { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (!tileCreature->isInGhostMode()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -642,7 +643,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ } if (hasHarmfulField()) { - CombatType_t combatType = getFieldItem()->getCombatType(); + const CombatType_t combatType = getFieldItem()->getCombatType(); // There is 3 options for a monster to enter a magic field // 1) Monster is immune @@ -665,7 +666,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ const CreatureVector* creatures = getCreatures(); if (const auto &player = creature->getPlayer()) { if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, tileFlags) && !player->isAccessPlayer()) { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (!player->canWalkthrough(tileCreature)) { return RETURNVALUE_NOTPOSSIBLE; } @@ -684,10 +685,10 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ const auto playerTile = player->getTile(); // moving from a pz tile to a non-pz tile if (playerTile && playerTile->hasFlag(TILESTATE_PROTECTIONZONE)) { - auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); + const auto maxOnline = g_configManager().getNumber(MAX_PLAYERS_PER_ACCOUNT, __FUNCTION__); if (maxOnline > 1 && player->getAccountType() < ACCOUNT_TYPE_GAMEMASTER && !hasFlag(TILESTATE_PROTECTIONZONE)) { - auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT, __FUNCTION__); - auto accountPlayers = g_game().getPlayersByAccount(player->getAccount()); + const auto maxOutsizePZ = g_configManager().getNumber(MAX_PLAYERS_OUTSIDE_PZ_PER_ACCOUNT, __FUNCTION__); + const auto accountPlayers = g_game().getPlayersByAccount(player->getAccount()); int countOutsizePZ = 0; for (const auto &accountPlayer : accountPlayers) { if (accountPlayer == player || accountPlayer->isOffline()) { @@ -720,7 +721,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ } } } else if (creatures && !creatures->empty() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, tileFlags)) { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (!tileCreature->isInGhostMode()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -733,7 +734,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ // NO PVP magic wall or wild growth field check if (creature && creature->getPlayer()) { if (const auto fieldList = getItemList()) { - for (auto &findfield : *fieldList) { + for (const auto &findfield : *fieldList) { if (findfield && (findfield->getID() == ITEM_WILDGROWTH_SAFE || findfield->getID() == ITEM_MAGICWALL_SAFE)) { if (!creature->isInGhostMode()) { g_game().internalRemoveItem(findfield, 1); @@ -755,7 +756,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ } if (const auto items = getItemList()) { - for (auto &item : *items) { + for (const auto &item : *items) { const ItemType &iiType = Item::items[item->getID()]; if (iiType.blockSolid && (!iiType.movable || item->hasAttribute(ItemAttribute_t::UNIQUEID))) { return RETURNVALUE_NOTPOSSIBLE; @@ -763,20 +764,20 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ } } } - } else if (auto item = thing->getItem()) { + } else if (const auto item = thing->getItem()) { const TileItemVector* items = getItemList(); if (items && items->size() >= 0x3E8) { return RETURNVALUE_NOTPOSSIBLE; } - bool itemIsHangable = item->isHangable(); + const bool itemIsHangable = item->isHangable(); if (ground == nullptr && !itemIsHangable) { return RETURNVALUE_NOTPOSSIBLE; } const CreatureVector* creatures = getCreatures(); if (creatures && !creatures->empty() && item->isBlocking() && !hasBitSet(FLAG_IGNOREBLOCKCREATURE, tileFlags)) { - for (auto &tileCreature : *creatures) { + for (const auto &tileCreature : *creatures) { if (!tileCreature->isInGhostMode()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -785,7 +786,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ if (itemIsHangable && hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { if (items) { - for (auto &tileItem : *items) { + for (const auto &tileItem : *items) { if (tileItem->isHangable()) { return RETURNVALUE_NEEDEXCHANGE; } @@ -808,7 +809,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_ } if (items) { - for (auto &tileItem : *items) { + for (const auto &tileItem : *items) { const ItemType &iiType = Item::items[tileItem->getID()]; if (!iiType.blockSolid || iiType.type == ITEM_TYPE_TRASHHOLDER) { continue; @@ -850,7 +851,7 @@ ReturnValue Tile::queryMaxCount(int32_t, const std::shared_ptr<Thing> &, uint32_ } ReturnValue Tile::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t tileFlags, const std::shared_ptr<Creature> & /*= nullptr */) { - int32_t index = getThingIndex(thing); + const int32_t index = getThingIndex(thing); if (index == -1) { return RETURNVALUE_NOTPOSSIBLE; } @@ -878,19 +879,19 @@ std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_pt if (hasFlag(TILESTATE_FLOORCHANGE_DOWN)) { uint16_t dx = tilePos.x; uint16_t dy = tilePos.y; - uint8_t dz = tilePos.z + 1; + const uint8_t dz = tilePos.z + 1; - std::shared_ptr<Tile> southDownTile = g_game().map.getTile(dx, dy - 1, dz); + const auto &southDownTile = g_game().map.getTile(dx, dy - 1, dz); if (southDownTile && southDownTile->hasFlag(TILESTATE_FLOORCHANGE_SOUTH_ALT)) { dy -= 2; destTile = g_game().map.getTile(dx, dy, dz); } else { - std::shared_ptr<Tile> eastDownTile = g_game().map.getTile(dx - 1, dy, dz); + const auto &eastDownTile = g_game().map.getTile(dx - 1, dy, dz); if (eastDownTile && eastDownTile->hasFlag(TILESTATE_FLOORCHANGE_EAST_ALT)) { dx -= 2; destTile = g_game().map.getTile(dx, dy, dz); } else { - std::shared_ptr<Tile> downTile = g_game().map.getTile(dx, dy, dz); + const auto &downTile = g_game().map.getTile(dx, dy, dz); if (downTile) { if (downTile->hasFlag(TILESTATE_FLOORCHANGE_NORTH)) { ++dy; @@ -923,7 +924,7 @@ std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_pt } else if (hasFlag(TILESTATE_FLOORCHANGE)) { uint16_t dx = tilePos.x; uint16_t dy = tilePos.y; - uint8_t dz = tilePos.z - 1; + const uint8_t dz = tilePos.z - 1; if (hasFlag(TILESTATE_FLOORCHANGE_NORTH)) { --dy; @@ -959,11 +960,11 @@ std::shared_ptr<Cylinder> Tile::queryDestination(int32_t &, const std::shared_pt } if (destTile) { - std::shared_ptr<Thing> destThing = destTile->getTopDownItem(); + const auto &destThing = destTile->getTopDownItem(); if (destThing) { destItem = destThing->getItem(); if (thing->getItem()) { - auto destCylinder = destThing->getCylinder(); + const auto &destCylinder = destThing->getCylinder(); if (destCylinder && !destCylinder->getContainer()) { return destThing->getCylinder(); } @@ -987,7 +988,7 @@ std::vector<std::shared_ptr<Tile>> Tile::getSurroundingTiles() { }; } -void Tile::addThing(std::shared_ptr<Thing> thing) { +void Tile::addThing(const std::shared_ptr<Thing> &thing) { addThing(0, thing); } @@ -1097,7 +1098,7 @@ void Tile::addThing(int32_t, const std::shared_ptr<Thing> &thing) { } void Tile::updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) { - int32_t index = getThingIndex(thing); + const int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1119,7 +1120,7 @@ void Tile::updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uin void Tile::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) { int32_t pos = index; - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -1139,7 +1140,7 @@ void Tile::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) { TileItemVector* items = getItemList(); if (items && !isInserted) { - int32_t topItemSize = getTopItemCount(); + const int32_t topItemSize = getTopItemCount(); if (pos < topItemSize) { auto it = items->getBeginTopItem(); it += pos; @@ -1153,7 +1154,7 @@ void Tile::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) { pos -= topItemSize; } - CreatureVector* creatures = getCreatures(); + const CreatureVector* creatures = getCreatures(); if (creatures) { if (!isInserted && pos < static_cast<int32_t>(creatures->size())) { return /*RETURNVALUE_NOTPOSSIBLE*/; @@ -1163,7 +1164,7 @@ void Tile::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) { } if (items && !isInserted) { - int32_t downItemSize = getDownItemCount(); + const int32_t downItemSize = getDownItemCount(); if (pos < downItemSize) { auto it = items->getBeginDownItem() + pos; oldItem = *it; @@ -1188,11 +1189,11 @@ void Tile::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) { } void Tile::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { - std::shared_ptr<Creature> creature = thing->getCreature(); + const auto &creature = thing->getCreature(); if (creature) { CreatureVector* creatures = getCreatures(); if (creatures) { - auto it = std::ranges::find(*creatures, thing); + const auto it = std::ranges::find(*creatures, thing); if (it != creatures->end()) { Spectators::clearCache(); creatures->erase(it); @@ -1201,12 +1202,12 @@ void Tile::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { return; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return; } - int32_t index = getThingIndex(item); + const int32_t index = getThingIndex(item); if (index == -1) { return; } @@ -1215,7 +1216,7 @@ void Tile::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { ground->resetParent(); ground = nullptr; - auto spectators = Spectators().find<Creature>(getPosition(), true); + const auto spectators = Spectators().find<Creature>(getPosition(), true); onRemoveTileItem(spectators.data(), std::vector<int32_t>(spectators.size(), 0), item); return; } @@ -1226,14 +1227,14 @@ void Tile::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { } if (item->isAlwaysOnTop()) { - auto it = std::find(items->getBeginTopItem(), items->getEndTopItem(), item); + const auto it = std::find(items->getBeginTopItem(), items->getEndTopItem(), item); if (it == items->getEndTopItem()) { return; } std::vector<int32_t> oldStackPosVector; - auto spectators = Spectators().find<Creature>(getPosition(), true); + const auto spectators = Spectators().find<Creature>(getPosition(), true); for (const auto &spectator : spectators) { if (const auto &tmpPlayer = spectator->getPlayer()) { oldStackPosVector.push_back(getStackposOfItem(tmpPlayer, item)); @@ -1244,14 +1245,14 @@ void Tile::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { items->erase(it); onRemoveTileItem(spectators.data(), oldStackPosVector, item); } else { - auto it = std::find(items->getBeginDownItem(), items->getEndDownItem(), item); + const auto it = std::find(items->getBeginDownItem(), items->getEndDownItem(), item); if (it == items->getEndDownItem()) { return; } const ItemType &itemType = Item::items[item->getID()]; if (itemType.stackable && count != item->getItemCount()) { - uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, static_cast<int32_t>(item->getItemCount() - count))); + const uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, static_cast<int32_t>(item->getItemCount() - count))); item->setItemCount(newCount); onUpdateTileItem(item, itemType, item, itemType); } else { @@ -1288,7 +1289,7 @@ int32_t Tile::getThingIndex(const std::shared_ptr<Thing> &thing) const { const TileItemVector* items = getItemList(); if (items) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item && item->isAlwaysOnTop()) { for (auto it = items->getBeginTopItem(), end = items->getEndTopItem(); it != end; ++it) { ++n; @@ -1303,7 +1304,7 @@ int32_t Tile::getThingIndex(const std::shared_ptr<Thing> &thing) const { if (const CreatureVector* creatures = getCreatures()) { if (thing->getCreature()) { - for (auto &creature : *creatures) { + for (const auto &creature : *creatures) { ++n; if (creature == thing) { return n; @@ -1315,7 +1316,7 @@ int32_t Tile::getThingIndex(const std::shared_ptr<Thing> &thing) const { } if (items) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item && !item->isAlwaysOnTop()) { for (auto it = items->getBeginDownItem(), end = items->getEndDownItem(); it != end; ++it) { ++n; @@ -1411,7 +1412,7 @@ int32_t Tile::getStackposOfItem(const std::shared_ptr<Player> &player, const std } if (const CreatureVector* creatures = getCreatures()) { - for (auto &creature : *creatures) { + for (const auto &creature : *creatures) { if (player->canSeeCreature(creature)) { if (++n >= 10) { return -1; @@ -1448,7 +1449,7 @@ uint32_t Tile::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) const const TileItemVector* items = getItemList(); if (items) { - for (auto &item : *items) { + for (const auto &item : *items) { if (item->getID() == itemId) { count += Item::countByType(item, subType); } @@ -1468,7 +1469,7 @@ std::shared_ptr<Thing> Tile::getThing(size_t index) const { const TileItemVector* items = getItemList(); if (items) { - uint32_t topItemSize = items->getTopItemCount(); + const uint32_t topItemSize = items->getTopItemCount(); if (index < topItemSize) { return items->at(items->getDownItemCount() + index); } @@ -1494,7 +1495,7 @@ void Tile::postAddNotification(const std::shared_ptr<Thing> &thing, const std::s } // add a reference to this item, it may be deleted after being added (mailbox for example) - std::shared_ptr<Creature> creature = thing->getCreature(); + const auto &creature = thing->getCreature(); std::shared_ptr<Item> item; if (creature) { item = nullptr; @@ -1504,17 +1505,17 @@ void Tile::postAddNotification(const std::shared_ptr<Thing> &thing, const std::s if (link == LINK_OWNER) { if (hasFlag(TILESTATE_TELEPORT)) { - std::shared_ptr<Teleport> teleport = getTeleportItem(); + const auto &teleport = getTeleportItem(); if (teleport) { teleport->addThing(thing); } } else if (hasFlag(TILESTATE_TRASHHOLDER)) { - std::shared_ptr<TrashHolder> trashholder = getTrashHolder(); + const auto &trashholder = getTrashHolder(); if (trashholder) { trashholder->addThing(thing); } } else if (hasFlag(TILESTATE_MAILBOX)) { - std::shared_ptr<Mailbox> mailbox = getMailbox(); + const auto &mailbox = getMailbox(); if (mailbox) { mailbox->addThing(thing); } @@ -1562,13 +1563,13 @@ void Tile::internalAddThing(const std::shared_ptr<Thing> &thing) { return; } - if (auto house = thing->getTile()->getHouse()) { - if (const auto item = thing->getItem()) { + if (const auto &house = thing->getTile()->getHouse()) { + if (const auto &item = thing->getItem()) { if (item->getParent().get() != this) { return; } - std::shared_ptr<Door> door = item->getDoor(); + const auto &door = item->getDoor(); if (door && door->getDoorId() != 0) { house->addDoor(door); } @@ -1586,14 +1587,14 @@ void Tile::internalAddThing(uint32_t, const std::shared_ptr<Thing> &thing) { thing->setParent(getTile()); - std::shared_ptr<Creature> creature = thing->getCreature(); + const auto &creature = thing->getCreature(); if (creature) { Spectators::clearCache(); CreatureVector* creatures = makeCreatures(); creatures->insert(creatures->begin(), creature); } else { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return; } @@ -1817,7 +1818,7 @@ std::shared_ptr<Item> Tile::getUseItem(int32_t index) const { return ground; } - if (std::shared_ptr<Thing> thing = getThing(index)) { + if (const auto &thing = getThing(index)) { return thing->getItem(); } @@ -1831,7 +1832,7 @@ std::shared_ptr<Item> Tile::getDoorItem() const { } if (items) { - for (auto &item : *items) { + for (const auto &item : *items) { const ItemType &it = Item::items[item->getID()]; if (it.isDoor()) { return item; diff --git a/src/items/tile.hpp b/src/items/tile.hpp index af9d7578546..3bd0017ed38 100644 --- a/src/items/tile.hpp +++ b/src/items/tile.hpp @@ -214,7 +214,7 @@ class Tile : public Cylinder, public SharedObject { std::vector<std::shared_ptr<Tile>> getSurroundingTiles(); - void addThing(std::shared_ptr<Thing> thing) final; + void addThing(const std::shared_ptr<Thing> &thing) final; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateTileFlags(const std::shared_ptr<Item> &item); diff --git a/src/items/trashholder.cpp b/src/items/trashholder.cpp index 1a0d89b5bbb..203bf65b4f8 100644 --- a/src/items/trashholder.cpp +++ b/src/items/trashholder.cpp @@ -36,7 +36,7 @@ std::shared_ptr<Cylinder> TrashHolder::queryDestination(int32_t &, const std::sh return static_self_cast<TrashHolder>(); } -void TrashHolder::addThing(std::shared_ptr<Thing> thing) { +void TrashHolder::addThing(const std::shared_ptr<Thing> &thing) { return addThing(0, thing); } @@ -56,7 +56,7 @@ void TrashHolder::addThing(int32_t, const std::shared_ptr<Thing> &thing) { const ItemType &it = Item::items[id]; if (item->isHangable() && it.isGroundTile()) { - std::shared_ptr<Tile> tile = std::dynamic_pointer_cast<Tile>(getParent()); + const std::shared_ptr<Tile> &tile = std::dynamic_pointer_cast<Tile>(getParent()); if (tile && tile->hasFlag(TILESTATE_SUPPORTS_HANGABLE)) { return; } diff --git a/src/items/trashholder.hpp b/src/items/trashholder.hpp index b9d1405f36b..049260c57e0 100644 --- a/src/items/trashholder.hpp +++ b/src/items/trashholder.hpp @@ -31,7 +31,7 @@ class TrashHolder final : public Item, public Cylinder { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; - void addThing(std::shared_ptr<Thing> thing) override; + void addThing(const std::shared_ptr<Thing> &thing) override; void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; diff --git a/src/kv/kv.cpp b/src/kv/kv.cpp index 29a9787f72f..8888826117a 100644 --- a/src/kv/kv.cpp +++ b/src/kv/kv.cpp @@ -21,12 +21,12 @@ KVStore &KVStore::getInstance() { } void KVStore::set(const std::string &key, const std::initializer_list<ValueWrapper> &init_list) { - ValueWrapper wrappedInitList(init_list); + const ValueWrapper wrappedInitList(init_list); set(key, wrappedInitList); } void KVStore::set(const std::string &key, const std::initializer_list<std::pair<const std::string, ValueWrapper>> &init_list) { - ValueWrapper wrappedInitList(init_list); + const ValueWrapper wrappedInitList(init_list); set(key, wrappedInitList); } @@ -37,7 +37,7 @@ void KVStore::set(const std::string &key, const ValueWrapper &value) { void KVStore::setLocked(const std::string &key, const ValueWrapper &value) { logger.trace("KVStore::set({})", key); - auto it = store_.find(key); + const auto it = store_.find(key); if (it != store_.end()) { it->second.first = value; lruQueue_.splice(lruQueue_.begin(), lruQueue_, it->second.second); diff --git a/src/kv/kv.hpp b/src/kv/kv.hpp index f645ce87fee..96980e38410 100644 --- a/src/kv/kv.hpp +++ b/src/kv/kv.hpp @@ -26,6 +26,7 @@ class KV : public std::enable_shared_from_this<KV> { public: + virtual ~KV() = default; virtual void set(const std::string &key, const std::initializer_list<ValueWrapper> &init_list) = 0; virtual void set(const std::string &key, const std::initializer_list<std::pair<const std::string, ValueWrapper>> &init_list) = 0; virtual void set(const std::string &key, const ValueWrapper &value) = 0; @@ -49,8 +50,8 @@ class KV : public std::enable_shared_from_this<KV> { static std::string generateUUID() { std::lock_guard<std::mutex> lock(mutex_); - auto now = std::chrono::system_clock::now().time_since_epoch(); - auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now).count(); + const auto now = std::chrono::system_clock::now().time_since_epoch(); + const auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(now).count(); if (milliseconds != lastTimestamp_) { counter_ = 0; @@ -141,7 +142,7 @@ class ScopedKV final : public KV { template <typename T> T get(const std::string &key, bool forceLoad = false) { - auto optValue = get(key, forceLoad); + const auto optValue = get(key, forceLoad); if (optValue.has_value()) { return optValue->get<T>(); } @@ -152,7 +153,7 @@ class ScopedKV final : public KV { return rootKV_.saveAll(); } - std::shared_ptr<KV> scoped(const std::string &scope) final { + std::shared_ptr<KV> scoped(const std::string &scope) override { logger.trace("ScopedKV::scoped({})", buildKey(scope)); return std::make_shared<ScopedKV>(logger, rootKV_, buildKey(scope)); } diff --git a/src/kv/kv_sql.cpp b/src/kv/kv_sql.cpp index 57d2cc57a10..23db45bc070 100644 --- a/src/kv/kv_sql.cpp +++ b/src/kv/kv_sql.cpp @@ -16,20 +16,20 @@ #include <kv.pb.h> std::optional<ValueWrapper> KVSQL::load(const std::string &key) { - auto query = fmt::format("SELECT `key_name`, `timestamp`, `value` FROM `kv_store` WHERE `key_name` = {}", db.escapeString(key)); - auto result = db.storeQuery(query); + const auto query = fmt::format("SELECT `key_name`, `timestamp`, `value` FROM `kv_store` WHERE `key_name` = {}", db.escapeString(key)); + const auto result = db.storeQuery(query); if (result == nullptr) { return std::nullopt; } unsigned long size; - auto data = result->getStream("value", size); + const auto data = result->getStream("value", size); if (data == nullptr) { return std::nullopt; } ValueWrapper valueWrapper; - auto timestamp = result->getNumber<uint64_t>("timestamp"); + const auto timestamp = result->getNumber<uint64_t>("timestamp"); Canary::protobuf::kv::ValueWrapper protoValue; if (protoValue.ParseFromArray(data, static_cast<int>(size))) { valueWrapper = ProtoSerializable::fromProto(protoValue, timestamp); @@ -42,8 +42,8 @@ std::optional<ValueWrapper> KVSQL::load(const std::string &key) { std::vector<std::string> KVSQL::loadPrefix(const std::string &prefix /* = ""*/) { std::vector<std::string> keys; std::string keySearch = db.escapeString(prefix + "%"); - auto query = fmt::format("SELECT `key_name` FROM `kv_store` WHERE `key_name` LIKE {}", keySearch); - auto result = db.storeQuery(query); + const auto query = fmt::format("SELECT `key_name` FROM `kv_store` WHERE `key_name` LIKE {}", keySearch); + const auto result = db.storeQuery(query); if (result == nullptr) { return keys; } @@ -63,14 +63,14 @@ bool KVSQL::save(const std::string &key, const ValueWrapper &value) { return update.execute(); } -bool KVSQL::prepareSave(const std::string &key, const ValueWrapper &value, DBInsert &update) { - auto protoValue = ProtoSerializable::toProto(value); +bool KVSQL::prepareSave(const std::string &key, const ValueWrapper &value, DBInsert &update) const { + const auto protoValue = ProtoSerializable::toProto(value); std::string data; if (!protoValue.SerializeToString(&data)) { return false; } if (value.isDeleted()) { - auto query = fmt::format("DELETE FROM `kv_store` WHERE `key_name` = {}", db.escapeString(key)); + const auto query = fmt::format("DELETE FROM `kv_store` WHERE `key_name` = {}", db.escapeString(key)); return db.executeQuery(query); } @@ -80,7 +80,7 @@ bool KVSQL::prepareSave(const std::string &key, const ValueWrapper &value, DBIns bool KVSQL::saveAll() { auto store = getStore(); - bool success = DBTransaction::executeWithinTransaction([this, &store]() { + const bool success = DBTransaction::executeWithinTransaction([this, &store]() { auto update = dbUpdate(); if (!std::ranges::all_of(store, [this, &update](const auto &kv) { const auto &[key, value] = kv; diff --git a/src/kv/kv_sql.hpp b/src/kv/kv_sql.hpp index 1d7a6387d68..602fe3d0e6c 100644 --- a/src/kv/kv_sql.hpp +++ b/src/kv/kv_sql.hpp @@ -28,9 +28,9 @@ class KVSQL final : public KVStore { std::vector<std::string> loadPrefix(const std::string &prefix = "") override; std::optional<ValueWrapper> load(const std::string &key) override; bool save(const std::string &key, const ValueWrapper &value) override; - bool prepareSave(const std::string &key, const ValueWrapper &value, DBInsert &update); + bool prepareSave(const std::string &key, const ValueWrapper &value, DBInsert &update) const; - DBInsert dbUpdate() { + DBInsert dbUpdate() const { auto insert = DBInsert("INSERT INTO `kv_store` (`key_name`, `timestamp`, `value`) VALUES"); insert.upsert({ "key_name", "timestamp", "value" }); return insert; diff --git a/src/kv/value_wrapper.cpp b/src/kv/value_wrapper.cpp index 2de2b290275..fbcb4350e15 100644 --- a/src/kv/value_wrapper.cpp +++ b/src/kv/value_wrapper.cpp @@ -41,7 +41,7 @@ ValueWrapper::ValueWrapper(const std::initializer_list<std::pair<const std::stri timestamp_(timestamp == 0 ? getTimeMsNow() : timestamp) { } std::optional<ValueWrapper> ValueWrapper::get(const std::string &key) const { - auto pval = std::get_if<MapType>(&data_); + const auto pval = std::get_if<MapType>(&data_); if (!pval) { return std::nullopt; } @@ -59,7 +59,7 @@ std::optional<ValueWrapper> ValueWrapper::get(const std::string &key) const { } std::optional<ValueWrapper> ValueWrapper::get(size_t index) const { - if (auto pval = std::get_if<ArrayType>(&data_)) { + if (const auto pval = std::get_if<ArrayType>(&data_)) { if (index < pval->size()) { return (*pval)[index]; } diff --git a/src/kv/value_wrapper_proto.cpp b/src/kv/value_wrapper_proto.cpp index 4362101957e..4456878753c 100644 --- a/src/kv/value_wrapper_proto.cpp +++ b/src/kv/value_wrapper_proto.cpp @@ -33,14 +33,14 @@ namespace ProtoHelpers { } void setProtoArrayValue(Canary::protobuf::kv::ValueWrapper &protoValue, const ArrayType &arg) { - auto arrayValue = protoValue.mutable_array_value(); + const auto arrayValue = protoValue.mutable_array_value(); for (const auto &elem : arg) { *arrayValue->add_values() = ProtoSerializable::toProto(elem); } } void setProtoMapValue(Canary::protobuf::kv::ValueWrapper &protoValue, const MapType &arg) { - auto mapValue = protoValue.mutable_map_value(); + const auto mapValue = protoValue.mutable_map_value(); for (const auto &[key, value] : arg) { auto* elem = mapValue->add_items(); elem->set_key(key); diff --git a/src/kv/value_wrapper_proto.hpp b/src/kv/value_wrapper_proto.hpp index 382b91a040b..9d5a61865ab 100644 --- a/src/kv/value_wrapper_proto.hpp +++ b/src/kv/value_wrapper_proto.hpp @@ -21,13 +21,9 @@ using MapType = phmap::flat_hash_map<std::string, std::shared_ptr<ValueWrapper>> using ValueVariant = std::variant<StringType, BooleanType, IntType, DoubleType, ArrayType, MapType>; // Forward declaration for protobuf class -namespace Canary { - namespace protobuf { - namespace kv { - class ValueWrapper; - } // namespace kv - } // namespace protobuf -} // namespace Canary +namespace Canary::protobuf::kv { + class ValueWrapper; +} struct ProtoSerializable { static Canary::protobuf::kv::ValueWrapper toProto(const ValueWrapper &obj); diff --git a/src/lib/di/runtime_provider.hpp b/src/lib/di/runtime_provider.hpp index 4a79ca95bec..70fad336e97 100644 --- a/src/lib/di/runtime_provider.hpp +++ b/src/lib/di/runtime_provider.hpp @@ -44,9 +44,9 @@ namespace extension { template <class T, class TInitialization, class TMemory, class... TArgs> auto get(const TInitialization &, const TMemory &, TArgs &&... args) const { - auto it = bindings_.find(std::type_index(typeid(T))); + const auto it = bindings_.find(std::type_index(typeid(T))); if (it == bindings_.end()) { - return get<T>(std::integral_constant < bool, !std::is_abstract<T>::value && std::is_constructible<T, TArgs...>::value > {}, std::forward<TArgs>(args)...); + return get<T>(std::integral_constant < bool, !std::is_abstract_v<T> && std::is_constructible_v<T, TArgs...> > {}, std::forward<TArgs>(args)...); } return static_cast<T*>(it->second()); } @@ -126,14 +126,14 @@ namespace extension { install(bindings); } - template <class T, std::enable_if_t<!std::is_base_of<core::injector_base, T>::value, int> = 0> + template <class T, std::enable_if_t<!std::is_base_of_v<core::injector_base, T>, int> = 0> void install(const T &binding) { this->cfg().bindings()[std::type_index(typeid(typename T::expected))] = [this, binding] { return make<typename T::given>(binding); }; } - template <class T, std::enable_if_t<std::is_base_of<core::injector_base, T>::value, int> = 0> + template <class T, std::enable_if_t<std::is_base_of_v<core::injector_base, T>, int> = 0> void install(const T &injector) { install(typename T::deps {}, injector, aux::identity<typename T::config> {}); } diff --git a/src/lib/metrics/metrics.hpp b/src/lib/metrics/metrics.hpp index 1e3dbe31086..9eda993992b 100644 --- a/src/lib/metrics/metrics.hpp +++ b/src/lib/metrics/metrics.hpp @@ -171,7 +171,7 @@ class ScopedLatency { explicit ScopedLatency([[maybe_unused]] std::string_view name, [[maybe_unused]] const std::string &histogramName, [[maybe_unused]] const std::string &scopeKey) {}; explicit ScopedLatency([[maybe_unused]] std::string_view name, [[maybe_unused]] std::set<double> &histogram, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}, [[maybe_unused]] const std::string &context = std::string()) {}; - void stop() {}; + void stop() const {}; ~ScopedLatency() = default; }; @@ -203,17 +203,17 @@ namespace metrics { Metrics() = default; ~Metrics() = default; - void init([[maybe_unused]] Options opts) {}; - void initHistograms() {}; - void shutdown() {}; + void init([[maybe_unused]] Options opts) const {}; + void initHistograms() const {}; + void shutdown() const {}; static Metrics &getInstance() { return inject<Metrics>(); }; - void addCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] double value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) { } + void addCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] double value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) const { } - void addUpDownCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] int value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) { } + void addUpDownCounter([[maybe_unused]] std::string_view name, [[maybe_unused]] int value, [[maybe_unused]] const std::map<std::string, std::string> &attrs = {}) const { } friend class ScopedLatency; }; diff --git a/src/lib/thread/thread_pool.cpp b/src/lib/thread/thread_pool.cpp index b2f51ef8f9d..0bfd6a63c61 100644 --- a/src/lib/thread/thread_pool.cpp +++ b/src/lib/thread/thread_pool.cpp @@ -30,7 +30,7 @@ ThreadPool::ThreadPool(Logger &logger) : start(); } -void ThreadPool::start() { +void ThreadPool::start() const { logger.info("Running with {} threads.", get_thread_count()); } diff --git a/src/lib/thread/thread_pool.hpp b/src/lib/thread/thread_pool.hpp index ea24d3486cb..e4f35af8bdb 100644 --- a/src/lib/thread/thread_pool.hpp +++ b/src/lib/thread/thread_pool.hpp @@ -19,7 +19,7 @@ class ThreadPool : public BS::thread_pool { ThreadPool(const ThreadPool &) = delete; ThreadPool operator=(const ThreadPool &) = delete; - void start(); + void start() const; void shutdown(); static int16_t getThreadId() { diff --git a/src/lua/callbacks/creaturecallback.cpp b/src/lua/callbacks/creaturecallback.cpp index 8461393e45d..21c4556cdfd 100644 --- a/src/lua/callbacks/creaturecallback.cpp +++ b/src/lua/callbacks/creaturecallback.cpp @@ -15,7 +15,7 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { } if (!LuaScriptInterface::reserveScriptEnv()) { - auto targetCreature = m_targetCreature.lock(); + const auto targetCreature = m_targetCreature.lock(); g_logger().error( "[CreatureCallback::startScriptInterface] - {} {} Call stack overflow. Too many lua script calls being nested.", getCreatureClass(targetCreature), @@ -35,9 +35,9 @@ bool CreatureCallback::startScriptInterface(int32_t scriptId) { } void CreatureCallback::pushSpecificCreature(const std::shared_ptr<Creature> &creature) { - if (std::shared_ptr<Npc> npc = creature->getNpc()) { + if (const auto &npc = creature->getNpc()) { LuaScriptInterface::pushUserdata<Npc>(L, npc); - } else if (std::shared_ptr<Monster> monster = creature->getMonster()) { + } else if (const auto &monster = creature->getMonster()) { LuaScriptInterface::pushUserdata<Monster>(L, monster); } else if (const auto &player = creature->getPlayer()) { LuaScriptInterface::pushUserdata<Player>(L, player); diff --git a/src/lua/callbacks/creaturecallback.hpp b/src/lua/callbacks/creaturecallback.hpp index 7d284623ee8..cb2e5c4c189 100644 --- a/src/lua/callbacks/creaturecallback.hpp +++ b/src/lua/callbacks/creaturecallback.hpp @@ -23,7 +23,7 @@ class CreatureCallback { void pushSpecificCreature(const std::shared_ptr<Creature> &creature); - bool persistLuaState() { + bool persistLuaState() const { return params > 0 && scriptInterface->callFunction(params); } diff --git a/src/lua/callbacks/event_callback.cpp b/src/lua/callbacks/event_callback.cpp index ea99635d7ab..9f13de52b07 100644 --- a/src/lua/callbacks/event_callback.cpp +++ b/src/lua/callbacks/event_callback.cpp @@ -228,7 +228,7 @@ void EventCallback::creatureOnDrainHealth(const std::shared_ptr<Creature> &creat } // Party -bool EventCallback::partyOnJoin(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) const { +bool EventCallback::partyOnJoin(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::partyOnJoin - " "Player {}] " @@ -243,7 +243,7 @@ bool EventCallback::partyOnJoin(std::shared_ptr<Party> party, const std::shared_ lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Party>(L, std::move(party)); + LuaScriptInterface::pushUserdata<Party>(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata<Player>(L, player); @@ -252,7 +252,7 @@ bool EventCallback::partyOnJoin(std::shared_ptr<Party> party, const std::shared_ return getScriptInterface()->callFunction(2); } -bool EventCallback::partyOnLeave(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) const { +bool EventCallback::partyOnLeave(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::partyOnLeave - " "Player {}] " @@ -267,7 +267,7 @@ bool EventCallback::partyOnLeave(std::shared_ptr<Party> party, const std::shared lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Party>(L, std::move(party)); + LuaScriptInterface::pushUserdata<Party>(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata<Player>(L, player); @@ -365,10 +365,10 @@ void EventCallback::playerOnLook(const std::shared_ptr<Player> &player, const Po LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - if (std::shared_ptr<Creature> creature = thing->getCreature()) { + if (const auto &creature = thing->getCreature()) { LuaScriptInterface::pushUserdata<Creature>(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - } else if (const auto item = thing->getItem()) { + } else if (const auto &item = thing->getItem()) { LuaScriptInterface::pushUserdata<Item>(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); } else { @@ -407,7 +407,7 @@ void EventCallback::playerOnLookInBattleList(const std::shared_ptr<Player> &play getScriptInterface()->callVoidFunction(3); } -void EventCallback::playerOnLookInTrade(const std::shared_ptr<Player> &player, std::shared_ptr<Player> partner, const std::shared_ptr<Item> &item, int32_t lookDistance) const { +void EventCallback::playerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::playerOnLookInTrade - " "Player {}] " @@ -425,7 +425,7 @@ void EventCallback::playerOnLookInTrade(const std::shared_ptr<Player> &player, s LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata<Player>(L, std::move(partner)); + LuaScriptInterface::pushUserdata<Player>(L, partner); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata<Item>(L, item); @@ -952,7 +952,7 @@ void EventCallback::playerOnInventoryUpdate(const std::shared_ptr<Player> &playe lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Player>(L, std::move(player)); + LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata<Item>(L, item); @@ -976,7 +976,7 @@ bool EventCallback::playerOnRotateItem(const std::shared_ptr<Player> &player, co lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Player>(L, std::move(player)); + LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata<Item>(L, item); @@ -987,7 +987,7 @@ bool EventCallback::playerOnRotateItem(const std::shared_ptr<Player> &player, co return getScriptInterface()->callFunction(3); } -void EventCallback::playerOnWalk(const std::shared_ptr<Player> &player, Direction &dir) const { +void EventCallback::playerOnWalk(const std::shared_ptr<Player> &player, const Direction &dir) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::eventOnWalk - " "Player {}] " @@ -1037,7 +1037,7 @@ void EventCallback::playerOnStorageUpdate(const std::shared_ptr<Player> &player, } // Monster -void EventCallback::monsterOnDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse) const { +void EventCallback::monsterOnDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::monsterOnDropLoot - " "Monster corpse {}] " @@ -1052,7 +1052,7 @@ void EventCallback::monsterOnDropLoot(std::shared_ptr<Monster> monster, const st lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Monster>(L, std::move(monster)); + LuaScriptInterface::pushUserdata<Monster>(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata<Container>(L, corpse); @@ -1061,7 +1061,7 @@ void EventCallback::monsterOnDropLoot(std::shared_ptr<Monster> monster, const st return getScriptInterface()->callVoidFunction(2); } -void EventCallback::monsterPostDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse) const { +void EventCallback::monsterPostDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("[EventCallback::monsterPostDropLoot - " "Monster corpse {}] " @@ -1076,7 +1076,7 @@ void EventCallback::monsterPostDropLoot(std::shared_ptr<Monster> monster, const lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Monster>(L, std::move(monster)); + LuaScriptInterface::pushUserdata<Monster>(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata<Container>(L, corpse); @@ -1085,7 +1085,7 @@ void EventCallback::monsterPostDropLoot(std::shared_ptr<Monster> monster, const return getScriptInterface()->callVoidFunction(2); } -void EventCallback::monsterOnSpawn(std::shared_ptr<Monster> monster, const Position &position) const { +void EventCallback::monsterOnSpawn(const std::shared_ptr<Monster> &monster, const Position &position) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" @@ -1100,7 +1100,7 @@ void EventCallback::monsterOnSpawn(std::shared_ptr<Monster> monster, const Posit lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Monster>(L, std::move(monster)); + LuaScriptInterface::pushUserdata<Monster>(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushPosition(L, position); @@ -1114,7 +1114,7 @@ void EventCallback::monsterOnSpawn(std::shared_ptr<Monster> monster, const Posit } // Npc -void EventCallback::npcOnSpawn(std::shared_ptr<Npc> npc, const Position &position) const { +void EventCallback::npcOnSpawn(const std::shared_ptr<Npc> &npc, const Position &position) const { if (!LuaScriptInterface::reserveScriptEnv()) { g_logger().error("{} - " "Position {}" @@ -1129,7 +1129,7 @@ void EventCallback::npcOnSpawn(std::shared_ptr<Npc> npc, const Position &positio lua_State* L = getScriptInterface()->getLuaState(); getScriptInterface()->pushFunction(getScriptId()); - LuaScriptInterface::pushUserdata<Npc>(L, std::move(npc)); + LuaScriptInterface::pushUserdata<Npc>(L, npc); LuaScriptInterface::setMetatable(L, -1, "Npc"); LuaScriptInterface::pushPosition(L, position); diff --git a/src/lua/callbacks/event_callback.hpp b/src/lua/callbacks/event_callback.hpp index bd45f82902f..038b540fd24 100644 --- a/src/lua/callbacks/event_callback.hpp +++ b/src/lua/callbacks/event_callback.hpp @@ -31,7 +31,7 @@ class Zone; * registration, and execution of custom behavior tied to specific game events. * @note It inherits from the Script class, providing scripting capabilities. */ -class EventCallback : public Script { +class EventCallback final : public Script { private: EventCallback_t m_callbackType = EventCallback_t::none; ///< The type of the event callback. std::string m_scriptTypeName; ///< The name associated with the script type. @@ -86,8 +86,8 @@ class EventCallback : public Script { void creatureOnDrainHealth(const std::shared_ptr<Creature> &creature, const std::shared_ptr<Creature> &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary) const; // Party - bool partyOnJoin(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) const; - bool partyOnLeave(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) const; + bool partyOnJoin(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) const; + bool partyOnLeave(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) const; bool partyOnDisband(const std::shared_ptr<Party> &party) const; void partyOnShareExperience(const std::shared_ptr<Party> &party, uint64_t &exp) const; @@ -95,7 +95,7 @@ class EventCallback : public Script { bool playerOnBrowseField(const std::shared_ptr<Player> &player, const Position &position) const; void playerOnLook(const std::shared_ptr<Player> &player, const Position &position, const std::shared_ptr<Thing> &thing, uint8_t stackpos, int32_t lookDistance) const; void playerOnLookInBattleList(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &creature, int32_t lookDistance) const; - void playerOnLookInTrade(const std::shared_ptr<Player> &player, std::shared_ptr<Player> partner, const std::shared_ptr<Item> &item, int32_t lookDistance) const; + void playerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance) const; bool playerOnLookInShop(const std::shared_ptr<Player> &player, const ItemType* itemType, uint8_t count) const; bool playerOnMoveItem(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr<Cylinder> &fromCylinder, const std::shared_ptr<Cylinder> &toCylinder) const; void playerOnItemMoved(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr<Cylinder> &fromCylinder, const std::shared_ptr<Cylinder> &toCylinder) const; @@ -116,15 +116,15 @@ class EventCallback : public Script { void playerOnCombat(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, CombatDamage &damage) const; void playerOnInventoryUpdate(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, Slots_t slot, bool equip) const; bool playerOnRotateItem(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const Position &position) const; - void playerOnWalk(const std::shared_ptr<Player> &player, Direction &dir) const; + void playerOnWalk(const std::shared_ptr<Player> &player, const Direction &dir) const; // Monster - void monsterOnDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse) const; - void monsterPostDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse) const; - void monsterOnSpawn(std::shared_ptr<Monster> monster, const Position &position) const; + void monsterOnDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse) const; + void monsterPostDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse) const; + void monsterOnSpawn(const std::shared_ptr<Monster> &monster, const Position &position) const; // Npc - void npcOnSpawn(std::shared_ptr<Npc> npc, const Position &position) const; + void npcOnSpawn(const std::shared_ptr<Npc> &npc, const Position &position) const; // Zone bool zoneBeforeCreatureEnter(const std::shared_ptr<Zone> &zone, const std::shared_ptr<Creature> &creature) const; diff --git a/src/lua/callbacks/events_callbacks.hpp b/src/lua/callbacks/events_callbacks.hpp index ecfe9cf635d..7ff2211e0b9 100644 --- a/src/lua/callbacks/events_callbacks.hpp +++ b/src/lua/callbacks/events_callbacks.hpp @@ -98,11 +98,11 @@ class EventsCallbacks { */ template <typename CallbackFunc, typename... Args> ReturnValue checkCallbackWithReturnValue(EventCallback_t eventType, CallbackFunc callbackFunc, Args &&... args) { - ReturnValue res = RETURNVALUE_NOERROR; + const ReturnValue res = RETURNVALUE_NOERROR; for (const auto &callback : getCallbacksByType(eventType)) { auto argsCopy = std::make_tuple(args...); if (callback && callback->isLoadedCallback()) { - ReturnValue callbackResult = std::apply( + const ReturnValue callbackResult = std::apply( [&callback, &callbackFunc](auto &&... args) { return ((*callback).*callbackFunc)(std::forward<decltype(args)>(args)...); }, @@ -130,7 +130,7 @@ class EventsCallbacks { for (const auto &callback : getCallbacksByType(eventType)) { auto argsCopy = std::make_tuple(args...); if (callback && callback->isLoadedCallback()) { - bool callbackResult = std::apply( + const bool callbackResult = std::apply( [&callback, &callbackFunc](auto &&... args) { return ((*callback).*callbackFunc)(std::forward<decltype(args)>(args)...); }, diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index f619e4cbe78..56a99781b68 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -169,7 +169,7 @@ bool Actions::registerLuaEvent(const std::shared_ptr<Action> &action) { return false; } -ReturnValue Actions::canUse(const std::shared_ptr<Player> &player, const Position &pos) { +ReturnValue Actions::canUse(const std::shared_ptr<Player> &player, const Position &pos) const { if (pos.x != 0xFFFF) { const Position &playerPos = player->getPosition(); if (playerPos.z != pos.z) { @@ -184,14 +184,14 @@ ReturnValue Actions::canUse(const std::shared_ptr<Player> &player, const Positio } ReturnValue Actions::canUse(const std::shared_ptr<Player> &player, const Position &pos, const std::shared_ptr<Item> &item) { - const std::shared_ptr<Action> action = getAction(item); + const auto &action = getAction(item); if (action != nullptr) { return action->canExecuteAction(player, pos); } return RETURNVALUE_NOERROR; } -ReturnValue Actions::canUseFar(const std::shared_ptr<Creature> &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) { +ReturnValue Actions::canUseFar(const std::shared_ptr<Creature> &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) const { if (toPos.x == 0xFFFF) { return RETURNVALUE_NOERROR; } @@ -214,27 +214,27 @@ ReturnValue Actions::canUseFar(const std::shared_ptr<Creature> &creature, const std::shared_ptr<Action> Actions::getAction(const std::shared_ptr<Item> &item) { if (item->hasAttribute(ItemAttribute_t::UNIQUEID)) { - auto it = uniqueItemMap.find(item->getAttribute<uint16_t>(ItemAttribute_t::UNIQUEID)); + const auto it = uniqueItemMap.find(item->getAttribute<uint16_t>(ItemAttribute_t::UNIQUEID)); if (it != uniqueItemMap.end()) { return it->second; } } if (item->hasAttribute(ItemAttribute_t::ACTIONID)) { - auto it = actionItemMap.find(item->getAttribute<uint16_t>(ItemAttribute_t::ACTIONID)); + const auto it = actionItemMap.find(item->getAttribute<uint16_t>(ItemAttribute_t::ACTIONID)); if (it != actionItemMap.end()) { return it->second; } } - auto it = useItemMap.find(item->getID()); + const auto it = useItemMap.find(item->getID()); if (it != useItemMap.end()) { return it->second; } - if (auto iteratePositions = actionPositionMap.find(item->getPosition()); + if (const auto iteratePositions = actionPositionMap.find(item->getPosition()); iteratePositions != actionPositionMap.end()) { - if (std::shared_ptr<Tile> tile = item->getTile(); + if (const auto &tile = item->getTile(); tile) { if (const auto &player = item->getHoldingPlayer(); player && item->getTopParent() == player) { @@ -251,7 +251,7 @@ std::shared_ptr<Action> Actions::getAction(const std::shared_ptr<Item> &item) { } ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, const Position &pos, uint8_t index, const std::shared_ptr<Item> &item, bool isHotkey) { - if (std::shared_ptr<Door> door = item->getDoor()) { + if (const auto &door = item->getDoor()) { if (!door->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } @@ -260,7 +260,7 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons auto itemId = item->getID(); const ItemType &itemType = Item::items[itemId]; auto transformTo = itemType.m_transformOnUse; - const std::shared_ptr<Action> action = getAction(item); + const auto &action = getAction(item); if (!action && transformTo > 0 && itemId != transformTo) { if (g_game().transformItem(item, transformTo) == nullptr) { g_logger().warn("[{}] item with id {} failed to transform to item {}", __FUNCTION__, itemId, transformTo); @@ -285,7 +285,7 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons } } - if (std::shared_ptr<BedItem> bed = item->getBed()) { + if (const auto &bed = item->getBed()) { if (!bed->canUse(player)) { return RETURNVALUE_CANNOTUSETHISOBJECT; } @@ -298,12 +298,12 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons return RETURNVALUE_NOERROR; } - if (std::shared_ptr<Container> container = item->getContainer()) { + if (const auto &container = item->getContainer()) { std::shared_ptr<Container> openContainer; // depot container - if (std::shared_ptr<DepotLocker> depot = container->getDepotLocker()) { - std::shared_ptr<DepotLocker> myDepotLocker = player->getDepotLocker(depot->getDepotId()); + if (const auto &depot = container->getDepotLocker()) { + const auto &myDepotLocker = player->getDepotLocker(depot->getDepotId()); myDepotLocker->setParent(depot->getParent()->getTile()); openContainer = myDepotLocker; player->setLastDepotId(depot->getDepotId()); @@ -317,7 +317,7 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons player->removeEmptyRewards(); } - std::shared_ptr<RewardChest> playerRewardChest = player->getRewardChest(); + const auto &playerRewardChest = player->getRewardChest(); if (playerRewardChest->empty()) { return RETURNVALUE_REWARDCHESTISEMPTY; } @@ -330,10 +330,10 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons openContainer = playerRewardChest; } - auto rewardId = container->getAttribute<time_t>(ItemAttribute_t::DATE); + const auto rewardId = container->getAttribute<time_t>(ItemAttribute_t::DATE); // Reward container proxy created when the boss dies if (container->getID() == ITEM_REWARD_CONTAINER && !container->getReward()) { - auto reward = player->getReward(rewardId, false); + const auto &reward = player->getReward(rewardId, false); if (!reward) { return RETURNVALUE_THISISIMPOSSIBLE; } @@ -344,13 +344,13 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons openContainer = reward; } - uint32_t corpseOwner = container->getCorpseOwner(); + const uint32_t corpseOwner = container->getCorpseOwner(); if (container->isRewardCorpse()) { // only players who participated in the fight can open the corpse if (player->getGroup()->id >= GROUP_TYPE_GAMEMASTER) { return RETURNVALUE_YOUCANTOPENCORPSEADM; } - auto reward = player->getReward(rewardId, false); + const auto &reward = player->getReward(rewardId, false); if (!reward) { return RETURNVALUE_YOUARENOTTHEOWNER; } @@ -362,7 +362,7 @@ ReturnValue Actions::internalUseItem(const std::shared_ptr<Player> &player, cons } // open/close container - int32_t oldContainerId = player->getContainerID(openContainer); + const int32_t oldContainerId = player->getContainerID(openContainer); if (oldContainerId != -1) { player->onCloseContainer(openContainer); player->closeContainer(oldContainerId); @@ -399,11 +399,11 @@ bool Actions::useItem(const std::shared_ptr<Player> &player, const Position &pos } } if (isHotkey) { - uint16_t subType = item->getSubType(); + const uint16_t subType = item->getSubType(); showUseHotkeyMessage(player, item, player->getItemTypeCount(item->getID(), subType != item->getItemCount() ? subType : -1)); } - ReturnValue ret = internalUseItem(player, pos, index, item, isHotkey); + const ReturnValue ret = internalUseItem(player, pos, index, item, isHotkey); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); return false; @@ -437,14 +437,14 @@ bool Actions::useItemEx(const std::shared_ptr<Player> &player, const Position &f return false; } - ReturnValue ret = action->canExecuteAction(player, toPos); + const ReturnValue ret = action->canExecuteAction(player, toPos); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); return false; } if (isHotkey) { - uint16_t subType = item->getSubType(); + const uint16_t subType = item->getSubType(); showUseHotkeyMessage(player, item, player->getItemTypeCount(item->getID(), subType != item->getItemCount() ? subType : -1)); } @@ -506,7 +506,7 @@ ReturnValue Action::canExecuteAction(const std::shared_ptr<Player> &player, cons return g_actions().canUseFar(player, toPos, checkLineOfSight, checkFloor); } -std::shared_ptr<Thing> Action::getTarget(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> targetCreature, const Position &toPosition, uint8_t toStackPos) const { +std::shared_ptr<Thing> Action::getTarget(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &targetCreature, const Position &toPosition, uint8_t toStackPos) const { if (targetCreature != nullptr) { return targetCreature; } diff --git a/src/lua/creature/actions.hpp b/src/lua/creature/actions.hpp index f03ee5950b6..ed5c6adc399 100644 --- a/src/lua/creature/actions.hpp +++ b/src/lua/creature/actions.hpp @@ -14,7 +14,7 @@ #include "lua/scripts/luascript.hpp" class Action; -class Position; +struct Position; class Action : public Script { public: @@ -102,7 +102,7 @@ class Action : public Script { return false; } - virtual std::shared_ptr<Thing> getTarget(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> targetCreature, const Position &toPosition, uint8_t toStackPos) const; + virtual std::shared_ptr<Thing> getTarget(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &targetCreature, const Position &toPosition, uint8_t toStackPos) const; private: std::string getScriptTypeName() const override { @@ -110,8 +110,8 @@ class Action : public Script { } std::function<bool( - const std::shared_ptr<Player> &player, std::shared_ptr<Item> item, - const Position &fromPosition, std::shared_ptr<Thing> target, + const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, + const Position &fromPosition, const std::shared_ptr<Thing> &target, const Position &toPosition, bool isHotkey )> useFunction = nullptr; @@ -146,9 +146,9 @@ class Actions final : public Scripts { bool useItem(const std::shared_ptr<Player> &player, const Position &pos, uint8_t index, const std::shared_ptr<Item> &item, bool isHotkey); bool useItemEx(const std::shared_ptr<Player> &player, const Position &fromPos, const Position &toPos, uint8_t toStackPos, const std::shared_ptr<Item> &item, bool isHotkey, const std::shared_ptr<Creature> &creature = nullptr); - ReturnValue canUse(const std::shared_ptr<Player> &player, const Position &pos); + ReturnValue canUse(const std::shared_ptr<Player> &player, const Position &pos) const; ReturnValue canUse(const std::shared_ptr<Player> &player, const Position &pos, const std::shared_ptr<Item> &item); - ReturnValue canUseFar(const std::shared_ptr<Creature> &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor); + ReturnValue canUseFar(const std::shared_ptr<Creature> &creature, const Position &toPos, bool checkLineOfSight, bool checkFloor) const; bool registerLuaItemEvent(const std::shared_ptr<Action> &action); bool registerLuaUniqueEvent(const std::shared_ptr<Action> &action); @@ -159,8 +159,8 @@ class Actions final : public Scripts { void clear(); private: - bool hasPosition(Position position) const { - if (auto it = actionPositionMap.find(position); + bool hasPosition(const Position &position) const { + if (const auto it = actionPositionMap.find(position); it != actionPositionMap.end()) { return true; } @@ -171,12 +171,12 @@ class Actions final : public Scripts { return actionPositionMap; } - void setPosition(Position position, std::shared_ptr<Action> action) { + void setPosition(const Position &position, const std::shared_ptr<Action> &action) { actionPositionMap.try_emplace(position, action); } bool hasItemId(uint16_t itemId) const { - if (auto it = useItemMap.find(itemId); + if (const auto it = useItemMap.find(itemId); it != useItemMap.end()) { return true; } @@ -188,7 +188,7 @@ class Actions final : public Scripts { } bool hasUniqueId(uint16_t uniqueId) const { - if (auto it = uniqueItemMap.find(uniqueId); + if (const auto it = uniqueItemMap.find(uniqueId); it != uniqueItemMap.end()) { return true; } @@ -200,7 +200,7 @@ class Actions final : public Scripts { } bool hasActionId(uint16_t actionId) const { - if (auto it = actionItemMap.find(actionId); + if (const auto it = actionItemMap.find(actionId); it != actionItemMap.end()) { return true; } diff --git a/src/lua/creature/creatureevent.cpp b/src/lua/creature/creatureevent.cpp index 7d6f620862c..3105f27af52 100644 --- a/src/lua/creature/creatureevent.cpp +++ b/src/lua/creature/creatureevent.cpp @@ -14,7 +14,7 @@ #include "creatures/players/player.hpp" void CreatureEvents::clear() { - for (auto &[name, event] : creatureEvents) { + for (const auto &[name, event] : creatureEvents) { event->clearEvent(); } } @@ -46,7 +46,7 @@ bool CreatureEvents::registerLuaEvent(const std::shared_ptr<CreatureEvent> &crea } std::shared_ptr<CreatureEvent> CreatureEvents::getEventByName(const std::string &name, bool forceLoaded /*= true*/) { - auto it = creatureEvents.find(name); + const auto it = creatureEvents.find(name); if (it != creatureEvents.end()) { if (!forceLoaded || it->second->isLoaded()) { return it->second; diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index e07121a9ec5..4aa4d7fbfda 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -23,8 +23,8 @@ Events::Events() : bool Events::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/events/events.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/events/events.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; @@ -33,18 +33,18 @@ bool Events::loadFromXml() { info = {}; phmap::flat_hash_set<std::string> classes; - for (auto eventNode : doc.child("events").children()) { + for (const auto &eventNode : doc.child("events").children()) { if (!eventNode.attribute("enabled").as_bool()) { continue; } const std::string &className = eventNode.attribute("class").as_string(); - auto res = classes.emplace(className); + const auto res = classes.emplace(className); if (res.second) { const std::string &lowercase = asLowerCaseString(className); const std::string &scriptName = lowercase + ".lua"; auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); - if (scriptInterface.loadFile(coreFolder + "/events/scripts/" + scriptName, scriptName) != 0) { + if (scriptInterface.loadFile(coreFolder + "/events/scripts/" += scriptName, scriptName) != 0) { g_logger().warn("{} - Can not load script: {}.lua", __FUNCTION__, lowercase); g_logger().warn(scriptInterface.getLastLuaError()); } @@ -152,7 +152,7 @@ bool Events::loadFromXml() { } // Monster -void Events::eventMonsterOnSpawn(std::shared_ptr<Monster> monster, const Position &position) { +void Events::eventMonsterOnSpawn(const std::shared_ptr<Monster> &monster, const Position &position) { // Monster:onSpawn(position) or Monster.onSpawn(self, position) if (info.monsterOnSpawn == -1) { return; @@ -172,7 +172,7 @@ void Events::eventMonsterOnSpawn(std::shared_ptr<Monster> monster, const Positio lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnSpawn); - LuaScriptInterface::pushUserdata<Monster>(L, std::move(monster)); + LuaScriptInterface::pushUserdata<Monster>(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushPosition(L, position); @@ -186,7 +186,7 @@ void Events::eventMonsterOnSpawn(std::shared_ptr<Monster> monster, const Positio } // Npc -void Events::eventNpcOnSpawn(std::shared_ptr<Npc> npc, const Position &position) { +void Events::eventNpcOnSpawn(const std::shared_ptr<Npc> &npc, const Position &position) { // Npc:onSpawn(position) or Npc.onSpawn(self, position) if (info.npcOnSpawn == -1) { return; @@ -206,7 +206,7 @@ void Events::eventNpcOnSpawn(std::shared_ptr<Npc> npc, const Position &position) lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.npcOnSpawn); - LuaScriptInterface::pushUserdata<Npc>(L, std::move(npc)); + LuaScriptInterface::pushUserdata<Npc>(L, npc); LuaScriptInterface::setMetatable(L, -1, "Npc"); LuaScriptInterface::pushPosition(L, position); @@ -423,7 +423,7 @@ void Events::eventCreatureOnDrainHealth(const std::shared_ptr<Creature> &creatur } // Party -bool Events::eventPartyOnJoin(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) { +bool Events::eventPartyOnJoin(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) { // Party:onJoin(player) or Party.onJoin(self, player) if (info.partyOnJoin == -1) { return true; @@ -443,7 +443,7 @@ bool Events::eventPartyOnJoin(std::shared_ptr<Party> party, const std::shared_pt lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.partyOnJoin); - LuaScriptInterface::pushUserdata<Party>(L, std::move(party)); + LuaScriptInterface::pushUserdata<Party>(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata<Player>(L, player); @@ -452,7 +452,7 @@ bool Events::eventPartyOnJoin(std::shared_ptr<Party> party, const std::shared_pt return scriptInterface.callFunction(2); } -bool Events::eventPartyOnLeave(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player) { +bool Events::eventPartyOnLeave(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player) { // Party:onLeave(player) or Party.onLeave(self, player) if (info.partyOnLeave == -1) { return true; @@ -472,7 +472,7 @@ bool Events::eventPartyOnLeave(std::shared_ptr<Party> party, const std::shared_p lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.partyOnLeave); - LuaScriptInterface::pushUserdata<Party>(L, std::move(party)); + LuaScriptInterface::pushUserdata<Party>(L, party); LuaScriptInterface::setMetatable(L, -1, "Party"); LuaScriptInterface::pushUserdata<Player>(L, player); @@ -590,10 +590,10 @@ void Events::eventPlayerOnLook(const std::shared_ptr<Player> &player, const Posi LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - if (std::shared_ptr<Creature> creature = thing->getCreature()) { + if (const std::shared_ptr<Creature> &creature = thing->getCreature()) { LuaScriptInterface::pushUserdata<Creature>(L, creature); LuaScriptInterface::setCreatureMetatable(L, -1, creature); - } else if (const auto item = thing->getItem()) { + } else if (const auto &item = thing->getItem()) { LuaScriptInterface::pushUserdata<Item>(L, item); LuaScriptInterface::setItemMetatable(L, -1, item); } else { @@ -637,7 +637,7 @@ void Events::eventPlayerOnLookInBattleList(const std::shared_ptr<Player> &player scriptInterface.callVoidFunction(3); } -void Events::eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, std::shared_ptr<Player> partner, const std::shared_ptr<Item> &item, int32_t lookDistance) { +void Events::eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance) { // Player:onLookInTrade(partner, item, distance) or Player.onLookInTrade(self, partner, item, distance) if (info.playerOnLookInTrade == -1) { return; @@ -660,7 +660,7 @@ void Events::eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, std LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); - LuaScriptInterface::pushUserdata<Player>(L, std::move(partner)); + LuaScriptInterface::pushUserdata<Player>(L, partner); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata<Item>(L, item); @@ -1264,7 +1264,7 @@ void Events::eventPlayerOnInventoryUpdate(const std::shared_ptr<Player> &player, lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.playerOnInventoryUpdate); - LuaScriptInterface::pushUserdata<Player>(L, std::move(player)); + LuaScriptInterface::pushUserdata<Player>(L, player); LuaScriptInterface::setMetatable(L, -1, "Player"); LuaScriptInterface::pushUserdata<Item>(L, item); @@ -1308,7 +1308,7 @@ void Events::eventOnStorageUpdate(const std::shared_ptr<Player> &player, const u } // Monster -void Events::eventMonsterOnDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse) { +void Events::eventMonsterOnDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse) { // Monster:onDropLoot(corpse) if (info.monsterOnDropLoot == -1) { return; @@ -1328,7 +1328,7 @@ void Events::eventMonsterOnDropLoot(std::shared_ptr<Monster> monster, const std: lua_State* L = scriptInterface.getLuaState(); scriptInterface.pushFunction(info.monsterOnDropLoot); - LuaScriptInterface::pushUserdata<Monster>(L, std::move(monster)); + LuaScriptInterface::pushUserdata<Monster>(L, monster); LuaScriptInterface::setMetatable(L, -1, "Monster"); LuaScriptInterface::pushUserdata<Container>(L, corpse); diff --git a/src/lua/creature/events.hpp b/src/lua/creature/events.hpp index 17d2a73384f..d76503fe425 100644 --- a/src/lua/creature/events.hpp +++ b/src/lua/creature/events.hpp @@ -88,8 +88,8 @@ class Events { void eventCreatureOnDrainHealth(const std::shared_ptr<Creature> &creature, const std::shared_ptr<Creature> &attacker, CombatType_t &typePrimary, int32_t &damagePrimary, CombatType_t &typeSecondary, int32_t &damageSecondary, TextColor_t &colorPrimary, TextColor_t &colorSecondary); // Party - bool eventPartyOnJoin(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player); - bool eventPartyOnLeave(std::shared_ptr<Party> party, const std::shared_ptr<Player> &player); + bool eventPartyOnJoin(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player); + bool eventPartyOnLeave(const std::shared_ptr<Party> &party, const std::shared_ptr<Player> &player); bool eventPartyOnDisband(const std::shared_ptr<Party> &party); void eventPartyOnShareExperience(const std::shared_ptr<Party> &party, uint64_t &exp); @@ -97,7 +97,7 @@ class Events { bool eventPlayerOnBrowseField(const std::shared_ptr<Player> &player, const Position &position); void eventPlayerOnLook(const std::shared_ptr<Player> &player, const Position &position, const std::shared_ptr<Thing> &thing, uint8_t stackpos, int32_t lookDistance); void eventPlayerOnLookInBattleList(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &creature, int32_t lookDistance); - void eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, std::shared_ptr<Player> partner, const std::shared_ptr<Item> &item, int32_t lookDistance); + void eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance); bool eventPlayerOnLookInShop(const std::shared_ptr<Player> &player, const ItemType* itemType, uint8_t count); bool eventPlayerOnMoveItem(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr<Cylinder> &fromCylinder, const std::shared_ptr<Cylinder> &toCylinder); void eventPlayerOnItemMoved(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, uint16_t count, const Position &fromPosition, const Position &toPosition, const std::shared_ptr<Cylinder> &fromCylinder, const std::shared_ptr<Cylinder> &toCylinder); @@ -119,11 +119,11 @@ class Events { void eventPlayerOnInventoryUpdate(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, Slots_t slot, bool equip); // Monster - void eventMonsterOnDropLoot(std::shared_ptr<Monster> monster, const std::shared_ptr<Container> &corpse); - void eventMonsterOnSpawn(std::shared_ptr<Monster> monster, const Position &position); + void eventMonsterOnDropLoot(const std::shared_ptr<Monster> &monster, const std::shared_ptr<Container> &corpse); + void eventMonsterOnSpawn(const std::shared_ptr<Monster> &monster, const Position &position); // Monster - void eventNpcOnSpawn(std::shared_ptr<Npc> npc, const Position &position); + void eventNpcOnSpawn(const std::shared_ptr<Npc> &npc, const Position &position); private: LuaScriptInterface scriptInterface; diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index 47cf65a28c4..a14719fd6a6 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -188,7 +188,7 @@ std::shared_ptr<MoveEvent> MoveEvents::getEvent(const std::shared_ptr<Item> &ite if (item->hasAttribute(ItemAttribute_t::ACTIONID)) { const auto &it = actionIdMap.find(item->getAttribute<uint16_t>(ItemAttribute_t::ACTIONID)); if (it != actionIdMap.end()) { - std::list<std::shared_ptr<MoveEvent>> moveEventList = it->second.moveEvent[eventType]; + const std::list<std::shared_ptr<MoveEvent>> moveEventList = it->second.moveEvent[eventType]; for (const auto &moveEvent : moveEventList) { if ((moveEvent->getSlot() & slotp) != 0) { return moveEvent; @@ -199,7 +199,7 @@ std::shared_ptr<MoveEvent> MoveEvents::getEvent(const std::shared_ptr<Item> &ite const auto &it = itemIdMap.find(item->getID()); if (it != itemIdMap.end()) { - std::list<std::shared_ptr<MoveEvent>> &moveEventList = it->second.moveEvent[eventType]; + const std::list<std::shared_ptr<MoveEvent>> &moveEventList = it->second.moveEvent[eventType]; for (const auto &moveEvent : moveEventList) { if ((moveEvent->getSlot() & slotp) != 0) { return moveEvent; @@ -242,7 +242,7 @@ std::shared_ptr<MoveEvent> MoveEvents::getEvent(const std::shared_ptr<Item> &ite } bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, const Position &position, std::map<Position, MoveEventList> &moveListMap) const { - auto it = moveListMap.find(position); + const auto it = moveListMap.find(position); if (it == moveListMap.end()) { MoveEventList moveEventList; moveEventList.moveEvent[moveEvent->getEventType()].push_back(moveEvent); @@ -266,7 +266,7 @@ bool MoveEvents::registerEvent(const std::shared_ptr<MoveEvent> &moveEvent, cons } std::shared_ptr<MoveEvent> MoveEvents::getEvent(const std::shared_ptr<Tile> &tile, MoveEvent_t eventType) { - if (auto it = positionsMap.find(tile->getPosition()); + if (const auto it = positionsMap.find(tile->getPosition()); it != positionsMap.end()) { std::list<std::shared_ptr<MoveEvent>> &moveEventList = it->second.moveEvent[eventType]; if (!moveEventList.empty()) { @@ -287,19 +287,19 @@ uint32_t MoveEvents::onCreatureMove(const std::shared_ptr<Creature> &creature, c } for (size_t i = tile->getFirstIndex(), j = tile->getLastIndex(); i < j; ++i) { - std::shared_ptr<Thing> thing = tile->getThing(i); + const auto &thing = tile->getThing(i); if (!thing) { continue; } - std::shared_ptr<Item> tileItem = thing->getItem(); + const auto &tileItem = thing->getItem(); if (!tileItem) { continue; } moveEvent = getEvent(tileItem, eventType); if (moveEvent) { - auto step = moveEvent->fireStepEvent(creature, tileItem, pos); + const auto step = moveEvent->fireStepEvent(creature, tileItem, pos); // If there is any problem in the function, we will kill the loop if (step == 0) { break; @@ -311,7 +311,7 @@ uint32_t MoveEvents::onCreatureMove(const std::shared_ptr<Creature> &creature, c } uint32_t MoveEvents::onPlayerEquip(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, Slots_t slot, bool isCheck) { - const auto moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot); + const auto &moveEvent = getEvent(item, MOVE_EVENT_EQUIP, slot); if (!moveEvent) { return 1; } @@ -321,7 +321,7 @@ uint32_t MoveEvents::onPlayerEquip(const std::shared_ptr<Player> &player, const } uint32_t MoveEvents::onPlayerDeEquip(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, Slots_t slot) { - const auto moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot); + const auto &moveEvent = getEvent(item, MOVE_EVENT_DEEQUIP, slot); if (!moveEvent) { return 1; } @@ -354,19 +354,19 @@ uint32_t MoveEvents::onItemMove(const std::shared_ptr<Item> &item, const std::sh } for (size_t i = tile->getFirstIndex(), j = tile->getLastIndex(); i < j; ++i) { - std::shared_ptr<Thing> thing = tile->getThing(i); + const auto &thing = tile->getThing(i); if (!thing) { continue; } - std::shared_ptr<Item> tileItem = thing->getItem(); + const auto &tileItem = thing->getItem(); if (!tileItem) { continue; } moveEvent = getEvent(tileItem, eventType2); if (moveEvent) { - auto moveItem = moveEvent->fireAddRemItem(item, tileItem, tile->getPosition()); + const auto &moveItem = moveEvent->fireAddRemItem(item, tileItem, tile->getPosition()); // If there is any problem in the function, we will kill the loop if (moveItem == 0) { break; @@ -420,7 +420,7 @@ uint32_t MoveEvent::StepInField(const std::shared_ptr<Creature> &creature, const return 0; } - std::shared_ptr<MagicField> field = item->getMagicField(); + const auto &field = item->getMagicField(); if (field) { field->onStepInField(creature); return 1; @@ -439,8 +439,8 @@ uint32_t MoveEvent::AddItemField(const std::shared_ptr<Item> &item, const std::s return 0; } - if (std::shared_ptr<MagicField> field = item->getMagicField()) { - std::shared_ptr<Tile> tile = item->getTile(); + if (const auto &field = item->getMagicField()) { + const auto &tile = item->getTile(); if (tile == nullptr) { g_logger().debug("[MoveEvent::AddItemField] - Tile is nullptr"); return 0; @@ -521,12 +521,12 @@ uint32_t MoveEvent::EquipItem(const std::shared_ptr<MoveEvent> &moveEvent, const if (it.abilities) { if (it.abilities->invisible) { - std::shared_ptr<Condition> condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_INVISIBLE, -1, 0); + const auto &condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_INVISIBLE, -1, 0); player->addCondition(condition); } if (it.abilities->manaShield) { - std::shared_ptr<Condition> condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_MANASHIELD, -1, 0); + const auto &condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_MANASHIELD, -1, 0); player->addCondition(condition); } @@ -538,7 +538,7 @@ uint32_t MoveEvent::EquipItem(const std::shared_ptr<MoveEvent> &moveEvent, const player->sendIcons(); if (it.abilities->regeneration) { - std::shared_ptr<Condition> condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_REGENERATION, -1, 0); + const auto &condition = Condition::createCondition(static_cast<ConditionId_t>(slot), CONDITION_REGENERATION, -1, 0); if (it.abilities->getHealthGain() != 0) { condition->setParam(CONDITION_PARAM_HEALTHGAIN, it.abilities->getHealthGain()); @@ -687,7 +687,7 @@ bool MoveEvent::executeStep(const std::shared_ptr<Creature> &creature, const std // Check if the new position is the same as the old one // If it is, log a warning and either teleport the player to their temple position if item type is an teleport - auto fromPosition = creature->getLastPosition(); + const auto fromPosition = creature->getLastPosition(); if (const auto &player = creature->getPlayer(); item && fromPosition == pos && getEventType() == MOVE_EVENT_STEP_IN) { if (const ItemType &itemType = Item::items[item->getID()]; player && itemType.isTeleport()) { g_logger().warn("[{}] cannot teleport player: {}, to the same position: {} of fromPosition: {}", __FUNCTION__, player->getName(), pos.toString(), fromPosition.toString()); diff --git a/src/lua/creature/movement.hpp b/src/lua/creature/movement.hpp index 65fef34cb36..58f42296f40 100644 --- a/src/lua/creature/movement.hpp +++ b/src/lua/creature/movement.hpp @@ -46,7 +46,7 @@ class MoveEvents final : public Scripts { } bool hasPosition(Position position) const { - if (auto it = positionsMap.find(position); + if (const auto it = positionsMap.find(position); it != positionsMap.end()) { return true; } @@ -62,7 +62,7 @@ class MoveEvents final : public Scripts { } bool hasItemId(int32_t itemId) const { - if (auto it = itemIdMap.find(itemId); + if (const auto it = itemIdMap.find(itemId); it != itemIdMap.end()) { return true; } @@ -78,7 +78,7 @@ class MoveEvents final : public Scripts { } bool hasUniqueId(int32_t uniqueId) const { - if (auto it = uniqueIdMap.find(uniqueId); + if (const auto it = uniqueIdMap.find(uniqueId); it != uniqueIdMap.end()) { return true; } @@ -94,7 +94,7 @@ class MoveEvents final : public Scripts { } bool hasActionId(int32_t actionId) const { - if (auto it = actionIdMap.find(actionId); + if (const auto it = actionIdMap.find(actionId); it != actionIdMap.end()) { return true; } @@ -176,7 +176,7 @@ class MoveEvent final : public Script, public SharedObject { return vocEquipMap; } void addVocEquipMap(const std::string &vocName) { - uint16_t vocationId = g_vocations().getVocationId(vocName); + const uint16_t vocationId = g_vocations().getVocationId(vocName); if (vocationId != 65535) { vocEquipMap[vocationId] = true; } diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index c5c0081a96f..3e794e0e383 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -26,14 +26,14 @@ bool Raids::loadFromXml() { } pugi::xml_document doc; - auto folder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/raids.xml"; - pugi::xml_parse_result result = doc.load_file(folder.c_str()); + const auto folder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/raids.xml"; + const pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); return false; } - for (auto raidNode : doc.child("raids").children()) { + for (const auto &raidNode : doc.child("raids").children()) { std::string name, file; uint32_t interval, margin; @@ -115,14 +115,14 @@ void Raids::checkRaids() { return; } if (!getRunning()) { - uint64_t now = OTSYS_TIME(); + const uint64_t now = OTSYS_TIME(); for (auto it = raidList.begin(), end = raidList.end(); it != end; ++it) { const auto &raid = *it; if (now >= (getLastRaidEnd() + raid->getMargin())) { - auto roll = static_cast<uint32_t>(uniform_random(0, MAX_RAND_RANGE)); - auto required = static_cast<uint32_t>(MAX_RAND_RANGE * raid->getInterval()) / CHECK_RAIDS_INTERVAL; - auto shouldStart = required >= roll; + const auto roll = static_cast<uint32_t>(uniform_random(0, MAX_RAND_RANGE)); + const auto required = static_cast<uint32_t>(MAX_RAND_RANGE * raid->getInterval()) / CHECK_RAIDS_INTERVAL; + const auto shouldStart = required >= roll; if (shouldStart) { setRunning(raid); raid->startRaid(); @@ -163,7 +163,7 @@ bool Raids::reload() { return loadFromXml(); } -std::shared_ptr<Raid> Raids::getRaidByName(const std::string &name) { +std::shared_ptr<Raid> Raids::getRaidByName(const std::string &name) const { for (const auto &raid : raidList) { if (strcasecmp(raid->getName().c_str(), name.c_str()) == 0) { return raid; @@ -178,13 +178,13 @@ bool Raid::loadFromXml(const std::string &filename) { } pugi::xml_document doc; - pugi::xml_parse_result result = doc.load_file(filename.c_str()); + const pugi::xml_parse_result result = doc.load_file(filename.c_str()); if (!result) { printXMLError(__FUNCTION__, filename, result); return false; } - for (auto eventNode : doc.child("raid").children()) { + for (const auto &eventNode : doc.child("raid").children()) { std::shared_ptr<RaidEvent> event; if (strcasecmp(eventNode.name(), "announce") == 0) { event = std::make_shared<AnnounceEvent>(); @@ -235,7 +235,7 @@ void Raid::executeRaidEvent(const std::shared_ptr<RaidEvent> &raidEvent) { const auto newRaidEvent = getNextRaidEvent(); if (newRaidEvent) { - uint32_t ticks = static_cast<uint32_t>(std::max<int32_t>(RAID_MINTICKS, newRaidEvent->getDelay() - raidEvent->getDelay())); + const uint32_t ticks = static_cast<uint32_t>(std::max<int32_t>(RAID_MINTICKS, newRaidEvent->getDelay() - raidEvent->getDelay())); nextEventEvent = g_dispatcher().scheduleEvent( ticks, [this, newRaidEvent] { executeRaidEvent(newRaidEvent); }, __FUNCTION__ ); @@ -270,7 +270,7 @@ std::shared_ptr<RaidEvent> Raid::getNextRaidEvent() { } bool RaidEvent::configureRaidEvent(const pugi::xml_node &eventNode) { - pugi::xml_attribute delayAttribute = eventNode.attribute("delay"); + const pugi::xml_attribute delayAttribute = eventNode.attribute("delay"); if (!delayAttribute) { g_logger().error("{} - 'delay' tag missing", __FUNCTION__); return false; @@ -285,7 +285,7 @@ bool AnnounceEvent::configureRaidEvent(const pugi::xml_node &eventNode) { return false; } - pugi::xml_attribute messageAttribute = eventNode.attribute("message"); + const pugi::xml_attribute messageAttribute = eventNode.attribute("message"); if (!messageAttribute) { g_logger().error("{} - " "'message' tag missing for announce event", @@ -294,9 +294,9 @@ bool AnnounceEvent::configureRaidEvent(const pugi::xml_node &eventNode) { } message = messageAttribute.as_string(); - pugi::xml_attribute typeAttribute = eventNode.attribute("type"); + const pugi::xml_attribute typeAttribute = eventNode.attribute("type"); if (typeAttribute) { - std::string tmpStrValue = asLowerCaseString(typeAttribute.as_string()); + const std::string tmpStrValue = asLowerCaseString(typeAttribute.as_string()); if (tmpStrValue == "warning") { messageType = MESSAGE_GAME_HIGHLIGHT; } else if (tmpStrValue == "event") { @@ -376,7 +376,7 @@ bool SingleSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { } bool SingleSpawnEvent::executeEvent() { - std::shared_ptr<Monster> monster = Monster::createMonster(monsterName); + const auto &monster = Monster::createMonster(monsterName); if (!monster) { g_logger().error("{} - Cant create monster {}", __FUNCTION__, monsterName); return false; @@ -398,7 +398,7 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { pugi::xml_attribute attr; if ((attr = eventNode.attribute("radius"))) { - auto radius = pugi::cast<int32_t>(attr.value()); + const auto radius = pugi::cast<int32_t>(attr.value()); Position centerPos; if ((attr = eventNode.attribute("centerx"))) { @@ -492,7 +492,7 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { } } - for (auto monsterNode : eventNode.children()) { + for (const auto &monsterNode : eventNode.children()) { const char* name; if ((attr = monsterNode.attribute("name"))) { @@ -537,7 +537,7 @@ bool AreaSpawnEvent::configureRaidEvent(const pugi::xml_node &eventNode) { bool AreaSpawnEvent::executeEvent() { for (const MonsterSpawn &spawn : spawnMonsterList) { - uint32_t amount = uniform_random(spawn.minAmount, spawn.maxAmount); + const uint32_t amount = uniform_random(spawn.minAmount, spawn.maxAmount); for (uint32_t i = 0; i < amount; ++i) { std::shared_ptr<Monster> monster = Monster::createMonster(spawn.name); if (!monster) { @@ -547,7 +547,7 @@ bool AreaSpawnEvent::executeEvent() { bool success = false; for (int32_t tries = 0; tries < MAXIMUM_TRIES_PER_MONSTER; tries++) { - std::shared_ptr<Tile> tile = g_game().map.getTile(static_cast<uint16_t>(uniform_random(fromPos.x, toPos.x)), static_cast<uint16_t>(uniform_random(fromPos.y, toPos.y)), static_cast<uint8_t>(uniform_random(fromPos.z, toPos.z))); + const auto &tile = g_game().map.getTile(static_cast<uint16_t>(uniform_random(fromPos.x, toPos.x)), static_cast<uint16_t>(uniform_random(fromPos.y, toPos.y)), static_cast<uint8_t>(uniform_random(fromPos.z, toPos.z))); if (tile && !tile->isMovableBlocking() && !tile->hasFlag(TILESTATE_PROTECTIONZONE) && tile->getTopCreature() == nullptr && g_game().placeCreature(monster, tile->getPosition(), false, true)) { success = true; monster->setForgeMonster(false); @@ -567,7 +567,7 @@ bool ScriptEvent::configureRaidEvent(const pugi::xml_node &eventNode) { return false; } - pugi::xml_attribute scriptAttribute = eventNode.attribute("script"); + const pugi::xml_attribute scriptAttribute = eventNode.attribute("script"); if (!scriptAttribute) { g_logger().error("{} - " "No script file found for raid", diff --git a/src/lua/creature/raids.hpp b/src/lua/creature/raids.hpp index b7c9a368827..9220f87f48e 100644 --- a/src/lua/creature/raids.hpp +++ b/src/lua/creature/raids.hpp @@ -62,7 +62,7 @@ class Raids { running = newRunning; } - std::shared_ptr<Raid> getRaidByName(const std::string &name); + std::shared_ptr<Raid> getRaidByName(const std::string &name) const; uint64_t getLastRaidEnd() const { return lastRaidEnd; diff --git a/src/lua/creature/talkaction.cpp b/src/lua/creature/talkaction.cpp index 02b21ae7e6d..9bee0edadf9 100644 --- a/src/lua/creature/talkaction.cpp +++ b/src/lua/creature/talkaction.cpp @@ -26,28 +26,28 @@ bool TalkActions::registerLuaEvent(const TalkAction_ptr &talkAction) { } bool TalkActions::checkWord(const std::shared_ptr<Player> &player, SpeakClasses type, const std::string &words, const std::string_view &word, const TalkAction_ptr &talkActionPtr) const { - auto spacePos = std::ranges::find_if(words.begin(), words.end(), ::isspace); - std::string firstWord = words.substr(0, spacePos - words.begin()); + const auto spacePos = std::ranges::find_if(words.begin(), words.end(), ::isspace); + const std::string firstWord = words.substr(0, spacePos - words.begin()); // Check for exact equality from saying word and talkaction stored word if (firstWord != word) { return false; } - auto groupId = player->getGroup()->id; + const auto groupId = player->getGroup()->id; if (groupId < talkActionPtr->getGroupType()) { return false; } std::string param; - size_t wordPos = words.find(word); - size_t talkactionLength = word.length(); + const size_t wordPos = words.find(word); + const size_t talkactionLength = word.length(); if (wordPos != std::string::npos && wordPos + talkactionLength < words.length()) { param = words.substr(wordPos + talkactionLength); trim_left(param, ' '); } - std::string separator = talkActionPtr->getSeparator(); + const std::string separator = talkActionPtr->getSeparator(); if (separator != " ") { if (!param.empty()) { if (param != separator) { diff --git a/src/lua/creature/talkaction.hpp b/src/lua/creature/talkaction.hpp index 7b74c94b6b1..980651ddf25 100644 --- a/src/lua/creature/talkaction.hpp +++ b/src/lua/creature/talkaction.hpp @@ -21,7 +21,7 @@ class TalkAction; using TalkAction_ptr = std::shared_ptr<TalkAction>; -class TalkAction : public Script { +class TalkAction final : public Script { public: using Script::Script; diff --git a/src/lua/functions/core/core_functions.hpp b/src/lua/functions/core/core_functions.hpp index c6c14121b06..2a75d148c51 100644 --- a/src/lua/functions/core/core_functions.hpp +++ b/src/lua/functions/core/core_functions.hpp @@ -16,6 +16,12 @@ class CoreFunctions final : LuaScriptInterface { public: + explicit CoreFunctions(lua_State* L) : + LuaScriptInterface("CoreFunctions") { + init(L); + } + ~CoreFunctions() override = default; + static void init(lua_State* L) { CoreGameFunctions::init(L); CoreLibsFunctions::init(L); diff --git a/src/lua/functions/core/game/bank_functions.cpp b/src/lua/functions/core/game/bank_functions.cpp index 49aa78e0dcf..90285c7012a 100644 --- a/src/lua/functions/core/game/bank_functions.cpp +++ b/src/lua/functions/core/game/bank_functions.cpp @@ -5,31 +5,31 @@ int BankFunctions::luaBankCredit(lua_State* L) { // Bank.credit(playerOrGuild, amount) - auto bank = getBank(L, 1); + const auto &bank = getBank(L, 1); if (bank == nullptr) { reportErrorFunc("Bank is nullptr"); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 2); + const uint64_t amount = getNumber<uint64_t>(L, 2); pushBoolean(L, bank->credit(amount)); return 1; } int BankFunctions::luaBankDebit(lua_State* L) { // Bank.debit(playerOrGuild, amount) - auto bank = getBank(L, 1); + const auto &bank = getBank(L, 1); if (bank == nullptr) { reportErrorFunc("Bank is nullptr"); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 2); + const uint64_t amount = getNumber<uint64_t>(L, 2); pushBoolean(L, bank->debit(amount)); return 1; } int BankFunctions::luaBankBalance(lua_State* L) { // Bank.balance(playerOrGuild[, amount]]) - auto bank = getBank(L, 1); + const auto &bank = getBank(L, 1); if (bank == nullptr) { reportErrorFunc("Bank is nullptr"); return 1; @@ -38,55 +38,55 @@ int BankFunctions::luaBankBalance(lua_State* L) { lua_pushnumber(L, bank->balance()); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 2); + const uint64_t amount = getNumber<uint64_t>(L, 2); pushBoolean(L, bank->balance(amount)); return 1; } int BankFunctions::luaBankHasBalance(lua_State* L) { // Bank.hasBalance(playerOrGuild, amount) - auto bank = getBank(L, 1); + const auto &bank = getBank(L, 1); if (bank == nullptr) { reportErrorFunc("Bank is nullptr"); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 2); + const uint64_t amount = getNumber<uint64_t>(L, 2); pushBoolean(L, bank->hasBalance(amount)); return 1; } int BankFunctions::luaBankTransfer(lua_State* L) { // Bank.transfer(fromPlayerOrGuild, toPlayerOrGuild, amount) - auto source = getBank(L, 1); + const auto &source = getBank(L, 1); if (source == nullptr) { g_logger().debug("BankFunctions::luaBankTransfer: source is null"); reportErrorFunc("Bank is nullptr"); return 1; } - std::shared_ptr<Bank> destination = getBank(L, 2); + const auto &destination = getBank(L, 2); if (destination == nullptr) { g_logger().debug("BankFunctions::luaBankTransfer: destination is null"); reportErrorFunc("Bank is nullptr"); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 3); + const uint64_t amount = getNumber<uint64_t>(L, 3); pushBoolean(L, source->transferTo(destination, amount)); return 1; } int BankFunctions::luaBankTransferToGuild(lua_State* L) { // Bank.transfer(fromPlayerOrGuild, toGuild, amount) - auto source = getBank(L, 1); + const auto &source = getBank(L, 1); if (source == nullptr) { reportErrorFunc("Source is nullptr"); return 1; } - std::shared_ptr<Bank> destination = getBank(L, 2, true /* isGuild */); + const auto &destination = getBank(L, 2, true /* isGuild */); if (destination == nullptr) { reportErrorFunc("Destination is nullptr"); return 1; } - uint64_t amount = getNumber<uint64_t>(L, 3); + const uint64_t amount = getNumber<uint64_t>(L, 3); pushBoolean(L, source->transferTo(destination, amount)); return 1; } @@ -99,13 +99,13 @@ int BankFunctions::luaBankWithdraw(lua_State* L) { return 1; } - uint64_t amount = getNumber<uint64_t>(L, 2); + const uint64_t amount = getNumber<uint64_t>(L, 2); if (lua_gettop(L) == 2) { - const auto bank = std::make_shared<Bank>(player); + const auto &bank = std::make_shared<Bank>(player); pushBoolean(L, bank->withdraw(player, amount)); return 1; } - auto source = getBank(L, 3); + const auto &source = getBank(L, 3); if (source == nullptr) { reportErrorFunc("Source is nullptr"); return 1; @@ -121,7 +121,7 @@ int BankFunctions::luaBankDeposit(lua_State* L) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; } - const auto bank = std::make_shared<Bank>(player); + const auto &bank = std::make_shared<Bank>(player); uint64_t amount = 0; if (lua_isnumber(L, 2)) { @@ -134,7 +134,7 @@ int BankFunctions::luaBankDeposit(lua_State* L) { pushBoolean(L, g_game().removeMoney(player, amount) && bank->credit(amount)); return 1; } - auto destination = getBank(L, 3); + const auto &destination = getBank(L, 3); if (destination == nullptr) { reportErrorFunc("Destination is nullptr"); return 1; @@ -148,7 +148,7 @@ std::shared_ptr<Bank> BankFunctions::getBank(lua_State* L, int32_t arg, bool isG return std::make_shared<Bank>(getGuild(L, arg)); } if (isGuild) { - const auto guild = getGuild(L, arg, true); + const auto &guild = getGuild(L, arg, true); if (!guild) { return nullptr; } diff --git a/src/lua/functions/core/game/bank_functions.hpp b/src/lua/functions/core/game/bank_functions.hpp index db450f49469..f2a94a40435 100644 --- a/src/lua/functions/core/game/bank_functions.hpp +++ b/src/lua/functions/core/game/bank_functions.hpp @@ -15,6 +15,12 @@ class Bank; class BankFunctions final : LuaScriptInterface { public: + explicit BankFunctions(lua_State* L) : + LuaScriptInterface("BankFunctions") { + init(L); + } + ~BankFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "Bank"); registerMethod(L, "Bank", "credit", BankFunctions::luaBankCredit); diff --git a/src/lua/functions/core/game/config_functions.cpp b/src/lua/functions/core/game/config_functions.cpp index d0e77a69352..736ba02829d 100644 --- a/src/lua/functions/core/game/config_functions.cpp +++ b/src/lua/functions/core/game/config_functions.cpp @@ -37,7 +37,7 @@ void ConfigFunctions::init(lua_State* L) { } int ConfigFunctions::luaConfigManagerGetString(lua_State* L) { - auto key = getNumber<ConfigKey_t>(L, -1); + const auto key = getNumber<ConfigKey_t>(L, -1); if (!key) { reportErrorFunc("Wrong enum"); return 1; @@ -48,7 +48,7 @@ int ConfigFunctions::luaConfigManagerGetString(lua_State* L) { } int ConfigFunctions::luaConfigManagerGetNumber(lua_State* L) { - auto key = getNumber<ConfigKey_t>(L, -1); + const auto key = getNumber<ConfigKey_t>(L, -1); if (!key) { reportErrorFunc("Wrong enum"); return 1; @@ -59,7 +59,7 @@ int ConfigFunctions::luaConfigManagerGetNumber(lua_State* L) { } int ConfigFunctions::luaConfigManagerGetBoolean(lua_State* L) { - auto key = getNumber<ConfigKey_t>(L, -1); + const auto key = getNumber<ConfigKey_t>(L, -1); if (!key) { reportErrorFunc("Wrong enum"); return 1; @@ -70,7 +70,7 @@ int ConfigFunctions::luaConfigManagerGetBoolean(lua_State* L) { } int ConfigFunctions::luaConfigManagerGetFloat(lua_State* L) { - auto key = getNumber<ConfigKey_t>(L, -1); + const auto key = getNumber<ConfigKey_t>(L, -1); if (!key) { reportErrorFunc("Wrong enum"); return 1; diff --git a/src/lua/functions/core/game/config_functions.hpp b/src/lua/functions/core/game/config_functions.hpp index ae4952e9643..8ece9ada9f8 100644 --- a/src/lua/functions/core/game/config_functions.hpp +++ b/src/lua/functions/core/game/config_functions.hpp @@ -14,6 +14,12 @@ class ConfigFunctions final : LuaScriptInterface { public: + explicit ConfigFunctions(lua_State* L) : + LuaScriptInterface("ConfigFunctions") { + init(L); + } + ~ConfigFunctions() override = default; + static void init(lua_State* L); private: diff --git a/src/lua/functions/core/game/core_game_functions.hpp b/src/lua/functions/core/game/core_game_functions.hpp index 03bcc236daf..f5fe1c9da94 100644 --- a/src/lua/functions/core/game/core_game_functions.hpp +++ b/src/lua/functions/core/game/core_game_functions.hpp @@ -19,6 +19,12 @@ class CoreGameFunctions final : LuaScriptInterface { public: + explicit CoreGameFunctions(lua_State* L) : + LuaScriptInterface("CoreGameFunctions") { + init(L); + } + ~CoreGameFunctions() override = default; + static void init(lua_State* L) { ConfigFunctions::init(L); GameFunctions::init(L); diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index 036acc00cd9..c8fb678363b 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -40,7 +40,7 @@ int GameFunctions::luaGameCreateMonsterType(lua_State* L) { auto variant = getString(L, 2, ""); const auto alternateName = getString(L, 3, ""); std::set<std::string> names; - auto monsterType = std::make_shared<MonsterType>(name); + const auto monsterType = std::make_shared<MonsterType>(name); if (!monsterType) { lua_pushstring(L, "MonsterType is nullptr"); lua_error(L); @@ -89,12 +89,12 @@ int GameFunctions::luaGameCreateNpcType(lua_State* L) { int GameFunctions::luaGameGetSpectators(lua_State* L) { // Game.getSpectators(position[, multifloor = false[, onlyPlayer = false[, minRangeX = 0[, maxRangeX = 0[, minRangeY = 0[, maxRangeY = 0]]]]]]) const Position &position = getPosition(L, 1); - bool multifloor = getBoolean(L, 2, false); - bool onlyPlayers = getBoolean(L, 3, false); - auto minRangeX = getNumber<int32_t>(L, 4, 0); - auto maxRangeX = getNumber<int32_t>(L, 5, 0); - auto minRangeY = getNumber<int32_t>(L, 6, 0); - auto maxRangeY = getNumber<int32_t>(L, 7, 0); + const bool multifloor = getBoolean(L, 2, false); + const bool onlyPlayers = getBoolean(L, 3, false); + const auto minRangeX = getNumber<int32_t>(L, 4, 0); + const auto maxRangeX = getNumber<int32_t>(L, 5, 0); + const auto minRangeY = getNumber<int32_t>(L, 6, 0); + const auto maxRangeY = getNumber<int32_t>(L, 7, 0); Spectators spectators; @@ -125,10 +125,10 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { // Game.getBestiaryList([bool[string or BestiaryType_t]]) lua_newtable(L); int index = 0; - bool name = getBoolean(L, 2, false); + const bool name = getBoolean(L, 2, false); if (lua_gettop(L) <= 2) { - std::map<uint16_t, std::string> mtype_list = g_game().getBestiaryList(); + const std::map<uint16_t, std::string> mtype_list = g_game().getBestiaryList(); for (const auto &ita : mtype_list) { if (name) { pushString(L, ita.second); @@ -139,7 +139,7 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { } } else { if (isNumber(L, 2)) { - std::map<uint16_t, std::string> tmplist = g_iobestiary().findRaceByName("CANARY", false, getNumber<BestiaryType_t>(L, 2)); + const std::map<uint16_t, std::string> tmplist = g_iobestiary().findRaceByName("CANARY", false, getNumber<BestiaryType_t>(L, 2)); for (const auto &itb : tmplist) { if (name) { pushString(L, itb.second); @@ -149,7 +149,7 @@ int GameFunctions::luaGameGetBestiaryList(lua_State* L) { lua_rawseti(L, -2, ++index); } } else { - std::map<uint16_t, std::string> tmplist = g_iobestiary().findRaceByName(getString(L, 2)); + const std::map<uint16_t, std::string> tmplist = g_iobestiary().findRaceByName(getString(L, 2)); for (const auto &itc : tmplist) { if (name) { pushString(L, itc.second); @@ -269,7 +269,7 @@ int GameFunctions::luaGameGetGameState(lua_State* L) { int GameFunctions::luaGameSetGameState(lua_State* L) { // Game.setGameState(state) - GameState_t state = getNumber<GameState_t>(L, 1); + const GameState_t state = getNumber<GameState_t>(L, 1); g_game().setGameState(state); pushBoolean(L, true); return 1; @@ -283,7 +283,7 @@ int GameFunctions::luaGameGetWorldType(lua_State* L) { int GameFunctions::luaGameSetWorldType(lua_State* L) { // Game.setWorldType(type) - WorldType_t type = getNumber<WorldType_t>(L, 1); + const WorldType_t type = getNumber<WorldType_t>(L, 1); g_game().setWorldType(type); pushBoolean(L, true); return 1; @@ -291,7 +291,7 @@ int GameFunctions::luaGameSetWorldType(lua_State* L) { int GameFunctions::luaGameGetReturnMessage(lua_State* L) { // Game.getReturnMessage(value) - ReturnValue value = getNumber<ReturnValue>(L, 1); + const ReturnValue value = getNumber<ReturnValue>(L, 1); pushString(L, getReturnMessage(value)); return 1; } @@ -309,14 +309,14 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { } } - auto count = getNumber<int32_t>(L, 2, 1); + const auto count = getNumber<int32_t>(L, 2, 1); int32_t itemCount = 1; int32_t subType = 1; const ItemType &it = Item::items[itemId]; if (it.hasSubType()) { if (it.stackable) { - itemCount = std::ceil(count / (float_t)it.stackSize); + itemCount = std::ceil(count / static_cast<float_t>(it.stackSize)); } subType = count; @@ -329,7 +329,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { position = getPosition(L, 3); } - bool hasTable = itemCount > 1; + const bool hasTable = itemCount > 1; if (hasTable) { lua_newtable(L); } else if (itemCount == 0) { @@ -361,7 +361,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { return 1; } - ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT); + const ReturnValue ret = g_game().internalAddItem(tile, item, INDEX_WHEREEVER, FLAG_NOLIMIT); if (ret != RETURNVALUE_NOERROR) { if (!hasTable) { lua_pushnil(L); @@ -389,7 +389,7 @@ int GameFunctions::luaGameCreateItem(lua_State* L) { int GameFunctions::luaGameCreateContainer(lua_State* L) { // Game.createContainer(itemId, size[, position]) - uint16_t size = getNumber<uint16_t>(L, 2); + const uint16_t size = getNumber<uint16_t>(L, 2); uint16_t id; if (isNumber(L, 1)) { id = getNumber<uint16_t>(L, 1); @@ -409,7 +409,7 @@ int GameFunctions::luaGameCreateContainer(lua_State* L) { if (lua_gettop(L) >= 3) { const Position &position = getPosition(L, 3); - std::shared_ptr<Tile> tile = g_game().map.getTile(position); + const auto &tile = g_game().map.getTile(position); if (!tile) { lua_pushnil(L); return 1; @@ -443,8 +443,8 @@ int GameFunctions::luaGameCreateMonster(lua_State* L) { } const Position &position = getPosition(L, 2); - bool extended = getBoolean(L, 3, false); - bool force = getBoolean(L, 4, false); + const bool extended = getBoolean(L, 3, false); + const bool force = getBoolean(L, 4, false); if (g_game().placeCreature(monster, position, extended, force)) { g_events().eventMonsterOnSpawn(monster, position); g_callbacks().executeCallback(EventCallback_t::monsterOnSpawn, &EventCallback::monsterOnSpawn, monster, position); @@ -471,7 +471,7 @@ int GameFunctions::luaGameCreateMonster(lua_State* L) { int GameFunctions::luaGameGenerateNpc(lua_State* L) { // Game.generateNpc(npcName) - std::shared_ptr<Npc> npc = Npc::createNpc(getString(L, 1)); + const auto &npc = Npc::createNpc(getString(L, 1)); if (!npc) { lua_pushnil(L); return 1; @@ -484,15 +484,15 @@ int GameFunctions::luaGameGenerateNpc(lua_State* L) { int GameFunctions::luaGameCreateNpc(lua_State* L) { // Game.createNpc(npcName, position[, extended = false[, force = false]]) - std::shared_ptr<Npc> npc = Npc::createNpc(getString(L, 1)); + const auto &npc = Npc::createNpc(getString(L, 1)); if (!npc) { lua_pushnil(L); return 1; } const Position &position = getPosition(L, 2); - bool extended = getBoolean(L, 3, false); - bool force = getBoolean(L, 4, false); + const bool extended = getBoolean(L, 3, false); + const bool force = getBoolean(L, 4, false); if (g_game().placeCreature(npc, position, extended, force)) { pushUserdata<Npc>(L, npc); setMetatable(L, -1, "Npc"); @@ -538,7 +538,7 @@ int GameFunctions::luaGameGetBestiaryCharm(lua_State* L) { int GameFunctions::luaGameCreateBestiaryCharm(lua_State* L) { // Game.createBestiaryCharm(id) - if (const std::shared_ptr<Charm> charm = g_iobestiary().getBestiaryCharm(static_cast<charmRune_t>(getNumber<int8_t>(L, 1, 0)), true)) { + if (const std::shared_ptr<Charm> &charm = g_iobestiary().getBestiaryCharm(static_cast<charmRune_t>(getNumber<int8_t>(L, 1, 0)), true)) { pushUserdata<Charm>(L, charm); setMetatable(L, -1, "Charm"); } else { @@ -563,7 +563,7 @@ int GameFunctions::luaGameStartRaid(lua_State* L) { // Game.startRaid(raidName) const std::string &raidName = getString(L, 1); - const auto raid = g_game().raids.getRaidByName(raidName); + const auto &raid = g_game().raids.getRaidByName(raidName); if (!raid || !raid->isLoaded()) { lua_pushnumber(L, RETURNVALUE_NOSUCHRAIDEXISTS); return 1; @@ -585,14 +585,14 @@ int GameFunctions::luaGameGetClientVersion(lua_State* L) { lua_createtable(L, 0, 3); setField(L, "min", CLIENT_VERSION); setField(L, "max", CLIENT_VERSION); - std::string version = fmt::format("{}.{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER); + const std::string version = fmt::format("{}.{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER); setField(L, "string", version); return 1; } int GameFunctions::luaGameReload(lua_State* L) { // Game.reload(reloadType) - Reload_t reloadType = getNumber<Reload_t>(L, 1); + const Reload_t reloadType = getNumber<Reload_t>(L, 1); if (GameReload::getReloadNumber(reloadType) == GameReload::getReloadNumber(Reload_t::RELOAD_TYPE_NONE)) { reportErrorFunc("Reload type is none"); pushBoolean(L, false); @@ -612,14 +612,14 @@ int GameFunctions::luaGameReload(lua_State* L) { int GameFunctions::luaGameHasEffect(lua_State* L) { // Game.hasEffect(effectId) - uint16_t effectId = getNumber<uint16_t>(L, 1); + const uint16_t effectId = getNumber<uint16_t>(L, 1); pushBoolean(L, g_game().hasEffect(effectId)); return 1; } int GameFunctions::luaGameHasDistanceEffect(lua_State* L) { // Game.hasDistanceEffect(effectId) - uint16_t effectId = getNumber<uint16_t>(L, 1); + const uint16_t effectId = getNumber<uint16_t>(L, 1); pushBoolean(L, g_game().hasDistanceEffect(effectId)); return 1; } @@ -628,14 +628,14 @@ int GameFunctions::luaGameGetOfflinePlayer(lua_State* L) { // Game.getOfflinePlayer(name or id) std::shared_ptr<Player> player = nullptr; if (isNumber(L, 1)) { - uint32_t id = getNumber<uint32_t>(L, 1); + const uint32_t id = getNumber<uint32_t>(L, 1); if (id >= Player::getFirstID() && id <= Player::getLastID()) { player = g_game().getPlayerByID(id, true); } else { player = g_game().getPlayerByGUID(id, true); } } else if (isString(L, 1)) { - auto name = getString(L, 1); + const auto name = getString(L, 1); player = g_game().getPlayerByName(name, true); } if (!player) { @@ -650,8 +650,8 @@ int GameFunctions::luaGameGetOfflinePlayer(lua_State* L) { int GameFunctions::luaGameGetNormalizedPlayerName(lua_State* L) { // Game.getNormalizedPlayerName(name[, isNewName = false]) - auto name = getString(L, 1); - auto isNewName = getBoolean(L, 2, false); + const auto name = getString(L, 1); + const auto isNewName = getBoolean(L, 2, false); const auto &player = g_game().getPlayerByName(name, true, isNewName); if (player) { pushString(L, player->getName()); @@ -663,8 +663,8 @@ int GameFunctions::luaGameGetNormalizedPlayerName(lua_State* L) { int GameFunctions::luaGameGetNormalizedGuildName(lua_State* L) { // Game.getNormalizedGuildName(name) - auto name = getString(L, 1); - const auto guild = g_game().getGuildByName(name, true); + const auto name = getString(L, 1); + const auto &guild = g_game().getGuildByName(name, true); if (guild) { pushString(L, guild->getName()); } else { @@ -675,7 +675,7 @@ int GameFunctions::luaGameGetNormalizedGuildName(lua_State* L) { int GameFunctions::luaGameAddInfluencedMonster(lua_State* L) { // Game.addInfluencedMonster(monster) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -688,15 +688,15 @@ int GameFunctions::luaGameAddInfluencedMonster(lua_State* L) { int GameFunctions::luaGameRemoveInfluencedMonster(lua_State* L) { // Game.removeInfluencedMonster(monsterId) - uint32_t monsterId = getNumber<uint32_t>(L, 1); - auto create = getBoolean(L, 2, false); + const uint32_t monsterId = getNumber<uint32_t>(L, 1); + const auto create = getBoolean(L, 2, false); lua_pushnumber(L, g_game().removeInfluencedMonster(monsterId, create)); return 1; } int GameFunctions::luaGameGetInfluencedMonsters(lua_State* L) { // Game.getInfluencedMonsters() - const auto monsters = g_game().getInfluencedMonsters(); + const auto &monsters = g_game().getInfluencedMonsters(); lua_createtable(L, static_cast<int>(monsters.size()), 0); int index = 0; for (const auto &monsterId : monsters) { @@ -713,7 +713,7 @@ int GameFunctions::luaGameGetLadderIds(lua_State* L) { const auto &ladders = Item::items.getLadders(); lua_createtable(L, static_cast<int>(ladders.size()), 0); int index = 0; - for (const auto ladderId : ladders) { + for (const auto &ladderId : ladders) { ++index; lua_pushnumber(L, static_cast<lua_Number>(ladderId)); lua_rawseti(L, -2, index); @@ -743,23 +743,23 @@ int GameFunctions::luaGameGetDummies(lua_State* L) { int GameFunctions::luaGameMakeFiendishMonster(lua_State* L) { // Game.makeFiendishMonster(monsterId[default= 0]) - auto monsterId = getNumber<uint32_t>(L, 1, 0); - auto createForgeableMonsters = getBoolean(L, 2, false); + const auto monsterId = getNumber<uint32_t>(L, 1, 0); + const auto createForgeableMonsters = getBoolean(L, 2, false); lua_pushnumber(L, g_game().makeFiendishMonster(monsterId, createForgeableMonsters)); return 1; } int GameFunctions::luaGameRemoveFiendishMonster(lua_State* L) { // Game.removeFiendishMonster(monsterId) - uint32_t monsterId = getNumber<uint32_t>(L, 1); - auto create = getBoolean(L, 2, false); + const uint32_t monsterId = getNumber<uint32_t>(L, 1); + const auto create = getBoolean(L, 2, false); lua_pushnumber(L, g_game().removeFiendishMonster(monsterId, create)); return 1; } int GameFunctions::luaGameGetFiendishMonsters(lua_State* L) { // Game.getFiendishMonsters() - const auto monsters = g_game().getFiendishMonsters(); + const auto &monsters = g_game().getFiendishMonsters(); lua_createtable(L, static_cast<int>(monsters.size()), 0); int index = 0; @@ -794,7 +794,7 @@ int GameFunctions::luaGameGetTalkActions(lua_State* L) { int GameFunctions::luaGameGetEventCallbacks(lua_State* L) { lua_createtable(L, 0, 0); lua_pushcfunction(L, EventCallbackFunctions::luaEventCallbackLoad); - for (auto [value, name] : magic_enum::enum_entries<EventCallback_t>()) { + for (const auto &[value, name] : magic_enum::enum_entries<EventCallback_t>()) { if (value != EventCallback_t::none) { std::string methodName = magic_enum::enum_name(value).data(); lua_pushstring(L, methodName.c_str()); @@ -815,12 +815,12 @@ int GameFunctions::luaGameRegisterAchievement(lua_State* L) { return 1; } - uint16_t id = getNumber<uint16_t>(L, 1); - std::string name = getString(L, 2); - std::string description = getString(L, 3); - bool secret = getBoolean(L, 4); - uint8_t grade = getNumber<uint8_t>(L, 5); - uint8_t points = getNumber<uint8_t>(L, 6); + const uint16_t id = getNumber<uint16_t>(L, 1); + const std::string name = getString(L, 2); + const std::string description = getString(L, 3); + const bool secret = getBoolean(L, 4); + const uint8_t grade = getNumber<uint8_t>(L, 5); + const uint8_t points = getNumber<uint8_t>(L, 6); g_game().registerAchievement(id, name, description, secret, grade, points); pushBoolean(L, true); return 1; @@ -828,8 +828,8 @@ int GameFunctions::luaGameRegisterAchievement(lua_State* L) { int GameFunctions::luaGameGetAchievementInfoById(lua_State* L) { // Game.getAchievementInfoById(id) - uint16_t id = getNumber<uint16_t>(L, 1); - Achievement achievement = g_game().getAchievementById(id); + const uint16_t id = getNumber<uint16_t>(L, 1); + const Achievement achievement = g_game().getAchievementById(id); if (achievement.id == 0) { reportErrorFunc("Achievement id is wrong"); return 1; @@ -847,8 +847,8 @@ int GameFunctions::luaGameGetAchievementInfoById(lua_State* L) { int GameFunctions::luaGameGetAchievementInfoByName(lua_State* L) { // Game.getAchievementInfoByName(name) - std::string name = getString(L, 1); - Achievement achievement = g_game().getAchievementByName(name); + const std::string name = getString(L, 1); + const Achievement achievement = g_game().getAchievementByName(name); if (achievement.id == 0) { reportErrorFunc("Achievement name is wrong"); return 1; diff --git a/src/lua/functions/core/game/game_functions.hpp b/src/lua/functions/core/game/game_functions.hpp index 70e81061c9c..3c668c54fb4 100644 --- a/src/lua/functions/core/game/game_functions.hpp +++ b/src/lua/functions/core/game/game_functions.hpp @@ -13,6 +13,12 @@ class GameFunctions final : LuaScriptInterface { public: + explicit GameFunctions(lua_State* L) : + LuaScriptInterface("GameFunctions") { + init(L); + } + ~GameFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "Game"); diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 756883a9006..df861531764 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -32,15 +32,15 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { return 1; } - uint16_t itemId = getNumber<uint16_t>(L, 2); - auto count = getNumber<int32_t>(L, 3, 1); - bool canDropOnMap = getBoolean(L, 4, true); + const uint16_t itemId = getNumber<uint16_t>(L, 2); + const auto count = getNumber<int32_t>(L, 3, 1); + const bool canDropOnMap = getBoolean(L, 4, true); auto subType = getNumber<uint16_t>(L, 5, 1); const ItemType &it = Item::items[itemId]; int32_t itemCount; - auto parameters = lua_gettop(L); + const auto parameters = lua_gettop(L); if (parameters > 4) { // subtype already supplied, count then is the amount itemCount = std::max<int32_t>(1, count); @@ -61,7 +61,7 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { stackCount = it.stackSize; } - std::shared_ptr<Item> newItem = Item::CreateItem(itemId, stackCount); + const auto &newItem = Item::CreateItem(itemId, stackCount); if (!newItem) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -72,7 +72,7 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { subType -= stackCount; } - ReturnValue ret = g_game().internalPlayerAddItem(player, newItem, canDropOnMap); + const ReturnValue ret = g_game().internalPlayerAddItem(player, newItem, canDropOnMap); if (ret != RETURNVALUE_NOERROR) { pushBoolean(L, false); return 1; @@ -80,7 +80,7 @@ int GlobalFunctions::luaDoPlayerAddItem(lua_State* L) { if (--itemCount == 0) { if (newItem->getParent()) { - uint32_t uid = getScriptEnv()->addThing(newItem); + const uint32_t uid = getScriptEnv()->addThing(newItem); lua_pushnumber(L, uid); return 1; } else { @@ -103,7 +103,7 @@ int GlobalFunctions::luaIsValidUID(lua_State* L) { int GlobalFunctions::luaIsDepot(lua_State* L) { // isDepot(uid) - std::shared_ptr<Container> container = getScriptEnv()->getContainerByUID(getNumber<uint32_t>(L, -1)); + const auto &container = getScriptEnv()->getContainerByUID(getNumber<uint32_t>(L, -1)); pushBoolean(L, container && container->getDepotLocker()); return 1; } @@ -111,29 +111,29 @@ int GlobalFunctions::luaIsDepot(lua_State* L) { int GlobalFunctions::luaIsMovable(lua_State* L) { // isMovable(uid) // isMovable(uid) - std::shared_ptr<Thing> thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)); + const auto &thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)); pushBoolean(L, thing && thing->isPushable()); return 1; } int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { // doAddContainerItem(uid, itemid, <optional> count/subtype) - uint32_t uid = getNumber<uint32_t>(L, 1); + const uint32_t uid = getNumber<uint32_t>(L, 1); ScriptEnvironment* env = getScriptEnv(); - std::shared_ptr<Container> container = env->getContainerByUID(uid); + const auto &container = env->getContainerByUID(uid); if (!container) { reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND)); pushBoolean(L, false); return 1; } - uint16_t itemId = getNumber<uint16_t>(L, 2); + const uint16_t itemId = getNumber<uint16_t>(L, 2); const ItemType &it = Item::items[itemId]; int32_t itemCount = 1; int32_t subType = 1; - auto count = getNumber<uint32_t>(L, 3, 1); + const auto count = getNumber<uint32_t>(L, 3, 1); if (it.hasSubType()) { if (it.stackable) { @@ -146,8 +146,8 @@ int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { } while (itemCount > 0) { - int32_t stackCount = std::min<int32_t>(it.stackSize, subType); - std::shared_ptr<Item> newItem = Item::CreateItem(itemId, stackCount); + const int32_t stackCount = std::min<int32_t>(it.stackSize, subType); + const auto &newItem = Item::CreateItem(itemId, stackCount); if (!newItem) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -158,7 +158,7 @@ int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { subType -= stackCount; } - ReturnValue ret = g_game().internalAddItem(container, newItem); + const ReturnValue ret = g_game().internalAddItem(container, newItem); if (ret != RETURNVALUE_NOERROR) { pushBoolean(L, false); return 1; @@ -181,16 +181,16 @@ int GlobalFunctions::luaDoAddContainerItem(lua_State* L) { int GlobalFunctions::luaGetDepotId(lua_State* L) { // getDepotId(uid) - uint32_t uid = getNumber<uint32_t>(L, -1); + const uint32_t uid = getNumber<uint32_t>(L, -1); - std::shared_ptr<Container> container = getScriptEnv()->getContainerByUID(uid); + const auto &container = getScriptEnv()->getContainerByUID(uid); if (!container) { reportErrorFunc(getErrorDesc(LUA_ERROR_CONTAINER_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<DepotLocker> depotLocker = container->getDepotLocker(); + const auto &depotLocker = container->getDepotLocker(); if (!depotLocker) { reportErrorFunc("Depot not found"); pushBoolean(L, false); @@ -203,14 +203,14 @@ int GlobalFunctions::luaGetDepotId(lua_State* L) { int GlobalFunctions::luaGetWorldTime(lua_State* L) { // getWorldTime() - uint32_t time = g_game().getLightHour(); + const uint32_t time = g_game().getLightHour(); lua_pushnumber(L, time); return 1; } int GlobalFunctions::luaGetWorldLight(lua_State* L) { // getWorldLight() - LightInfo lightInfo = g_game().getWorldLightInfo(); + const LightInfo lightInfo = g_game().getWorldLightInfo(); lua_pushnumber(L, lightInfo.level); lua_pushnumber(L, lightInfo.color); return 2; @@ -218,24 +218,24 @@ int GlobalFunctions::luaGetWorldLight(lua_State* L) { int GlobalFunctions::luaGetWorldUpTime(lua_State* L) { // getWorldUpTime() - uint64_t uptime = (OTSYS_TIME(true) - ProtocolStatus::start) / 1000; + const uint64_t uptime = (OTSYS_TIME(true) - ProtocolStatus::start) / 1000; lua_pushnumber(L, uptime); return 1; } int GlobalFunctions::luaCreateCombatArea(lua_State* L) { // createCombatArea( {area}, <optional> {extArea} ) - ScriptEnvironment* env = getScriptEnv(); + const ScriptEnvironment* env = getScriptEnv(); if (env->getScriptId() != EVENT_ID_LOADING) { reportErrorFunc("This function can only be used while loading the script."); pushBoolean(L, false); return 1; } - uint32_t areaId = g_luaEnvironment().createAreaObject(env->getScriptInterface()); + const uint32_t areaId = g_luaEnvironment().createAreaObject(env->getScriptInterface()); const auto &area = g_luaEnvironment().getAreaObject(areaId); - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); if (parameters >= 2) { uint32_t rowsExtArea; std::list<uint32_t> listExtArea; @@ -262,17 +262,17 @@ int GlobalFunctions::luaCreateCombatArea(lua_State* L) { int GlobalFunctions::luaDoAreaCombatHealth(lua_State* L) { // doAreaCombatHealth(cid, type, pos, area, min, max, effect[, origin = ORIGIN_SPELL]) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - uint32_t areaId = getNumber<uint32_t>(L, 4); + const uint32_t areaId = getNumber<uint32_t>(L, 4); const auto &area = g_luaEnvironment().getAreaObject(areaId); if (area || areaId == 0) { - CombatType_t combatType = getNumber<CombatType_t>(L, 2); + const CombatType_t combatType = getNumber<CombatType_t>(L, 2); CombatParams params; params.combatType = combatType; @@ -302,21 +302,21 @@ int GlobalFunctions::luaDoAreaCombatHealth(lua_State* L) { int GlobalFunctions::luaDoTargetCombatHealth(lua_State* L) { // doTargetCombatHealth(cid, target, type, min, max, effect[, origin = ORIGIN_SPELL]) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); if (!target) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - CombatType_t combatType = getNumber<CombatType_t>(L, 3); + const CombatType_t combatType = getNumber<CombatType_t>(L, 3); CombatParams params; params.combatType = combatType; @@ -347,14 +347,14 @@ int GlobalFunctions::luaDoTargetCombatHealth(lua_State* L) { int GlobalFunctions::luaDoAreaCombatMana(lua_State* L) { // doAreaCombatMana(cid, pos, area, min, max, effect[, origin = ORIGIN_SPELL]) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - uint32_t areaId = getNumber<uint32_t>(L, 3); + const uint32_t areaId = getNumber<uint32_t>(L, 3); const auto &area = g_luaEnvironment().getAreaObject(areaId); if (area || areaId == 0) { CombatParams params; @@ -373,7 +373,7 @@ int GlobalFunctions::luaDoAreaCombatMana(lua_State* L) { } } - Position pos = getPosition(L, 2); + const Position pos = getPosition(L, 2); Combat::doCombatMana(creature, pos, area, damage, params); pushBoolean(L, true); } else { @@ -385,14 +385,14 @@ int GlobalFunctions::luaDoAreaCombatMana(lua_State* L) { int GlobalFunctions::luaDoTargetCombatMana(lua_State* L) { // doTargetCombatMana(cid, target, min, max, effect[, origin = ORIGIN_SPELL) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); if (!target) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -400,8 +400,8 @@ int GlobalFunctions::luaDoTargetCombatMana(lua_State* L) { } CombatParams params; - auto minval = getNumber<int32_t>(L, 3); - auto maxval = getNumber<int32_t>(L, 4); + const auto minval = getNumber<int32_t>(L, 3); + const auto maxval = getNumber<int32_t>(L, 4); params.aggressive = minval + maxval < 0; params.impactEffect = getNumber<uint16_t>(L, 5); @@ -425,21 +425,21 @@ int GlobalFunctions::luaDoTargetCombatMana(lua_State* L) { int GlobalFunctions::luaDoAreaCombatCondition(lua_State* L) { // doAreaCombatCondition(cid, pos, area, condition, effect) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - const std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 4); + const auto &condition = getUserdataShared<Condition>(L, 4); if (!condition) { reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND)); pushBoolean(L, false); return 1; } - uint32_t areaId = getNumber<uint32_t>(L, 3); + const uint32_t areaId = getNumber<uint32_t>(L, 3); const auto &area = g_luaEnvironment().getAreaObject(areaId); if (area || areaId == 0) { CombatParams params; @@ -456,21 +456,21 @@ int GlobalFunctions::luaDoAreaCombatCondition(lua_State* L) { int GlobalFunctions::luaDoTargetCombatCondition(lua_State* L) { // doTargetCombatCondition(cid, target, condition, effect) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); if (!target) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - const std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 3); + const auto &condition = getUserdataShared<Condition>(L, 3); if (!condition) { reportErrorFunc(getErrorDesc(LUA_ERROR_CONDITION_NOT_FOUND)); pushBoolean(L, false); @@ -487,14 +487,14 @@ int GlobalFunctions::luaDoTargetCombatCondition(lua_State* L) { int GlobalFunctions::luaDoAreaCombatDispel(lua_State* L) { // doAreaCombatDispel(cid, pos, area, type, effect) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - uint32_t areaId = getNumber<uint32_t>(L, 3); + const uint32_t areaId = getNumber<uint32_t>(L, 3); const auto &area = g_luaEnvironment().getAreaObject(areaId); if (area || areaId == 0) { CombatParams params; @@ -512,14 +512,14 @@ int GlobalFunctions::luaDoAreaCombatDispel(lua_State* L) { int GlobalFunctions::luaDoTargetCombatDispel(lua_State* L) { // doTargetCombatDispel(cid, target, type, effect) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature && (!isNumber(L, 1) || getNumber<uint32_t>(L, 1) != 0)) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); if (!target) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -536,21 +536,21 @@ int GlobalFunctions::luaDoTargetCombatDispel(lua_State* L) { int GlobalFunctions::luaDoChallengeCreature(lua_State* L) { // doChallengeCreature(cid, target, targetChangeCooldown) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); if (!target) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - int targetChangeCooldown = getNumber<int32_t>(L, 3, 6000); + const int targetChangeCooldown = getNumber<int32_t>(L, 3, 6000); // This function must be defined to take and handle the targetChangeCooldown. target->challengeCreature(creature, targetChangeCooldown); @@ -569,7 +569,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { lua_xmove(L, globalState, lua_gettop(L)); } - int parameters = lua_gettop(globalState); + const int parameters = lua_gettop(globalState); if (!isFunction(globalState, -parameters)) { // -parameters means the first parameter from left to right reportErrorFunc("callback parameter should be a function."); pushBoolean(L, false); @@ -586,14 +586,14 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaData_t type = getNumber<LuaData_t>(L, -1); if (type != LuaData_t::Unknown && type <= LuaData_t::Npc) { - indexes.push_back({ i, type }); + indexes.emplace_back( i, type ); } lua_pop(globalState, 2); } if (!indexes.empty()) { if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__)) { - bool plural = indexes.size() > 1; + const bool plural = indexes.size() > 1; std::string warningString = "Argument"; if (plural) { @@ -655,7 +655,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { eventDesc.parameters.push_back(luaL_ref(globalState, LUA_REGISTRYINDEX)); } - uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2)); + const uint32_t delay = std::max<uint32_t>(100, getNumber<uint32_t>(globalState, 2)); lua_pop(globalState, 1); eventDesc.function = luaL_ref(globalState, LUA_REGISTRYINDEX); @@ -683,22 +683,22 @@ int GlobalFunctions::luaStopEvent(lua_State* L) { return 1; } - uint32_t eventId = getNumber<uint32_t>(L, 1); + const uint32_t eventId = getNumber<uint32_t>(L, 1); auto &timerEvents = g_luaEnvironment().timerEvents; - auto it = timerEvents.find(eventId); + const auto it = timerEvents.find(eventId); if (it == timerEvents.end()) { pushBoolean(L, false); return 1; } - LuaTimerEventDesc timerEventDesc = std::move(it->second); + const LuaTimerEventDesc timerEventDesc = std::move(it->second); timerEvents.erase(it); g_dispatcher().stopEvent(timerEventDesc.eventId); luaL_unref(globalState, LUA_REGISTRYINDEX, timerEventDesc.function); - for (auto parameter : timerEventDesc.parameters) { + for (const auto parameter : timerEventDesc.parameters) { luaL_unref(globalState, LUA_REGISTRYINDEX, parameter); } @@ -748,7 +748,7 @@ int GlobalFunctions::luaGetWaypointPositionByName(lua_State* L) { // getWaypointPositionByName(name) auto &waypoints = g_game().map.waypoints; - auto it = waypoints.find(getString(L, -1)); + const auto it = waypoints.find(getString(L, -1)); if (it != waypoints.end()) { pushPosition(L, it->second); } else { @@ -759,15 +759,15 @@ int GlobalFunctions::luaGetWaypointPositionByName(lua_State* L) { int GlobalFunctions::luaSendChannelMessage(lua_State* L) { // sendChannelMessage(channelId, type, message) - uint16_t channelId = getNumber<uint16_t>(L, 1); + const uint16_t channelId = getNumber<uint16_t>(L, 1); const auto &channel = g_chat().getChannelById(channelId); if (!channel) { pushBoolean(L, false); return 1; } - SpeakClasses type = getNumber<SpeakClasses>(L, 2); - std::string message = getString(L, 3); + const SpeakClasses type = getNumber<SpeakClasses>(L, 2); + const std::string message = getString(L, 3); channel->sendToAll(message, type); pushBoolean(L, true); return 1; @@ -775,15 +775,15 @@ int GlobalFunctions::luaSendChannelMessage(lua_State* L) { int GlobalFunctions::luaSendGuildChannelMessage(lua_State* L) { // sendGuildChannelMessage(guildId, type, message) - uint32_t guildId = getNumber<uint32_t>(L, 1); + const uint32_t guildId = getNumber<uint32_t>(L, 1); const auto &channel = g_chat().getGuildChannelById(guildId); if (!channel) { pushBoolean(L, false); return 1; } - SpeakClasses type = getNumber<SpeakClasses>(L, 2); - std::string message = getString(L, 3); + const SpeakClasses type = getNumber<SpeakClasses>(L, 2); + const std::string message = getString(L, 3); channel->sendToAll(message, type); pushBoolean(L, true); return 1; @@ -795,20 +795,20 @@ int GlobalFunctions::luaIsType(lua_State* L) { lua_getmetatable(L, -2); lua_rawgeti(L, -2, 'p'); - uint_fast8_t parentsB = getNumber<uint_fast8_t>(L, 1); + const uint_fast8_t parentsB = getNumber<uint_fast8_t>(L, 1); lua_rawgeti(L, -3, 'h'); - size_t hashB = getNumber<size_t>(L, 1); + const size_t hashB = getNumber<size_t>(L, 1); lua_rawgeti(L, -3, 'p'); - uint_fast8_t parentsA = getNumber<uint_fast8_t>(L, 1); + const uint_fast8_t parentsA = getNumber<uint_fast8_t>(L, 1); for (uint_fast8_t i = parentsA; i < parentsB; ++i) { lua_getfield(L, -3, "__index"); lua_replace(L, -4); } lua_rawgeti(L, -4, 'h'); - size_t hashA = getNumber<size_t>(L, 1); + const size_t hashA = getNumber<size_t>(L, 1); pushBoolean(L, hashA == hashB); return 1; @@ -834,14 +834,14 @@ int GlobalFunctions::luaSystemTime(lua_State* L) { int GlobalFunctions::luaGetFormattedTimeRemaining(lua_State* L) { // getFormattedTimeRemaining(time) - time_t time = getNumber<uint32_t>(L, 1); + const time_t time = getNumber<uint32_t>(L, 1); lua_pushstring(L, getFormattedTimeRemaining(time).c_str()); return 1; } int GlobalFunctions::luaReportError(lua_State* L) { // reportError(errorDescription) - auto errorDescription = getString(L, 1); + const auto errorDescription = getString(L, 1); reportError(__func__, errorDescription, true); return 1; } diff --git a/src/lua/functions/core/game/global_functions.hpp b/src/lua/functions/core/game/global_functions.hpp index cef752c6695..2b1e249a5fd 100644 --- a/src/lua/functions/core/game/global_functions.hpp +++ b/src/lua/functions/core/game/global_functions.hpp @@ -13,6 +13,12 @@ class GlobalFunctions final : LuaScriptInterface { public: + explicit GlobalFunctions(lua_State* L) : + LuaScriptInterface("GlobalFunctions") { + init(L); + } + ~GlobalFunctions() override = default; + static void init(lua_State* L) { lua_register(L, "addEvent", GlobalFunctions::luaAddEvent); lua_register(L, "cleanMap", GlobalFunctions::luaCleanMap); diff --git a/src/lua/functions/core/game/lua_enums.cpp b/src/lua/functions/core/game/lua_enums.cpp index 05fc72c019f..55ea7776912 100644 --- a/src/lua/functions/core/game/lua_enums.cpp +++ b/src/lua/functions/core/game/lua_enums.cpp @@ -331,7 +331,7 @@ void LuaEnums::initFactionEnums(lua_State* L) { } void LuaEnums::initConditionEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<ConditionType_t>()) { + for (const auto value : magic_enum::enum_values<ConditionType_t>()) { registerMagicEnum(L, value); } } @@ -837,7 +837,7 @@ void LuaEnums::initItemTypeEnums(lua_State* L) { } void LuaEnums::initFluidEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<Fluids_t>()) { + for (const auto value : magic_enum::enum_values<Fluids_t>()) { registerMagicEnum(L, value); } } @@ -909,7 +909,7 @@ void LuaEnums::initItemIdEnums(lua_State* L) { } void LuaEnums::initPlayerFlagEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<PlayerFlags_t>()) { + for (const auto value : magic_enum::enum_values<PlayerFlags_t>()) { registerMagicEnum(L, value); } } @@ -1199,7 +1199,7 @@ void LuaEnums::initReturnValueEnums(lua_State* L) { // Reload void LuaEnums::initReloadTypeEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<Reload_t>()) { + for (const auto value : magic_enum::enum_values<Reload_t>()) { registerMagicEnum(L, value); } } @@ -1225,7 +1225,7 @@ void LuaEnums::initCreaturesEventEnums(lua_State* L) { } void LuaEnums::initForgeEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<ForgeClassifications_t>()) { + for (const auto value : magic_enum::enum_values<ForgeClassifications_t>()) { registerMagicEnum(L, value); } } @@ -1239,7 +1239,7 @@ void LuaEnums::initWebhookEnums(lua_State* L) { } void LuaEnums::initBosstiaryEnums(lua_State* L) { - for (auto value : magic_enum::enum_values<BosstiaryRarity_t>()) { + for (const auto value : magic_enum::enum_values<BosstiaryRarity_t>()) { registerMagicEnum(L, value); } } @@ -1763,31 +1763,31 @@ void LuaEnums::initSoundEnums(lua_State* L) { void LuaEnums::initWheelEnums(lua_State* L) { std::string wheelNamespace = "WHEEL_INSTANT_"; - for (auto value : magic_enum::enum_values<WheelInstant_t>()) { + for (const auto value : magic_enum::enum_values<WheelInstant_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_STAGE_"; - for (auto value : magic_enum::enum_values<WheelStage_t>()) { + for (const auto value : magic_enum::enum_values<WheelStage_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_GRADE_"; - for (auto value : magic_enum::enum_values<WheelSpellGrade_t>()) { + for (const auto value : magic_enum::enum_values<WheelSpellGrade_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_AVATAR_SKILL_"; - for (auto value : magic_enum::enum_values<WheelAvatarSkill_t>()) { + for (const auto value : magic_enum::enum_values<WheelAvatarSkill_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_STAT_"; - for (auto value : magic_enum::enum_values<WheelStat_t>()) { + for (const auto value : magic_enum::enum_values<WheelStat_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_BOOST_"; - for (auto value : magic_enum::enum_values<WheelSpellBoost_t>()) { + for (const auto value : magic_enum::enum_values<WheelSpellBoost_t>()) { registerMagicEnumNamespace(L, wheelNamespace, value); } } diff --git a/src/lua/functions/core/game/lua_enums.hpp b/src/lua/functions/core/game/lua_enums.hpp index 8beabbbacee..42ba792f52e 100644 --- a/src/lua/functions/core/game/lua_enums.hpp +++ b/src/lua/functions/core/game/lua_enums.hpp @@ -15,6 +15,12 @@ class LuaEnums final : LuaScriptInterface { public: + explicit LuaEnums(lua_State* L) : + LuaScriptInterface("LuaEnums") { + init(L); + } + ~LuaEnums() override = default; + static void init(lua_State* L); private: diff --git a/src/lua/functions/core/game/modal_window_functions.hpp b/src/lua/functions/core/game/modal_window_functions.hpp index 9d6b9192026..1e2242d8570 100644 --- a/src/lua/functions/core/game/modal_window_functions.hpp +++ b/src/lua/functions/core/game/modal_window_functions.hpp @@ -13,6 +13,12 @@ class ModalWindowFunctions final : LuaScriptInterface { public: + explicit ModalWindowFunctions(lua_State* L) : + LuaScriptInterface("ModalWindowFunctions") { + init(L); + } + ~ModalWindowFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "ModalWindow", "", ModalWindowFunctions::luaModalWindowCreate); registerMetaMethod(L, "ModalWindow", "__eq", ModalWindowFunctions::luaUserdataCompare); diff --git a/src/lua/functions/core/game/zone_functions.cpp b/src/lua/functions/core/game/zone_functions.cpp index 8ab6d4b9532..74ed6d190b0 100644 --- a/src/lua/functions/core/game/zone_functions.cpp +++ b/src/lua/functions/core/game/zone_functions.cpp @@ -6,7 +6,7 @@ // Zone int ZoneFunctions::luaZoneCreate(lua_State* L) { // Zone(name) - auto name = getString(L, 2); + const auto name = getString(L, 2); auto zone = Zone::getZone(name); if (!zone) { zone = Zone::addZone(name); @@ -17,8 +17,8 @@ int ZoneFunctions::luaZoneCreate(lua_State* L) { } int ZoneFunctions::luaZoneCompare(lua_State* L) { - auto zone1 = getUserdataShared<Zone>(L, 1); - auto zone2 = getUserdataShared<Zone>(L, 2); + const auto &zone1 = getUserdataShared<Zone>(L, 1); + const auto &zone2 = getUserdataShared<Zone>(L, 2); if (!zone1) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); @@ -36,7 +36,7 @@ int ZoneFunctions::luaZoneCompare(lua_State* L) { int ZoneFunctions::luaZoneGetName(lua_State* L) { // Zone:getName() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); @@ -48,15 +48,15 @@ int ZoneFunctions::luaZoneGetName(lua_State* L) { int ZoneFunctions::luaZoneAddArea(lua_State* L) { // Zone:addArea(fromPos, toPos) - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto fromPos = getPosition(L, 2); - auto toPos = getPosition(L, 3); - auto area = Area(fromPos, toPos); + const auto fromPos = getPosition(L, 2); + const auto toPos = getPosition(L, 3); + const auto area = Area(fromPos, toPos); zone->addArea(area); pushBoolean(L, true); return 1; @@ -64,15 +64,15 @@ int ZoneFunctions::luaZoneAddArea(lua_State* L) { int ZoneFunctions::luaZoneSubtractArea(lua_State* L) { // Zone:subtractArea(fromPos, toPos) - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto fromPos = getPosition(L, 2); - auto toPos = getPosition(L, 3); - auto area = Area(fromPos, toPos); + const auto fromPos = getPosition(L, 2); + const auto toPos = getPosition(L, 3); + const auto area = Area(fromPos, toPos); zone->subtractArea(area); pushBoolean(L, true); return 1; @@ -80,7 +80,7 @@ int ZoneFunctions::luaZoneSubtractArea(lua_State* L) { int ZoneFunctions::luaZoneGetRemoveDestination(lua_State* L) { // Zone:getRemoveDestination() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); return 1; @@ -91,25 +91,25 @@ int ZoneFunctions::luaZoneGetRemoveDestination(lua_State* L) { int ZoneFunctions::luaZoneSetRemoveDestination(lua_State* L) { // Zone:setRemoveDestination(pos) - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); return 1; } - auto pos = getPosition(L, 2); + const auto pos = getPosition(L, 2); zone->setRemoveDestination(pos); return 1; } int ZoneFunctions::luaZoneGetPositions(lua_State* L) { // Zone:getPositions() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto positions = zone->getPositions(); + const auto positions = zone->getPositions(); lua_createtable(L, static_cast<int>(positions.size()), 0); int index = 0; @@ -123,13 +123,13 @@ int ZoneFunctions::luaZoneGetPositions(lua_State* L) { int ZoneFunctions::luaZoneGetCreatures(lua_State* L) { // Zone:getCreatures() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto creatures = zone->getCreatures(); + const auto &creatures = zone->getCreatures(); lua_createtable(L, static_cast<int>(creatures.size()), 0); int index = 0; @@ -144,13 +144,13 @@ int ZoneFunctions::luaZoneGetCreatures(lua_State* L) { int ZoneFunctions::luaZoneGetPlayers(lua_State* L) { // Zone:getPlayers() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto players = zone->getPlayers(); + const auto &players = zone->getPlayers(); lua_createtable(L, static_cast<int>(players.size()), 0); int index = 0; @@ -165,13 +165,13 @@ int ZoneFunctions::luaZoneGetPlayers(lua_State* L) { int ZoneFunctions::luaZoneGetMonsters(lua_State* L) { // Zone:getMonsters() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto monsters = zone->getMonsters(); + const auto &monsters = zone->getMonsters(); lua_createtable(L, static_cast<int>(monsters.size()), 0); int index = 0; @@ -186,13 +186,13 @@ int ZoneFunctions::luaZoneGetMonsters(lua_State* L) { int ZoneFunctions::luaZoneGetNpcs(lua_State* L) { // Zone:getNpcs() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto npcs = zone->getNpcs(); + const auto &npcs = zone->getNpcs(); lua_createtable(L, static_cast<int>(npcs.size()), 0); int index = 0; @@ -207,13 +207,13 @@ int ZoneFunctions::luaZoneGetNpcs(lua_State* L) { int ZoneFunctions::luaZoneGetItems(lua_State* L) { // Zone:getItems() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto items = zone->getItems(); + const auto &items = zone->getItems(); lua_createtable(L, static_cast<int>(items.size()), 0); int index = 0; @@ -228,7 +228,7 @@ int ZoneFunctions::luaZoneGetItems(lua_State* L) { int ZoneFunctions::luaZoneRemovePlayers(lua_State* L) { // Zone:removePlayers() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); @@ -241,7 +241,7 @@ int ZoneFunctions::luaZoneRemovePlayers(lua_State* L) { int ZoneFunctions::luaZoneRemoveMonsters(lua_State* L) { // Zone:removeMonsters() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); @@ -253,7 +253,7 @@ int ZoneFunctions::luaZoneRemoveMonsters(lua_State* L) { int ZoneFunctions::luaZoneRemoveNpcs(lua_State* L) { // Zone:removeNpcs() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); @@ -265,13 +265,13 @@ int ZoneFunctions::luaZoneRemoveNpcs(lua_State* L) { int ZoneFunctions::luaZoneSetMonsterVariant(lua_State* L) { // Zone:setMonsterVariant(variant) - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); pushBoolean(L, false); return 1; } - auto variant = getString(L, 2); + const auto variant = getString(L, 2); if (variant.empty()) { pushBoolean(L, false); return 1; @@ -283,8 +283,8 @@ int ZoneFunctions::luaZoneSetMonsterVariant(lua_State* L) { int ZoneFunctions::luaZoneGetByName(lua_State* L) { // Zone.getByName(name) - auto name = getString(L, 1); - auto zone = Zone::getZone(name); + const auto name = getString(L, 1); + const auto &zone = Zone::getZone(name); if (!zone) { lua_pushnil(L); return 1; @@ -296,14 +296,14 @@ int ZoneFunctions::luaZoneGetByName(lua_State* L) { int ZoneFunctions::luaZoneGetByPosition(lua_State* L) { // Zone.getByPosition(pos) - auto pos = getPosition(L, 1); - auto tile = g_game().map.getTile(pos); + const auto pos = getPosition(L, 1); + const auto &tile = g_game().map.getTile(pos); if (!tile) { lua_pushnil(L); return 1; } int index = 0; - auto zones = tile->getZones(); + const auto &zones = tile->getZones(); lua_createtable(L, static_cast<int>(zones.size()), 0); for (const auto &zone : zones) { index++; @@ -316,7 +316,7 @@ int ZoneFunctions::luaZoneGetByPosition(lua_State* L) { int ZoneFunctions::luaZoneGetAll(lua_State* L) { // Zone.getAll() - auto zones = Zone::getZones(); + const auto &zones = Zone::getZones(); lua_createtable(L, static_cast<int>(zones.size()), 0); int index = 0; for (const auto &zone : zones) { @@ -330,7 +330,7 @@ int ZoneFunctions::luaZoneGetAll(lua_State* L) { int ZoneFunctions::luaZoneRefresh(lua_State* L) { // Zone:refresh() - auto zone = getUserdataShared<Zone>(L, 1); + const auto &zone = getUserdataShared<Zone>(L, 1); if (!zone) { reportErrorFunc(getErrorDesc(LUA_ERROR_ZONE_NOT_FOUND)); return 1; diff --git a/src/lua/functions/core/game/zone_functions.hpp b/src/lua/functions/core/game/zone_functions.hpp index 2a3bbd0f8ea..0860595f0a8 100644 --- a/src/lua/functions/core/game/zone_functions.hpp +++ b/src/lua/functions/core/game/zone_functions.hpp @@ -6,6 +6,12 @@ class Zone; class ZoneFunctions final : LuaScriptInterface { public: + explicit ZoneFunctions(lua_State* L) : + LuaScriptInterface("ZoneFunctions") { + init(L); + } + ~ZoneFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Zone", "", ZoneFunctions::luaZoneCreate); registerMetaMethod(L, "Zone", "__eq", ZoneFunctions::luaZoneCompare); diff --git a/src/lua/functions/core/libs/bit_functions.hpp b/src/lua/functions/core/libs/bit_functions.hpp index c2143fde198..3d117e74b55 100644 --- a/src/lua/functions/core/libs/bit_functions.hpp +++ b/src/lua/functions/core/libs/bit_functions.hpp @@ -13,6 +13,12 @@ class BitFunctions final : LuaScriptInterface { public: + explicit BitFunctions(lua_State* L) : + LuaScriptInterface("BitFunctions") { + init(L); + } + ~BitFunctions() override = default; + static void init(lua_State* L) { #ifndef LUAJIT_VERSION registerTable(L, "bit"); diff --git a/src/lua/functions/core/libs/core_libs_functions.hpp b/src/lua/functions/core/libs/core_libs_functions.hpp index 614c59e6e3d..fdfa2d9de81 100644 --- a/src/lua/functions/core/libs/core_libs_functions.hpp +++ b/src/lua/functions/core/libs/core_libs_functions.hpp @@ -19,6 +19,12 @@ class CoreLibsFunctions final : LuaScriptInterface { public: + explicit CoreLibsFunctions(lua_State* L) : + LuaScriptInterface("CoreLibsFunctions") { + init(L); + } + ~CoreLibsFunctions() override = default; + static void init(lua_State* L) { BitFunctions::init(L); DBFunctions::init(L); diff --git a/src/lua/functions/core/libs/db_functions.cpp b/src/lua/functions/core/libs/db_functions.cpp index 2ca1bface33..6c8215f42da 100644 --- a/src/lua/functions/core/libs/db_functions.cpp +++ b/src/lua/functions/core/libs/db_functions.cpp @@ -37,7 +37,7 @@ int DBFunctions::luaDatabaseAsyncExecute(lua_State* L) { lua_rawgeti(luaState, LUA_REGISTRYINDEX, ref); pushBoolean(luaState, success); - auto env = getScriptEnv(); + const auto env = getScriptEnv(); env->setScriptId(scriptId, &g_luaEnvironment()); g_luaEnvironment().callFunction(1); @@ -49,7 +49,7 @@ int DBFunctions::luaDatabaseAsyncExecute(lua_State* L) { } int DBFunctions::luaDatabaseStoreQuery(lua_State* L) { - if (DBResult_ptr res = Database::getInstance().storeQuery(getString(L, -1))) { + if (const DBResult_ptr &res = Database::getInstance().storeQuery(getString(L, -1))) { lua_pushnumber(L, ScriptEnvironment::addResult(res)); } else { pushBoolean(L, false); @@ -79,7 +79,7 @@ int DBFunctions::luaDatabaseAsyncStoreQuery(lua_State* L) { } else { pushBoolean(luaState, false); } - auto env = getScriptEnv(); + const auto env = getScriptEnv(); env->setScriptId(scriptId, &g_luaEnvironment()); g_luaEnvironment().callFunction(1); @@ -96,7 +96,7 @@ int DBFunctions::luaDatabaseEscapeString(lua_State* L) { } int DBFunctions::luaDatabaseEscapeBlob(lua_State* L) { - uint32_t length = getNumber<uint32_t>(L, 2); + const uint32_t length = getNumber<uint32_t>(L, 2); pushString(L, Database::getInstance().escapeBlob(getString(L, 1).c_str(), length)); return 1; } diff --git a/src/lua/functions/core/libs/db_functions.hpp b/src/lua/functions/core/libs/db_functions.hpp index 99b69f1f7ba..6d95acdeae9 100644 --- a/src/lua/functions/core/libs/db_functions.hpp +++ b/src/lua/functions/core/libs/db_functions.hpp @@ -13,6 +13,12 @@ class DBFunctions final : LuaScriptInterface { public: + explicit DBFunctions(lua_State* L) : + LuaScriptInterface("DBFunctions") { + init(L); + } + ~DBFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "db"); registerMethod(L, "db", "query", DBFunctions::luaDatabaseExecute); diff --git a/src/lua/functions/core/libs/kv_functions.cpp b/src/lua/functions/core/libs/kv_functions.cpp index f145c2c0b5d..3ba76cedff4 100644 --- a/src/lua/functions/core/libs/kv_functions.cpp +++ b/src/lua/functions/core/libs/kv_functions.cpp @@ -17,17 +17,17 @@ int KVFunctions::luaKVScoped(lua_State* L) { // KV.scoped(key) | KV:scoped(key) - auto key = getString(L, -1); + const auto key = getString(L, -1); if (isUserdata(L, 1)) { - auto scopedKV = getUserdataShared<KV>(L, 1); - auto newScope = scopedKV->scoped(key); + const auto &scopedKV = getUserdataShared<KV>(L, 1); + const auto &newScope = scopedKV->scoped(key); pushUserdata<KV>(L, newScope); setMetatable(L, -1, "KV"); return 1; } - auto scopedKV = g_kv().scoped(key); + const auto &scopedKV = g_kv().scoped(key); pushUserdata<KV>(L, scopedKV); setMetatable(L, -1, "KV"); return 1; @@ -35,8 +35,8 @@ int KVFunctions::luaKVScoped(lua_State* L) { int KVFunctions::luaKVSet(lua_State* L) { // KV.set(key, value) | scopedKV:set(key, value) - auto key = getString(L, -2); - auto valueWrapper = getValueWrapper(L); + const auto key = getString(L, -2); + const auto &valueWrapper = getValueWrapper(L); if (!valueWrapper) { g_logger().warn("[{}] invalid param type", __FUNCTION__); @@ -45,7 +45,7 @@ int KVFunctions::luaKVSet(lua_State* L) { } if (isUserdata(L, 1)) { - auto scopedKV = getUserdataShared<KV>(L, 1); + const auto &scopedKV = getUserdataShared<KV>(L, 1); scopedKV->set(key, valueWrapper.value()); pushBoolean(L, true); return 1; @@ -66,7 +66,7 @@ int KVFunctions::luaKVGet(lua_State* L) { key = getString(L, -2); } if (isUserdata(L, 1)) { - auto scopedKV = getUserdataShared<KV>(L, 1); + const auto &scopedKV = getUserdataShared<KV>(L, 1); valueWrapper = scopedKV->get(key, forceLoad); } else { valueWrapper = g_kv().get(key, forceLoad); @@ -82,9 +82,9 @@ int KVFunctions::luaKVGet(lua_State* L) { int KVFunctions::luaKVRemove(lua_State* L) { // KV.remove(key) | scopedKV:remove(key) - auto key = getString(L, -1); + const auto key = getString(L, -1); if (isUserdata(L, 1)) { - auto scopedKV = getUserdataShared<KV>(L, 1); + const auto &scopedKV = getUserdataShared<KV>(L, 1); scopedKV->remove(key); } else { g_kv().remove(key); @@ -103,7 +103,7 @@ int KVFunctions::luaKVKeys(lua_State* L) { } if (isUserdata(L, 1)) { - auto scopedKV = getUserdataShared<KV>(L, 1); + const auto &scopedKV = getUserdataShared<KV>(L, 1); keys = scopedKV->keys(); } else { keys = g_kv().keys(prefix); @@ -133,7 +133,7 @@ std::optional<ValueWrapper> KVFunctions::getValueWrapper(lua_State* L) { ArrayType array; for (int i = 1; i <= lua_objlen(L, -1); ++i) { lua_rawgeti(L, -1, i); - auto value = getValueWrapper(L); + const auto &value = getValueWrapper(L); if (!value) { g_logger().warn("[{}] invalid param type", __FUNCTION__); return std::nullopt; @@ -148,7 +148,7 @@ std::optional<ValueWrapper> KVFunctions::getValueWrapper(lua_State* L) { MapType map; lua_pushnil(L); while (lua_next(L, -2) != 0) { - auto value = getValueWrapper(L); + const auto &value = getValueWrapper(L); if (!value) { g_logger().warn("[{}] invalid param type", __FUNCTION__); return std::nullopt; diff --git a/src/lua/functions/core/libs/kv_functions.hpp b/src/lua/functions/core/libs/kv_functions.hpp index 919901df7f8..4ef47333f2f 100644 --- a/src/lua/functions/core/libs/kv_functions.hpp +++ b/src/lua/functions/core/libs/kv_functions.hpp @@ -27,6 +27,12 @@ struct lua_State; class KVFunctions final : LuaScriptInterface { public: + explicit KVFunctions(lua_State* L) : + LuaScriptInterface("KVFunctions") { + init(L); + } + ~KVFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "kv"); registerMethod(L, "kv", "scoped", KVFunctions::luaKVScoped); diff --git a/src/lua/functions/core/libs/logger_functions.hpp b/src/lua/functions/core/libs/logger_functions.hpp index 2c4dba46cc1..fb3c265f21d 100644 --- a/src/lua/functions/core/libs/logger_functions.hpp +++ b/src/lua/functions/core/libs/logger_functions.hpp @@ -13,6 +13,12 @@ class LoggerFunctions final : public LuaScriptInterface { public: + explicit LoggerFunctions(lua_State* L) : + LuaScriptInterface("LoggerFunctions") { + init(L); + } + ~LoggerFunctions() override = default; + static void init(lua_State* L); private: diff --git a/src/lua/functions/core/libs/metrics_functions.cpp b/src/lua/functions/core/libs/metrics_functions.cpp index 9dc9fa528cb..4e27ec05d32 100644 --- a/src/lua/functions/core/libs/metrics_functions.cpp +++ b/src/lua/functions/core/libs/metrics_functions.cpp @@ -20,9 +20,9 @@ void MetricsFunctions::init(lua_State* L) { // Metrics int MetricsFunctions::luaMetricsAddCounter(lua_State* L) { // metrics.addCounter(name, value, attributes) - auto name = getString(L, 1); - auto value = getNumber<double>(L, 2); - auto attributes = getAttributes(L, 3); + const auto name = getString(L, 1); + const auto value = getNumber<double>(L, 2); + const auto attributes = getAttributes(L, 3); g_metrics().addCounter(name, value, attributes); return 1; } diff --git a/src/lua/functions/core/libs/metrics_functions.hpp b/src/lua/functions/core/libs/metrics_functions.hpp index e71f005aaa8..4155646cb51 100644 --- a/src/lua/functions/core/libs/metrics_functions.hpp +++ b/src/lua/functions/core/libs/metrics_functions.hpp @@ -13,6 +13,12 @@ class MetricsFunctions final : public LuaScriptInterface { public: + explicit MetricsFunctions(lua_State* L) : + LuaScriptInterface("MetricsFunctions") { + init(L); + } + ~MetricsFunctions() override = default; + static void init(lua_State* L); private: diff --git a/src/lua/functions/core/libs/result_functions.cpp b/src/lua/functions/core/libs/result_functions.cpp index 512f90f7da5..afb6912d707 100644 --- a/src/lua/functions/core/libs/result_functions.cpp +++ b/src/lua/functions/core/libs/result_functions.cpp @@ -12,7 +12,7 @@ #include "lua/functions/core/libs/result_functions.hpp" int ResultFunctions::luaResultGetNumber(lua_State* L) { - DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); + const auto &res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); if (!res) { pushBoolean(L, false); return 1; @@ -24,7 +24,7 @@ int ResultFunctions::luaResultGetNumber(lua_State* L) { } int ResultFunctions::luaResultGetString(lua_State* L) { - DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); + const auto &res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); if (!res) { pushBoolean(L, false); return 1; @@ -36,7 +36,7 @@ int ResultFunctions::luaResultGetString(lua_State* L) { } int ResultFunctions::luaResultGetStream(lua_State* L) { - DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); + const auto &res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, 1)); if (!res) { pushBoolean(L, false); return 1; @@ -50,7 +50,7 @@ int ResultFunctions::luaResultGetStream(lua_State* L) { } int ResultFunctions::luaResultNext(lua_State* L) { - DBResult_ptr res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, -1)); + const auto &res = ScriptEnvironment::getResultByID(getNumber<uint32_t>(L, -1)); if (!res) { pushBoolean(L, false); return 1; diff --git a/src/lua/functions/core/libs/result_functions.hpp b/src/lua/functions/core/libs/result_functions.hpp index 4aa25173ed7..7e7f74f1add 100644 --- a/src/lua/functions/core/libs/result_functions.hpp +++ b/src/lua/functions/core/libs/result_functions.hpp @@ -13,6 +13,12 @@ class ResultFunctions final : LuaScriptInterface { public: + explicit ResultFunctions(lua_State* L) : + LuaScriptInterface("ResultFunctions") { + init(L); + } + ~ResultFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "Result"); registerMethod(L, "Result", "getNumber", ResultFunctions::luaResultGetNumber); diff --git a/src/lua/functions/core/network/core_network_functions.hpp b/src/lua/functions/core/network/core_network_functions.hpp index c1e65ec15ac..8f0c3b021ef 100644 --- a/src/lua/functions/core/network/core_network_functions.hpp +++ b/src/lua/functions/core/network/core_network_functions.hpp @@ -15,6 +15,12 @@ class CoreNetworkFunctions final : LuaScriptInterface { public: + explicit CoreNetworkFunctions(lua_State* L) : + LuaScriptInterface("CoreNetworkFunctions") { + init(L); + } + ~CoreNetworkFunctions() override = default; + static void init(lua_State* L) { NetworkMessageFunctions::init(L); WebhookFunctions::init(L); diff --git a/src/lua/functions/core/network/network_message_functions.cpp b/src/lua/functions/core/network/network_message_functions.cpp index 017d7e74100..c638e49416a 100644 --- a/src/lua/functions/core/network/network_message_functions.cpp +++ b/src/lua/functions/core/network/network_message_functions.cpp @@ -88,7 +88,7 @@ int NetworkMessageFunctions::luaNetworkMessageGetPosition(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddByte(lua_State* L) { // networkMessage:addByte(number) - uint8_t number = getNumber<uint8_t>(L, 2); + const uint8_t number = getNumber<uint8_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->addByte(number); @@ -101,7 +101,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddByte(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddU16(lua_State* L) { // networkMessage:addU16(number) - uint16_t number = getNumber<uint16_t>(L, 2); + const uint16_t number = getNumber<uint16_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<uint16_t>(number); @@ -114,7 +114,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddU16(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddU32(lua_State* L) { // networkMessage:addU32(number) - uint32_t number = getNumber<uint32_t>(L, 2); + const uint32_t number = getNumber<uint32_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<uint32_t>(number); @@ -127,7 +127,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddU32(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddU64(lua_State* L) { // networkMessage:addU64(number) - uint64_t number = getNumber<uint64_t>(L, 2); + const uint64_t number = getNumber<uint64_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<uint64_t>(number); @@ -140,7 +140,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddU64(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAdd8(lua_State* L) { // networkMessage:add8(number) - auto number = getNumber<int8_t>(L, 2); + const auto number = getNumber<int8_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<int8_t>(number); @@ -153,7 +153,7 @@ int NetworkMessageFunctions::luaNetworkMessageAdd8(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAdd16(lua_State* L) { // networkMessage:add16(number) - auto number = getNumber<int16_t>(L, 2); + const auto number = getNumber<int16_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<int16_t>(number); @@ -166,7 +166,7 @@ int NetworkMessageFunctions::luaNetworkMessageAdd16(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAdd32(lua_State* L) { // networkMessage:add32(number) - auto number = getNumber<int32_t>(L, 2); + const auto number = getNumber<int32_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<int32_t>(number); @@ -179,7 +179,7 @@ int NetworkMessageFunctions::luaNetworkMessageAdd32(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAdd64(lua_State* L) { // networkMessage:add64(number) - auto number = getNumber<int64_t>(L, 2); + const auto number = getNumber<int64_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->add<int64_t>(number); @@ -219,7 +219,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddPosition(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddDouble(lua_State* L) { // networkMessage:addDouble(number) - double number = getNumber<double>(L, 2); + const double number = getNumber<double>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->addDouble(number); @@ -232,7 +232,7 @@ int NetworkMessageFunctions::luaNetworkMessageAddDouble(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageAddItem(lua_State* L) { // networkMessage:addItem(item, player) - const auto item = getUserdataShared<Item>(L, 2); + const auto &item = getUserdataShared<Item>(L, 2); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); lua_pushnil(L); @@ -270,7 +270,7 @@ int NetworkMessageFunctions::luaNetworkMessageReset(lua_State* L) { int NetworkMessageFunctions::luaNetworkMessageSkipBytes(lua_State* L) { // networkMessage:skipBytes(number) - int16_t number = getNumber<int16_t>(L, 2); + const int16_t number = getNumber<int16_t>(L, 2); const auto &message = getUserdataShared<NetworkMessage>(L, 1); if (message) { message->skipBytes(number); diff --git a/src/lua/functions/core/network/network_message_functions.hpp b/src/lua/functions/core/network/network_message_functions.hpp index 5a2982c0d85..783e06aec57 100644 --- a/src/lua/functions/core/network/network_message_functions.hpp +++ b/src/lua/functions/core/network/network_message_functions.hpp @@ -13,6 +13,12 @@ class NetworkMessageFunctions final : LuaScriptInterface { public: + explicit NetworkMessageFunctions(lua_State* L) : + LuaScriptInterface("NetworkMessageFunctions") { + init(L); + } + ~NetworkMessageFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "NetworkMessage", "", NetworkMessageFunctions::luaNetworkMessageCreate); registerMetaMethod(L, "NetworkMessage", "__eq", NetworkMessageFunctions::luaUserdataCompare); diff --git a/src/lua/functions/core/network/webhook_functions.cpp b/src/lua/functions/core/network/webhook_functions.cpp index 6b1bf5eea05..d2022408a13 100644 --- a/src/lua/functions/core/network/webhook_functions.cpp +++ b/src/lua/functions/core/network/webhook_functions.cpp @@ -15,10 +15,10 @@ int WebhookFunctions::luaWebhookSendMessage(lua_State* L) { // Webhook.sendMessage(title, message, color, url = "WEBHOOK_DISCORD_URL") | // Webhook.sendMessage(message, url = "WEBHOOK_DISCORD_URL") - std::string title = getString(L, 1); - std::string message = getString(L, 2); - auto color = getNumber<uint32_t>(L, 3, 0); - std::string url = getString(L, -1); + const std::string title = getString(L, 1); + const std::string message = getString(L, 2); + const auto color = getNumber<uint32_t>(L, 3, 0); + const std::string url = getString(L, -1); if (url == title) { g_webhook().sendMessage(title); } else if (url == message) { diff --git a/src/lua/functions/core/network/webhook_functions.hpp b/src/lua/functions/core/network/webhook_functions.hpp index 7d5f53ba4b8..83ecb377c80 100644 --- a/src/lua/functions/core/network/webhook_functions.hpp +++ b/src/lua/functions/core/network/webhook_functions.hpp @@ -13,6 +13,12 @@ class WebhookFunctions final : LuaScriptInterface { public: + explicit WebhookFunctions(lua_State* L) : + LuaScriptInterface("WebhookFunctions") { + init(L); + } + ~WebhookFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "Webhook"); registerMethod(L, "Webhook", "sendMessage", WebhookFunctions::luaWebhookSendMessage); diff --git a/src/lua/functions/creatures/combat/combat_functions.cpp b/src/lua/functions/creatures/combat/combat_functions.cpp index c7a87a2a15c..5c2e3ff7f28 100644 --- a/src/lua/functions/creatures/combat/combat_functions.cpp +++ b/src/lua/functions/creatures/combat/combat_functions.cpp @@ -30,7 +30,7 @@ int CombatFunctions::luaCombatSetParameter(lua_State* L) { return 1; } - CombatParam_t key = getNumber<CombatParam_t>(L, 2); + const CombatParam_t key = getNumber<CombatParam_t>(L, 2); uint32_t value; if (isBoolean(L, 3)) { value = getBoolean(L, 3) ? 1 : 0; @@ -50,11 +50,11 @@ int CombatFunctions::luaCombatSetFormula(lua_State* L) { return 1; } - formulaType_t type = getNumber<formulaType_t>(L, 2); - double mina = getNumber<double>(L, 3); - double minb = getNumber<double>(L, 4); - double maxa = getNumber<double>(L, 5); - double maxb = getNumber<double>(L, 6); + const formulaType_t type = getNumber<formulaType_t>(L, 2); + const double mina = getNumber<double>(L, 3); + const double minb = getNumber<double>(L, 4); + const double maxa = getNumber<double>(L, 5); + const double maxb = getNumber<double>(L, 6); combat->setPlayerCombatValues(type, mina, minb, maxa, maxb); pushBoolean(L, true); return 1; @@ -88,7 +88,7 @@ int CombatFunctions::luaCombatSetArea(lua_State* L) { int CombatFunctions::luaCombatSetCondition(lua_State* L) { // combat:addCondition(condition) - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 2); + const std::shared_ptr<Condition> &condition = getUserdataShared<Condition>(L, 2); auto* combat = getUserdata<Combat>(L, 1); if (combat && condition) { combat->addCondition(condition->clone()); @@ -107,7 +107,7 @@ int CombatFunctions::luaCombatSetCallback(lua_State* L) { return 1; } - CallBackParam_t key = getNumber<CallBackParam_t>(L, 2); + const CallBackParam_t key = getNumber<CallBackParam_t>(L, 2); if (!combat->setCallback(key)) { lua_pushnil(L); return 1; @@ -145,14 +145,14 @@ int CombatFunctions::luaCombatExecute(lua_State* L) { } if (isUserdata(L, 2)) { - LuaData_t type = getUserdataType(L, 2); + const LuaData_t type = getUserdataType(L, 2); if (type != LuaData_t::Player && type != LuaData_t::Monster && type != LuaData_t::Npc) { pushBoolean(L, false); return 1; } } - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); const LuaVariant &variant = getVariant(L, 3); combat->setInstantSpellName(variant.instantName); @@ -160,7 +160,7 @@ int CombatFunctions::luaCombatExecute(lua_State* L) { bool result = true; switch (variant.type) { case VARIANT_NUMBER: { - std::shared_ptr<Creature> target = g_game().getCreatureByID(variant.number); + const std::shared_ptr<Creature> &target = g_game().getCreatureByID(variant.number); if (!target) { pushBoolean(L, false); return 1; @@ -190,7 +190,7 @@ int CombatFunctions::luaCombatExecute(lua_State* L) { } case VARIANT_STRING: { - std::shared_ptr<Player> target = g_game().getPlayerByName(variant.text); + const std::shared_ptr<Player> &target = g_game().getPlayerByName(variant.text); if (!target) { pushBoolean(L, false); return 1; diff --git a/src/lua/functions/creatures/combat/combat_functions.hpp b/src/lua/functions/creatures/combat/combat_functions.hpp index e031713e98e..a24b7c63bdd 100644 --- a/src/lua/functions/creatures/combat/combat_functions.hpp +++ b/src/lua/functions/creatures/combat/combat_functions.hpp @@ -16,6 +16,12 @@ class CombatFunctions final : LuaScriptInterface { public: + explicit CombatFunctions(lua_State* L) : + LuaScriptInterface("CombatFunctions") { + init(L); + } + ~CombatFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Combat", "", CombatFunctions::luaCombatCreate); registerMetaMethod(L, "Combat", "__eq", CombatFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/combat/condition_functions.cpp b/src/lua/functions/creatures/combat/condition_functions.cpp index 7f4098e701e..ec65d5bc196 100644 --- a/src/lua/functions/creatures/combat/condition_functions.cpp +++ b/src/lua/functions/creatures/combat/condition_functions.cpp @@ -15,15 +15,15 @@ int ConditionFunctions::luaConditionCreate(lua_State* L) { // Condition(conditionType, conditionId = CONDITIONID_COMBAT, subid = 0, isPersistent = false) - ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); + const ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); if (conditionType == CONDITION_NONE) { reportErrorFunc("Invalid condition type"); return 1; } - ConditionId_t conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); - uint32_t subId = getNumber<uint32_t>(L, 4, 0); - bool isPersistent = getBoolean(L, 5, false); + const auto conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); + const auto subId = getNumber<uint32_t>(L, 4, 0); + const bool isPersistent = getBoolean(L, 5, false); const auto &condition = Condition::createCondition(conditionId, conditionType, 0, 0, false, subId, isPersistent); if (condition) { @@ -46,7 +46,7 @@ int ConditionFunctions::luaConditionDelete(lua_State* L) { int ConditionFunctions::luaConditionGetId(lua_State* L) { // condition:getId() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { lua_pushnumber(L, condition->getId()); } else { @@ -57,7 +57,7 @@ int ConditionFunctions::luaConditionGetId(lua_State* L) { int ConditionFunctions::luaConditionGetSubId(lua_State* L) { // condition:getSubId() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { lua_pushnumber(L, condition->getSubId()); } else { @@ -68,7 +68,7 @@ int ConditionFunctions::luaConditionGetSubId(lua_State* L) { int ConditionFunctions::luaConditionGetType(lua_State* L) { // condition:getType() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { lua_pushnumber(L, condition->getType()); } else { @@ -79,9 +79,9 @@ int ConditionFunctions::luaConditionGetType(lua_State* L) { int ConditionFunctions::luaConditionGetIcons(lua_State* L) { // condition:getIcons() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { - auto icons = condition->getIcons(); + const auto icons = condition->getIcons(); lua_newtable(L); // Creates a new table on the Lua stack int index = 1; for (const auto &icon : icons) { @@ -96,7 +96,7 @@ int ConditionFunctions::luaConditionGetIcons(lua_State* L) { int ConditionFunctions::luaConditionGetEndTime(lua_State* L) { // condition:getEndTime() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { lua_pushnumber(L, condition->getEndTime()); } else { @@ -107,7 +107,7 @@ int ConditionFunctions::luaConditionGetEndTime(lua_State* L) { int ConditionFunctions::luaConditionClone(lua_State* L) { // condition:clone() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { pushUserdata<Condition>(L, condition->clone()); setMetatable(L, -1, "Condition"); @@ -119,7 +119,7 @@ int ConditionFunctions::luaConditionClone(lua_State* L) { int ConditionFunctions::luaConditionGetTicks(lua_State* L) { // condition:getTicks() - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { lua_pushnumber(L, condition->getTicks()); } else { @@ -130,8 +130,8 @@ int ConditionFunctions::luaConditionGetTicks(lua_State* L) { int ConditionFunctions::luaConditionSetTicks(lua_State* L) { // condition:setTicks(ticks) - int32_t ticks = getNumber<int32_t>(L, 2); - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const int32_t ticks = getNumber<int32_t>(L, 2); + const auto &condition = getUserdataShared<Condition>(L, 1); if (condition) { condition->setTicks(ticks); pushBoolean(L, true); @@ -143,13 +143,13 @@ int ConditionFunctions::luaConditionSetTicks(lua_State* L) { int ConditionFunctions::luaConditionSetParameter(lua_State* L) { // condition:setParameter(key, value) - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 1); if (!condition) { lua_pushnil(L); return 1; } - ConditionParam_t key = getNumber<ConditionParam_t>(L, 2); + const ConditionParam_t key = getNumber<ConditionParam_t>(L, 2); int32_t value; if (isBoolean(L, 3)) { value = getBoolean(L, 3) ? 1 : 0; @@ -163,11 +163,11 @@ int ConditionFunctions::luaConditionSetParameter(lua_State* L) { int ConditionFunctions::luaConditionSetFormula(lua_State* L) { // condition:setFormula(mina, minb, maxa, maxb) - double maxb = getNumber<double>(L, 5); - double maxa = getNumber<double>(L, 4); - double minb = getNumber<double>(L, 3); - double mina = getNumber<double>(L, 2); - std::shared_ptr<ConditionSpeed> condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionSpeed>(); + const double maxb = getNumber<double>(L, 5); + const double maxa = getNumber<double>(L, 4); + const double minb = getNumber<double>(L, 3); + const double mina = getNumber<double>(L, 2); + const std::shared_ptr<ConditionSpeed> &condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionSpeed>(); if (condition) { condition->setFormulaVars(mina, minb, maxa, maxb); pushBoolean(L, true); @@ -200,7 +200,7 @@ int ConditionFunctions::luaConditionSetOutfit(lua_State* L) { outfit.lookTypeEx = getNumber<uint16_t>(L, 2); } - std::shared_ptr<ConditionOutfit> condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionOutfit>(); + const std::shared_ptr<ConditionOutfit> &condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionOutfit>(); if (condition) { condition->setOutfit(outfit); pushBoolean(L, true); @@ -212,10 +212,10 @@ int ConditionFunctions::luaConditionSetOutfit(lua_State* L) { int ConditionFunctions::luaConditionAddDamage(lua_State* L) { // condition:addDamage(rounds, time, value) - int32_t value = getNumber<int32_t>(L, 4); - int32_t time = getNumber<int32_t>(L, 3); - int32_t rounds = getNumber<int32_t>(L, 2); - std::shared_ptr<ConditionDamage> condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionDamage>(); + const int32_t value = getNumber<int32_t>(L, 4); + const int32_t time = getNumber<int32_t>(L, 3); + const int32_t rounds = getNumber<int32_t>(L, 2); + const std::shared_ptr<ConditionDamage> &condition = getUserdataShared<Condition>(L, 1)->dynamic_self_cast<ConditionDamage>(); if (condition) { pushBoolean(L, condition->addDamage(rounds, time, value)); } else { diff --git a/src/lua/functions/creatures/combat/condition_functions.hpp b/src/lua/functions/creatures/combat/condition_functions.hpp index 938c5170542..931a4fc2f5e 100644 --- a/src/lua/functions/creatures/combat/condition_functions.hpp +++ b/src/lua/functions/creatures/combat/condition_functions.hpp @@ -13,6 +13,12 @@ class ConditionFunctions final : LuaScriptInterface { public: + explicit ConditionFunctions(lua_State* L) : + LuaScriptInterface("ConditionFunctions") { + init(L); + } + ~ConditionFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Condition", "", ConditionFunctions::luaConditionCreate); registerMetaMethod(L, "Condition", "__eq", ConditionFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/combat/spell_functions.cpp b/src/lua/functions/creatures/combat/spell_functions.cpp index a7ffac63a46..69214aefd5b 100644 --- a/src/lua/functions/creatures/combat/spell_functions.cpp +++ b/src/lua/functions/creatures/combat/spell_functions.cpp @@ -27,7 +27,7 @@ int SpellFunctions::luaSpellCreate(lua_State* L) { if (isNumber(L, 2)) { uint16_t id = getNumber<uint16_t>(L, 2); - std::shared_ptr<RuneSpell> rune = g_spells().getRuneSpell(id); + const auto &rune = g_spells().getRuneSpell(id); if (rune) { pushUserdata<Spell>(L, rune); @@ -37,8 +37,8 @@ int SpellFunctions::luaSpellCreate(lua_State* L) { spellType = static_cast<SpellType_t>(id); } else if (isString(L, 2)) { - std::string arg = getString(L, 2); - std::shared_ptr<InstantSpell> instant = g_spells().getInstantSpellByName(arg); + const std::string arg = getString(L, 2); + auto instant = g_spells().getInstantSpellByName(arg); if (instant) { pushUserdata<Spell>(L, instant); setMetatable(L, -1, "Spell"); @@ -50,14 +50,14 @@ int SpellFunctions::luaSpellCreate(lua_State* L) { setMetatable(L, -1, "Spell"); return 1; } - std::shared_ptr<RuneSpell> rune = g_spells().getRuneSpellByName(arg); + const auto &rune = g_spells().getRuneSpellByName(arg); if (rune) { pushUserdata<Spell>(L, rune); setMetatable(L, -1, "Spell"); return 1; } - std::string tmp = asLowerCaseString(arg); + const std::string tmp = asLowerCaseString(arg); if (tmp == "instant") { spellType = SPELL_INSTANT; } else if (tmp == "rune") { @@ -66,13 +66,13 @@ int SpellFunctions::luaSpellCreate(lua_State* L) { } if (spellType == SPELL_INSTANT) { - auto spell = std::make_shared<InstantSpell>(getScriptEnv()->getScriptInterface()); + const auto &spell = std::make_shared<InstantSpell>(getScriptEnv()->getScriptInterface()); pushUserdata<Spell>(L, spell); setMetatable(L, -1, "Spell"); spell->spellType = SPELL_INSTANT; return 1; } else if (spellType == SPELL_RUNE) { - auto runeSpell = std::make_shared<RuneSpell>(getScriptEnv()->getScriptInterface()); + const auto &runeSpell = std::make_shared<RuneSpell>(getScriptEnv()->getScriptInterface()); pushUserdata<Spell>(L, runeSpell); setMetatable(L, -1, "Spell"); runeSpell->spellType = SPELL_RUNE; @@ -85,10 +85,10 @@ int SpellFunctions::luaSpellCreate(lua_State* L) { int SpellFunctions::luaSpellOnCastSpell(lua_State* L) { // spell:onCastSpell(callback) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (spell->spellType == SPELL_INSTANT) { - const auto spellBase = getUserdataShared<Spell>(L, 1); + const auto &spellBase = getUserdataShared<Spell>(L, 1); const auto instant = std::static_pointer_cast<InstantSpell>(spellBase); if (!instant->loadCallback()) { pushBoolean(L, false); @@ -97,8 +97,8 @@ int SpellFunctions::luaSpellOnCastSpell(lua_State* L) { instant->setLoadedCallback(true); pushBoolean(L, true); } else if (spell->spellType == SPELL_RUNE) { - std::shared_ptr<Spell> spellBase = getUserdataShared<Spell>(L, 1); - std::shared_ptr<RuneSpell> rune = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &rune = std::static_pointer_cast<RuneSpell>(spellBase); if (!rune->loadCallback()) { pushBoolean(L, false); return 1; @@ -114,7 +114,7 @@ int SpellFunctions::luaSpellOnCastSpell(lua_State* L) { int SpellFunctions::luaSpellRegister(lua_State* L) { // spell:register() - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); @@ -122,16 +122,16 @@ int SpellFunctions::luaSpellRegister(lua_State* L) { } if (spell->spellType == SPELL_INSTANT) { - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto instant = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &instant = std::static_pointer_cast<InstantSpell>(spellBase); if (!instant->isLoadedCallback()) { pushBoolean(L, false); return 1; } pushBoolean(L, g_spells().registerInstantLuaEvent(instant)); } else if (spell->spellType == SPELL_RUNE) { - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto rune = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &rune = std::static_pointer_cast<RuneSpell>(spellBase); if (rune->getMagicLevel() != 0 || rune->getLevel() != 0) { // Change information in the ItemType to get accurate description ItemType &iType = Item::items.getItemType(rune->getRuneItemId()); @@ -155,7 +155,7 @@ int SpellFunctions::luaSpellRegister(lua_State* L) { int SpellFunctions::luaSpellName(lua_State* L) { // spell:name(name) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushString(L, spell->getName()); @@ -171,7 +171,7 @@ int SpellFunctions::luaSpellName(lua_State* L) { int SpellFunctions::luaSpellId(lua_State* L) { // spell:id(id) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (spell->spellType != SPELL_INSTANT && spell->spellType != SPELL_RUNE) { reportErrorFunc("The method: 'spell:id(id)' is only for use of instant spells and rune spells"); @@ -192,14 +192,14 @@ int SpellFunctions::luaSpellId(lua_State* L) { int SpellFunctions::luaSpellGroup(lua_State* L) { // spell:group(primaryGroup[, secondaryGroup]) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getGroup()); lua_pushnumber(L, spell->getSecondaryGroup()); return 2; } else if (lua_gettop(L) == 2) { - SpellGroup_t group = getNumber<SpellGroup_t>(L, 2); + auto group = getNumber<SpellGroup_t>(L, 2); if (group) { spell->setGroup(group); pushBoolean(L, true); @@ -223,8 +223,8 @@ int SpellFunctions::luaSpellGroup(lua_State* L) { return 1; } } else { - SpellGroup_t primaryGroup = getNumber<SpellGroup_t>(L, 2); - SpellGroup_t secondaryGroup = getNumber<SpellGroup_t>(L, 2); + auto primaryGroup = getNumber<SpellGroup_t>(L, 2); + auto secondaryGroup = getNumber<SpellGroup_t>(L, 2); if (primaryGroup && secondaryGroup) { spell->setGroup(primaryGroup); spell->setSecondaryGroup(secondaryGroup); @@ -267,7 +267,7 @@ int SpellFunctions::luaSpellGroup(lua_State* L) { int SpellFunctions::luaSpellCastSound(lua_State* L) { // get: spell:castSound() set: spell:castSound(effect) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast<uint16_t>(spell->soundCastEffect)); @@ -283,7 +283,7 @@ int SpellFunctions::luaSpellCastSound(lua_State* L) { int SpellFunctions::luaSpellImpactSound(lua_State* L) { // get: spell:impactSound() set: spell:impactSound(effect) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast<uint16_t>(spell->soundImpactEffect)); @@ -299,7 +299,7 @@ int SpellFunctions::luaSpellImpactSound(lua_State* L) { int SpellFunctions::luaSpellCooldown(lua_State* L) { // spell:cooldown(cooldown) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getCooldown()); @@ -315,7 +315,7 @@ int SpellFunctions::luaSpellCooldown(lua_State* L) { int SpellFunctions::luaSpellGroupCooldown(lua_State* L) { // spell:groupCooldown(primaryGroupCd[, secondaryGroupCd]) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getGroupCooldown()); @@ -337,7 +337,7 @@ int SpellFunctions::luaSpellGroupCooldown(lua_State* L) { int SpellFunctions::luaSpellLevel(lua_State* L) { // spell:level(lvl) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getLevel()); @@ -353,7 +353,7 @@ int SpellFunctions::luaSpellLevel(lua_State* L) { int SpellFunctions::luaSpellMagicLevel(lua_State* L) { // spell:magicLevel(lvl) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getMagicLevel()); @@ -369,7 +369,7 @@ int SpellFunctions::luaSpellMagicLevel(lua_State* L) { int SpellFunctions::luaSpellMana(lua_State* L) { // spell:mana(mana) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getMana()); @@ -385,7 +385,7 @@ int SpellFunctions::luaSpellMana(lua_State* L) { int SpellFunctions::luaSpellManaPercent(lua_State* L) { // spell:manaPercent(percent) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getManaPercent()); @@ -401,7 +401,7 @@ int SpellFunctions::luaSpellManaPercent(lua_State* L) { int SpellFunctions::luaSpellSoul(lua_State* L) { // spell:soul(soul) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getSoulCost()); @@ -417,7 +417,7 @@ int SpellFunctions::luaSpellSoul(lua_State* L) { int SpellFunctions::luaSpellRange(lua_State* L) { // spell:range(range) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_pushnumber(L, spell->getRange()); @@ -433,7 +433,7 @@ int SpellFunctions::luaSpellRange(lua_State* L) { int SpellFunctions::luaSpellPremium(lua_State* L) { // spell:isPremium(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->isPremium()); @@ -449,7 +449,7 @@ int SpellFunctions::luaSpellPremium(lua_State* L) { int SpellFunctions::luaSpellEnabled(lua_State* L) { // spell:isEnabled(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->isEnabled()); @@ -465,7 +465,7 @@ int SpellFunctions::luaSpellEnabled(lua_State* L) { int SpellFunctions::luaSpellNeedTarget(lua_State* L) { // spell:needTarget(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getNeedTarget()); @@ -481,7 +481,7 @@ int SpellFunctions::luaSpellNeedTarget(lua_State* L) { int SpellFunctions::luaSpellNeedWeapon(lua_State* L) { // spell:needWeapon(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getNeedWeapon()); @@ -497,7 +497,7 @@ int SpellFunctions::luaSpellNeedWeapon(lua_State* L) { int SpellFunctions::luaSpellNeedLearn(lua_State* L) { // spell:needLearn(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getNeedLearn()); @@ -513,7 +513,7 @@ int SpellFunctions::luaSpellNeedLearn(lua_State* L) { int SpellFunctions::luaSpellSelfTarget(lua_State* L) { // spell:isSelfTarget(bool) - if (const auto spell = getUserdataShared<Spell>(L, 1)) { + if (const auto &spell = getUserdataShared<Spell>(L, 1)) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getSelfTarget()); } else { @@ -528,7 +528,7 @@ int SpellFunctions::luaSpellSelfTarget(lua_State* L) { int SpellFunctions::luaSpellBlocking(lua_State* L) { // spell:isBlocking(blockingSolid, blockingCreature) - if (const auto spell = getUserdataShared<Spell>(L, 1)) { + if (const auto &spell = getUserdataShared<Spell>(L, 1)) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getBlockingSolid()); pushBoolean(L, spell->getBlockingCreature()); @@ -546,7 +546,7 @@ int SpellFunctions::luaSpellBlocking(lua_State* L) { int SpellFunctions::luaSpellAggressive(lua_State* L) { // spell:isAggressive(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getAggressive()); @@ -562,7 +562,7 @@ int SpellFunctions::luaSpellAggressive(lua_State* L) { int SpellFunctions::luaSpellAllowOnSelf(lua_State* L) { // spell:allowOnSelf(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getAllowOnSelf()); @@ -578,7 +578,7 @@ int SpellFunctions::luaSpellAllowOnSelf(lua_State* L) { int SpellFunctions::luaSpellPzLocked(lua_State* L) { // spell:isPzLocked(bool) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { pushBoolean(L, spell->getLockedPZ()); @@ -594,12 +594,12 @@ int SpellFunctions::luaSpellPzLocked(lua_State* L) { int SpellFunctions::luaSpellVocation(lua_State* L) { // spell:vocation(vocation) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (spell) { if (lua_gettop(L) == 1) { lua_createtable(L, 0, 0); auto it = 0; - for (auto voc : spell->getVocMap()) { + for (const auto &voc : spell->getVocMap()) { ++it; std::string s = std::to_string(it); const char* pchar = s.c_str(); @@ -608,11 +608,11 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { } setMetatable(L, -1, "Spell"); } else { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc for (int i = 0; i < parameters; ++i) { if (getString(L, 2 + i).find(';') != std::string::npos) { std::vector<std::string> vocList = explodeString(getString(L, 2 + i), ";"); - int32_t vocationId = g_vocations().getVocationId(vocList[0]); + const int32_t vocationId = g_vocations().getVocationId(vocList[0]); if (!vocList.empty()) { if (vocList[1] == "true") { spell->addVocMap(vocationId, true); @@ -621,7 +621,7 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { } } } else { - int32_t vocationId = g_vocations().getVocationId(getString(L, 2 + i)); + const int32_t vocationId = g_vocations().getVocationId(getString(L, 2 + i)); spell->addVocMap(vocationId, false); } } @@ -636,8 +636,8 @@ int SpellFunctions::luaSpellVocation(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellWords(lua_State* L) { // spell:words(words[, separator = ""]) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -667,8 +667,8 @@ int SpellFunctions::luaSpellWords(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellNeedDirection(lua_State* L) { // spell:needDirection(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -691,8 +691,8 @@ int SpellFunctions::luaSpellNeedDirection(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellHasParams(lua_State* L) { // spell:hasParams(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -715,8 +715,8 @@ int SpellFunctions::luaSpellHasParams(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellHasPlayerNameParam(lua_State* L) { // spell:hasPlayerNameParam(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -739,8 +739,8 @@ int SpellFunctions::luaSpellHasPlayerNameParam(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellNeedCasterTargetOrDirection(lua_State* L) { // spell:needCasterTargetOrDirection(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -763,8 +763,8 @@ int SpellFunctions::luaSpellNeedCasterTargetOrDirection(lua_State* L) { // only for InstantSpells int SpellFunctions::luaSpellIsBlockingWalls(lua_State* L) { // spell:blockWalls(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<InstantSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<InstantSpell>(spellBase); if (spell) { // if spell != SPELL_INSTANT, it means that this actually is no InstantSpell, so we return nil if (spell->spellType != SPELL_INSTANT) { @@ -787,8 +787,8 @@ int SpellFunctions::luaSpellIsBlockingWalls(lua_State* L) { // only for RuneSpells int SpellFunctions::luaSpellRuneId(lua_State* L) { // spell:runeId(id) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<RuneSpell>(spellBase); if (spell) { // if spell != SPELL_RUNE, it means that this actually is no RuneSpell, so we return nil if (spell->spellType != SPELL_RUNE) { @@ -811,8 +811,8 @@ int SpellFunctions::luaSpellRuneId(lua_State* L) { // only for RuneSpells int SpellFunctions::luaSpellCharges(lua_State* L) { // spell:charges(charges) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<RuneSpell>(spellBase); if (spell) { // if spell != SPELL_RUNE, it means that this actually is no RuneSpell, so we return nil if (spell->spellType != SPELL_RUNE) { @@ -835,8 +835,8 @@ int SpellFunctions::luaSpellCharges(lua_State* L) { // only for RuneSpells int SpellFunctions::luaSpellAllowFarUse(lua_State* L) { // spell:allowFarUse(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<RuneSpell>(spellBase); if (spell) { // if spell != SPELL_RUNE, it means that this actually is no RuneSpell, so we return nil if (spell->spellType != SPELL_RUNE) { @@ -859,8 +859,8 @@ int SpellFunctions::luaSpellAllowFarUse(lua_State* L) { // only for RuneSpells int SpellFunctions::luaSpellBlockWalls(lua_State* L) { // spell:blockWalls(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<RuneSpell>(spellBase); if (spell) { // if spell != SPELL_RUNE, it means that this actually is no RuneSpell, so we return nil if (spell->spellType != SPELL_RUNE) { @@ -883,8 +883,8 @@ int SpellFunctions::luaSpellBlockWalls(lua_State* L) { // only for RuneSpells int SpellFunctions::luaSpellCheckFloor(lua_State* L) { // spell:checkFloor(bool) - const auto spellBase = getUserdataShared<Spell>(L, 1); - const auto spell = std::static_pointer_cast<RuneSpell>(spellBase); + const auto &spellBase = getUserdataShared<Spell>(L, 1); + const auto &spell = std::static_pointer_cast<RuneSpell>(spellBase); if (spell) { // if spell != SPELL_RUNE, it means that this actually is no RuneSpell, so we return nil if (spell->spellType != SPELL_RUNE) { @@ -907,8 +907,8 @@ int SpellFunctions::luaSpellCheckFloor(lua_State* L) { // Wheel of destiny int SpellFunctions::luaSpellManaWOD(lua_State* L) { // spell:manaWOD(grade, mana) - const auto spell = getUserdataShared<Spell>(L, 1); - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const auto &spell = getUserdataShared<Spell>(L, 1); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); @@ -927,14 +927,14 @@ int SpellFunctions::luaSpellManaWOD(lua_State* L) { int SpellFunctions::luaSpellCooldownWOD(lua_State* L) { // spell:cooldownWOD(grade, time) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::COOLDOWN, grade)); } else { @@ -947,14 +947,14 @@ int SpellFunctions::luaSpellCooldownWOD(lua_State* L) { int SpellFunctions::luaSpellGroupCooldownWOD(lua_State* L) { // spell:groupCooldownWOD(grade, time) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::GROUP_COOLDOWN, grade)); } else { @@ -967,14 +967,14 @@ int SpellFunctions::luaSpellGroupCooldownWOD(lua_State* L) { int SpellFunctions::luaSpellSecondaryGroupCooldownWOD(lua_State* L) { // spell:secondaryGroupCooldownWOD(grade, time) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::SECONDARY_GROUP_COOLDOWN, grade)); } else { @@ -987,18 +987,18 @@ int SpellFunctions::luaSpellSecondaryGroupCooldownWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseManaLeechWOD(lua_State* L) { // spell:increaseManaLeechWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::MANA_LEECH, grade)); } else { - int32_t value = getNumber<int32_t>(L, 3); + const int32_t value = getNumber<int32_t>(L, 3); if (value > 0) { spell->setWheelOfDestinyBoost(WheelSpellBoost_t::MANA_LEECH_CHANCE, grade, 100); } else { @@ -1013,18 +1013,18 @@ int SpellFunctions::luaSpellIncreaseManaLeechWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaselifeLeechWOD(lua_State* L) { // spell:increaselifeLeechWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::LIFE_LEECH, grade)); } else { - int32_t value = getNumber<int32_t>(L, 3); + const int32_t value = getNumber<int32_t>(L, 3); if (value > 0) { spell->setWheelOfDestinyBoost(WheelSpellBoost_t::LIFE_LEECH_CHANCE, grade, 100); } else { @@ -1039,14 +1039,14 @@ int SpellFunctions::luaSpellIncreaselifeLeechWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseDamageWOD(lua_State* L) { // spell:increaseDamageWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::DAMAGE, grade)); } else { @@ -1059,14 +1059,14 @@ int SpellFunctions::luaSpellIncreaseDamageWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseDamageReductionWOD(lua_State* L) { // spell:increaseDamageReductionWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::DAMAGE_REDUCTION, grade)); } else { @@ -1079,14 +1079,14 @@ int SpellFunctions::luaSpellIncreaseDamageReductionWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseHealWOD(lua_State* L) { // spell:increaseHealWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::HEAL, grade)); } else { @@ -1099,14 +1099,14 @@ int SpellFunctions::luaSpellIncreaseHealWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseCriticalDamageWOD(lua_State* L) { // spell:increaseCriticalDamageWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::CRITICAL_DAMAGE, grade)); } else { @@ -1119,14 +1119,14 @@ int SpellFunctions::luaSpellIncreaseCriticalDamageWOD(lua_State* L) { int SpellFunctions::luaSpellIncreaseCriticalChanceWOD(lua_State* L) { // spell:increaseCriticalChanceWOD(grade, value) - const auto spell = getUserdataShared<Spell>(L, 1); + const auto &spell = getUserdataShared<Spell>(L, 1); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); return 1; } - WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); + const WheelSpellGrade_t grade = getNumber<WheelSpellGrade_t>(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, spell->getWheelOfDestinyBoost(WheelSpellBoost_t::CRITICAL_CHANCE, grade)); } else { diff --git a/src/lua/functions/creatures/combat/spell_functions.hpp b/src/lua/functions/creatures/combat/spell_functions.hpp index 7f2487ba16f..1a7c417f9fd 100644 --- a/src/lua/functions/creatures/combat/spell_functions.hpp +++ b/src/lua/functions/creatures/combat/spell_functions.hpp @@ -13,6 +13,12 @@ class SpellFunctions final : LuaScriptInterface { public: + explicit SpellFunctions(lua_State* L) : + LuaScriptInterface("SpellFunctions") { + init(L); + } + ~SpellFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Spell", "", SpellFunctions::luaSpellCreate); registerMetaMethod(L, "Spell", "__eq", SpellFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/combat/variant_functions.cpp b/src/lua/functions/creatures/combat/variant_functions.cpp index 3b0299983fd..a776ac6476a 100644 --- a/src/lua/functions/creatures/combat/variant_functions.cpp +++ b/src/lua/functions/creatures/combat/variant_functions.cpp @@ -17,7 +17,7 @@ int VariantFunctions::luaVariantCreate(lua_State* L) { // Variant(number or string or position or thing) LuaVariant variant; if (isUserdata(L, 2)) { - if (std::shared_ptr<Thing> thing = getThing(L, 2)) { + if (const auto &thing = getThing(L, 2)) { variant.type = VARIANT_TARGETPOSITION; variant.pos = thing->getPosition(); } diff --git a/src/lua/functions/creatures/combat/variant_functions.hpp b/src/lua/functions/creatures/combat/variant_functions.hpp index c62bbc114a8..eba239b221c 100644 --- a/src/lua/functions/creatures/combat/variant_functions.hpp +++ b/src/lua/functions/creatures/combat/variant_functions.hpp @@ -13,6 +13,12 @@ class VariantFunctions final : LuaScriptInterface { public: + explicit VariantFunctions(lua_State* L) : + LuaScriptInterface("VariantFunctions") { + init(L); + } + ~VariantFunctions() override = default; + static void init(lua_State* L) { registerClass(L, "Variant", "", VariantFunctions::luaVariantCreate); diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index 85f5897c8ca..c38139d5122 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -22,7 +22,7 @@ int CreatureFunctions::luaCreatureCreate(lua_State* L) { } else if (isString(L, 2)) { creature = g_game().getCreatureByName(getString(L, 2)); } else if (isUserdata(L, 2)) { - LuaData_t type = getUserdataType(L, 2); + const LuaData_t type = getUserdataType(L, 2); if (type != LuaData_t::Player && type != LuaData_t::Monster && type != LuaData_t::Npc) { lua_pushnil(L); return 1; @@ -43,13 +43,13 @@ int CreatureFunctions::luaCreatureCreate(lua_State* L) { int CreatureFunctions::luaCreatureGetEvents(lua_State* L) { // creature:getEvents(type) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - CreatureEventType_t eventType = getNumber<CreatureEventType_t>(L, 2); + const CreatureEventType_t eventType = getNumber<CreatureEventType_t>(L, 2); const auto eventList = creature->getCreatureEvents(eventType); lua_createtable(L, static_cast<int>(eventList.size()), 0); @@ -63,7 +63,7 @@ int CreatureFunctions::luaCreatureGetEvents(lua_State* L) { int CreatureFunctions::luaCreatureRegisterEvent(lua_State* L) { // creature:registerEvent(name) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { const std::string &name = getString(L, 2); pushBoolean(L, creature->registerCreatureEvent(name)); @@ -76,7 +76,7 @@ int CreatureFunctions::luaCreatureRegisterEvent(lua_State* L) { int CreatureFunctions::luaCreatureUnregisterEvent(lua_State* L) { // creature:unregisterEvent(name) const std::string &name = getString(L, 2); - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->unregisterCreatureEvent(name)); } else { @@ -87,7 +87,7 @@ int CreatureFunctions::luaCreatureUnregisterEvent(lua_State* L) { int CreatureFunctions::luaCreatureIsRemoved(lua_State* L) { // creature:isRemoved() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->isRemoved()); } else { @@ -104,7 +104,7 @@ int CreatureFunctions::luaCreatureIsCreature(lua_State* L) { int CreatureFunctions::luaCreatureIsInGhostMode(lua_State* L) { // creature:isInGhostMode() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->isInGhostMode()); } else { @@ -115,7 +115,7 @@ int CreatureFunctions::luaCreatureIsInGhostMode(lua_State* L) { int CreatureFunctions::luaCreatureIsHealthHidden(lua_State* L) { // creature:isHealthHidden() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->isHealthHidden()); } else { @@ -126,7 +126,7 @@ int CreatureFunctions::luaCreatureIsHealthHidden(lua_State* L) { int CreatureFunctions::luaCreatureCanSee(lua_State* L) { // creature:canSee(position) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { const Position &position = getPosition(L, 2); pushBoolean(L, creature->canSee(position)); @@ -138,9 +138,9 @@ int CreatureFunctions::luaCreatureCanSee(lua_State* L) { int CreatureFunctions::luaCreatureCanSeeCreature(lua_State* L) { // creature:canSeeCreature(creature) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { - std::shared_ptr<Creature> otherCreature = getCreature(L, 2); + const auto &otherCreature = getCreature(L, 2); pushBoolean(L, creature->canSeeCreature(otherCreature)); } else { lua_pushnil(L); @@ -150,13 +150,13 @@ int CreatureFunctions::luaCreatureCanSeeCreature(lua_State* L) { int CreatureFunctions::luaCreatureGetParent(lua_State* L) { // creature:getParent() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr<Cylinder> parent = creature->getParent(); + const auto &parent = creature->getParent(); if (!parent) { lua_pushnil(L); return 1; @@ -168,7 +168,7 @@ int CreatureFunctions::luaCreatureGetParent(lua_State* L) { int CreatureFunctions::luaCreatureGetId(lua_State* L) { // creature:getId() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getID()); } else { @@ -179,7 +179,7 @@ int CreatureFunctions::luaCreatureGetId(lua_State* L) { int CreatureFunctions::luaCreatureGetName(lua_State* L) { // creature:getName() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushString(L, creature->getName()); } else { @@ -190,7 +190,7 @@ int CreatureFunctions::luaCreatureGetName(lua_State* L) { int CreatureFunctions::luaCreatureGetTypeName(lua_State* L) { // creature:getTypeName() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushString(L, creature->getTypeName()); } else { @@ -201,13 +201,13 @@ int CreatureFunctions::luaCreatureGetTypeName(lua_State* L) { int CreatureFunctions::luaCreatureGetTarget(lua_State* L) { // creature:getTarget() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr<Creature> target = creature->getAttackedCreature(); + const auto &target = creature->getAttackedCreature(); if (target) { pushUserdata<Creature>(L, target); setCreatureMetatable(L, -1, target); @@ -219,9 +219,9 @@ int CreatureFunctions::luaCreatureGetTarget(lua_State* L) { int CreatureFunctions::luaCreatureSetTarget(lua_State* L) { // creature:setTarget(target) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { - std::shared_ptr<Creature> target = getCreature(L, 2); + const auto &target = getCreature(L, 2); pushBoolean(L, creature->setAttackedCreature(target)); } else { lua_pushnil(L); @@ -231,13 +231,13 @@ int CreatureFunctions::luaCreatureSetTarget(lua_State* L) { int CreatureFunctions::luaCreatureGetFollowCreature(lua_State* L) { // creature:getFollowCreature() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr<Creature> followCreature = creature->getFollowCreature(); + const auto &followCreature = creature->getFollowCreature(); if (followCreature) { pushUserdata<Creature>(L, followCreature); setCreatureMetatable(L, -1, followCreature); @@ -249,9 +249,9 @@ int CreatureFunctions::luaCreatureGetFollowCreature(lua_State* L) { int CreatureFunctions::luaCreatureSetFollowCreature(lua_State* L) { // creature:setFollowCreature(followedCreature) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { - std::shared_ptr<Creature> followCreature = getCreature(L, 2); + const auto &followCreature = getCreature(L, 2); pushBoolean(L, creature->setFollowCreature(followCreature)); } else { lua_pushnil(L); @@ -261,13 +261,13 @@ int CreatureFunctions::luaCreatureSetFollowCreature(lua_State* L) { int CreatureFunctions::luaCreatureGetMaster(lua_State* L) { // creature:getMaster() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr<Creature> master = creature->getMaster(); + const auto &master = creature->getMaster(); if (!master) { lua_pushnil(L); return 1; @@ -280,7 +280,7 @@ int CreatureFunctions::luaCreatureGetMaster(lua_State* L) { int CreatureFunctions::luaCreatureReload(lua_State* L) { // creature:reload() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -293,7 +293,7 @@ int CreatureFunctions::luaCreatureReload(lua_State* L) { int CreatureFunctions::luaCreatureSetMaster(lua_State* L) { // creature:setMaster(master) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -307,13 +307,13 @@ int CreatureFunctions::luaCreatureSetMaster(lua_State* L) { int CreatureFunctions::luaCreatureGetLight(lua_State* L) { // creature:getLight() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - LightInfo lightInfo = creature->getCreatureLight(); + const LightInfo lightInfo = creature->getCreatureLight(); lua_pushnumber(L, lightInfo.level); lua_pushnumber(L, lightInfo.color); return 2; @@ -321,7 +321,7 @@ int CreatureFunctions::luaCreatureGetLight(lua_State* L) { int CreatureFunctions::luaCreatureSetLight(lua_State* L) { // creature:setLight(color, level) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -338,7 +338,7 @@ int CreatureFunctions::luaCreatureSetLight(lua_State* L) { int CreatureFunctions::luaCreatureGetSpeed(lua_State* L) { // creature:getSpeed() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getSpeed()); } else { @@ -349,14 +349,14 @@ int CreatureFunctions::luaCreatureGetSpeed(lua_State* L) { int CreatureFunctions::luaCreatureSetSpeed(lua_State* L) { // creature:setSpeed(speed) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - int32_t speed = getNumber<int32_t>(L, 2); + const int32_t speed = getNumber<int32_t>(L, 2); g_game().setCreatureSpeed(creature, speed); pushBoolean(L, true); return 1; @@ -364,7 +364,7 @@ int CreatureFunctions::luaCreatureSetSpeed(lua_State* L) { int CreatureFunctions::luaCreatureGetBaseSpeed(lua_State* L) { // creature:getBaseSpeed() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getBaseSpeed()); } else { @@ -375,14 +375,14 @@ int CreatureFunctions::luaCreatureGetBaseSpeed(lua_State* L) { int CreatureFunctions::luaCreatureChangeSpeed(lua_State* L) { // creature:changeSpeed(delta) - std::shared_ptr<Creature> creature = getCreature(L, 1); + const auto &creature = getCreature(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); return 1; } - int32_t delta = getNumber<int32_t>(L, 2); + const int32_t delta = getNumber<int32_t>(L, 2); g_game().changeSpeed(creature, delta); pushBoolean(L, true); return 1; @@ -390,7 +390,7 @@ int CreatureFunctions::luaCreatureChangeSpeed(lua_State* L) { int CreatureFunctions::luaCreatureSetDropLoot(lua_State* L) { // creature:setDropLoot(doDrop) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setDropLoot(getBoolean(L, 2)); pushBoolean(L, true); @@ -402,7 +402,7 @@ int CreatureFunctions::luaCreatureSetDropLoot(lua_State* L) { int CreatureFunctions::luaCreatureSetSkillLoss(lua_State* L) { // creature:setSkillLoss(skillLoss) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setSkillLoss(getBoolean(L, 2)); pushBoolean(L, true); @@ -414,7 +414,7 @@ int CreatureFunctions::luaCreatureSetSkillLoss(lua_State* L) { int CreatureFunctions::luaCreatureGetPosition(lua_State* L) { // creature:getPosition() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushPosition(L, creature->getPosition()); } else { @@ -425,13 +425,13 @@ int CreatureFunctions::luaCreatureGetPosition(lua_State* L) { int CreatureFunctions::luaCreatureGetTile(lua_State* L) { // creature:getTile() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - std::shared_ptr<Tile> tile = creature->getTile(); + const auto &tile = creature->getTile(); if (tile) { pushUserdata<Tile>(L, tile); setMetatable(L, -1, "Tile"); @@ -443,7 +443,7 @@ int CreatureFunctions::luaCreatureGetTile(lua_State* L) { int CreatureFunctions::luaCreatureGetDirection(lua_State* L) { // creature:getDirection() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getDirection()); } else { @@ -454,7 +454,7 @@ int CreatureFunctions::luaCreatureGetDirection(lua_State* L) { int CreatureFunctions::luaCreatureSetDirection(lua_State* L) { // creature:setDirection(direction) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, g_game().internalCreatureTurn(creature, getNumber<Direction>(L, 2))); } else { @@ -465,7 +465,7 @@ int CreatureFunctions::luaCreatureSetDirection(lua_State* L) { int CreatureFunctions::luaCreatureGetHealth(lua_State* L) { // creature:getHealth() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getHealth()); } else { @@ -476,7 +476,7 @@ int CreatureFunctions::luaCreatureGetHealth(lua_State* L) { int CreatureFunctions::luaCreatureSetHealth(lua_State* L) { // creature:setHealth(health) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -495,7 +495,7 @@ int CreatureFunctions::luaCreatureSetHealth(lua_State* L) { int CreatureFunctions::luaCreatureAddHealth(lua_State* L) { // creature:addHealth(healthChange, combatType) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -516,7 +516,7 @@ int CreatureFunctions::luaCreatureAddHealth(lua_State* L) { int CreatureFunctions::luaCreatureGetMaxHealth(lua_State* L) { // creature:getMaxHealth() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getMaxHealth()); } else { @@ -527,7 +527,7 @@ int CreatureFunctions::luaCreatureGetMaxHealth(lua_State* L) { int CreatureFunctions::luaCreatureSetMaxHealth(lua_State* L) { // creature:setMaxHealth(maxHealth) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -547,7 +547,7 @@ int CreatureFunctions::luaCreatureSetMaxHealth(lua_State* L) { int CreatureFunctions::luaCreatureSetHiddenHealth(lua_State* L) { // creature:setHiddenHealth(hide) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setHiddenHealth(getBoolean(L, 2)); g_game().addCreatureHealth(creature); @@ -560,7 +560,7 @@ int CreatureFunctions::luaCreatureSetHiddenHealth(lua_State* L) { int CreatureFunctions::luaCreatureIsMoveLocked(lua_State* L) { // creature:isMoveLocked() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->isMoveLocked()); } else { @@ -571,7 +571,7 @@ int CreatureFunctions::luaCreatureIsMoveLocked(lua_State* L) { int CreatureFunctions::luaCreatureSetMoveLocked(lua_State* L) { // creature:setMoveLocked(moveLocked) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setMoveLocked(getBoolean(L, 2)); pushBoolean(L, true); @@ -583,7 +583,7 @@ int CreatureFunctions::luaCreatureSetMoveLocked(lua_State* L) { int CreatureFunctions::luaCreatureIsDirectionLocked(lua_State* L) { // creature:isDirectionLocked() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->isDirectionLocked()); } else { @@ -594,7 +594,7 @@ int CreatureFunctions::luaCreatureIsDirectionLocked(lua_State* L) { int CreatureFunctions::luaCreatureSetDirectionLocked(lua_State* L) { // creature:setDirectionLocked(directionLocked) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setDirectionLocked(getBoolean(L, 2)); pushBoolean(L, true); @@ -606,7 +606,7 @@ int CreatureFunctions::luaCreatureSetDirectionLocked(lua_State* L) { int CreatureFunctions::luaCreatureGetSkull(lua_State* L) { // creature:getSkull() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getSkull()); } else { @@ -617,7 +617,7 @@ int CreatureFunctions::luaCreatureGetSkull(lua_State* L) { int CreatureFunctions::luaCreatureSetSkull(lua_State* L) { // creature:setSkull(skull) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { creature->setSkull(getNumber<Skulls_t>(L, 2)); pushBoolean(L, true); @@ -629,7 +629,7 @@ int CreatureFunctions::luaCreatureSetSkull(lua_State* L) { int CreatureFunctions::luaCreatureGetOutfit(lua_State* L) { // creature:getOutfit() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushOutfit(L, creature->getCurrentOutfit()); } else { @@ -640,7 +640,7 @@ int CreatureFunctions::luaCreatureGetOutfit(lua_State* L) { int CreatureFunctions::luaCreatureSetOutfit(lua_State* L) { // creature:setOutfit(outfit) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { Outfit_t outfit = getOutfit(L, 2); if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { @@ -659,17 +659,17 @@ int CreatureFunctions::luaCreatureSetOutfit(lua_State* L) { int CreatureFunctions::luaCreatureGetCondition(lua_State* L) { // creature:getCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0]]) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); - auto conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); - auto subId = getNumber<uint32_t>(L, 4, 0); + const ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); + const auto conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); + const auto subId = getNumber<uint32_t>(L, 4, 0); - const std::shared_ptr<Condition> condition = creature->getCondition(conditionType, conditionId, subId); + const auto &condition = creature->getCondition(conditionType, conditionId, subId); if (condition) { pushUserdata<const Condition>(L, condition); setWeakMetatable(L, -1, "Condition"); @@ -681,8 +681,8 @@ int CreatureFunctions::luaCreatureGetCondition(lua_State* L) { int CreatureFunctions::luaCreatureAddCondition(lua_State* L) { // creature:addCondition(condition) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); - std::shared_ptr<Condition> condition = getUserdataShared<Condition>(L, 2); + const auto &creature = getUserdataShared<Creature>(L, 1); + const auto &condition = getUserdataShared<Condition>(L, 2); if (creature && condition) { pushBoolean(L, creature->addCondition(condition->clone())); } else { @@ -693,18 +693,18 @@ int CreatureFunctions::luaCreatureAddCondition(lua_State* L) { int CreatureFunctions::luaCreatureRemoveCondition(lua_State* L) { // creature:removeCondition(conditionType[, conditionId = CONDITIONID_COMBAT[, subId = 0[, force = false]]]) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); - auto conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); - auto subId = getNumber<uint32_t>(L, 4, 0); - const std::shared_ptr<Condition> condition = creature->getCondition(conditionType, conditionId, subId); + const ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); + const auto conditionId = getNumber<ConditionId_t>(L, 3, CONDITIONID_COMBAT); + const auto subId = getNumber<uint32_t>(L, 4, 0); + const auto &condition = creature->getCondition(conditionType, conditionId, subId); if (condition) { - bool force = getBoolean(L, 5, false); + const bool force = getBoolean(L, 5, false); if (subId == 0) { creature->removeCondition(conditionType, conditionId, force); } else { @@ -719,21 +719,21 @@ int CreatureFunctions::luaCreatureRemoveCondition(lua_State* L) { int CreatureFunctions::luaCreatureHasCondition(lua_State* L) { // creature:hasCondition(conditionType[, subId = 0]) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } - ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); - auto subId = getNumber<uint32_t>(L, 3, 0); + const ConditionType_t conditionType = getNumber<ConditionType_t>(L, 2); + const auto subId = getNumber<uint32_t>(L, 3, 0); pushBoolean(L, creature->hasCondition(conditionType, subId)); return 1; } int CreatureFunctions::luaCreatureIsImmune(lua_State* L) { // creature:isImmune(condition or conditionType) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -741,7 +741,7 @@ int CreatureFunctions::luaCreatureIsImmune(lua_State* L) { if (isNumber(L, 2)) { pushBoolean(L, creature->isImmune(getNumber<ConditionType_t>(L, 2))); - } else if (auto condition = getUserdataShared<Condition>(L, 2)) { + } else if (const auto condition = getUserdataShared<Condition>(L, 2)) { pushBoolean(L, creature->isImmune(condition->getType())); } else { lua_pushnil(L); @@ -751,19 +751,19 @@ int CreatureFunctions::luaCreatureIsImmune(lua_State* L) { int CreatureFunctions::luaCreatureRemove(lua_State* L) { // creature:remove([forced = true]) - std::shared_ptr<Creature>* creaturePtr = getRawUserDataShared<Creature>(L, 1); + auto* creaturePtr = getRawUserDataShared<Creature>(L, 1); if (!creaturePtr) { lua_pushnil(L); return 1; } - std::shared_ptr<Creature> creature = *creaturePtr; + const auto &creature = *creaturePtr; if (!creature) { lua_pushnil(L); return 1; } - bool forced = getBoolean(L, 2, true); + const bool forced = getBoolean(L, 2, true); if (const auto &player = creature->getPlayer()) { if (forced) { player->removePlayer(true); @@ -781,10 +781,10 @@ int CreatureFunctions::luaCreatureRemove(lua_State* L) { int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { // creature:teleportTo(position[, pushMovement = false]) - bool pushMovement = getBoolean(L, 3, false); + const bool pushMovement = getBoolean(L, 3, false); const Position &position = getPosition(L, 2); - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature == nullptr) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -792,7 +792,7 @@ int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { } const Position oldPosition = creature->getPosition(); - if (auto ret = g_game().internalTeleport(creature, position, pushMovement); + if (const auto ret = g_game().internalTeleport(creature, position, pushMovement); ret != RETURNVALUE_NOERROR) { g_logger().debug("[{}] Failed to teleport creature {}, on position {}, error code: {}", __FUNCTION__, creature->getName(), oldPosition.toString(), getReturnMessage(ret)); pushBoolean(L, false); @@ -818,7 +818,7 @@ int CreatureFunctions::luaCreatureTeleportTo(lua_State* L) { int CreatureFunctions::luaCreatureSay(lua_State* L) { // creature:say(text[, type = TALKTYPE_MONSTER_SAY[, ghost = false[, target = nullptr[, position]]]]) - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); Position position; if (parameters >= 6) { @@ -835,11 +835,11 @@ int CreatureFunctions::luaCreatureSay(lua_State* L) { target = getCreature(L, 5); } - bool ghost = getBoolean(L, 4, false); + const bool ghost = getBoolean(L, 4, false); - auto type = getNumber<SpeakClasses>(L, 3, TALKTYPE_MONSTER_SAY); + const auto type = getNumber<SpeakClasses>(L, 3, TALKTYPE_MONSTER_SAY); const std::string &text = getString(L, 2); - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -860,14 +860,14 @@ int CreatureFunctions::luaCreatureSay(lua_State* L) { int CreatureFunctions::luaCreatureGetDamageMap(lua_State* L) { // creature:getDamageMap() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } lua_createtable(L, creature->damageMap.size(), 0); - for (auto damageEntry : creature->damageMap) { + for (const auto damageEntry : creature->damageMap) { lua_createtable(L, 0, 2); setField(L, "total", damageEntry.second.total); setField(L, "ticks", damageEntry.second.ticks); @@ -878,7 +878,7 @@ int CreatureFunctions::luaCreatureGetDamageMap(lua_State* L) { int CreatureFunctions::luaCreatureGetSummons(lua_State* L) { // creature:getSummons() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -899,7 +899,7 @@ int CreatureFunctions::luaCreatureGetSummons(lua_State* L) { int CreatureFunctions::luaCreatureHasBeenSummoned(lua_State* L) { // creature:hasBeenSummoned() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushBoolean(L, creature->hasBeenSummoned()); } else { @@ -911,8 +911,8 @@ int CreatureFunctions::luaCreatureHasBeenSummoned(lua_State* L) { int CreatureFunctions::luaCreatureGetDescription(lua_State* L) { // creature:getDescription(distance) - int32_t distance = getNumber<int32_t>(L, 2); - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const int32_t distance = getNumber<int32_t>(L, 2); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { pushString(L, creature->getDescription(distance)); } else { @@ -923,7 +923,7 @@ int CreatureFunctions::luaCreatureGetDescription(lua_State* L) { int CreatureFunctions::luaCreatureGetPathTo(lua_State* L) { // creature:getPathTo(pos[, minTargetDist = 0[, maxTargetDist = 1[, fullPathSearch = true[, clearSight = true[, maxSearchDist = 0]]]]]) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; @@ -943,7 +943,7 @@ int CreatureFunctions::luaCreatureGetPathTo(lua_State* L) { lua_newtable(L); int index = 0; - for (Direction dir : dirList) { + for (const Direction dir : dirList) { lua_pushnumber(L, dir); lua_rawseti(L, -2, ++index); } @@ -956,21 +956,21 @@ int CreatureFunctions::luaCreatureGetPathTo(lua_State* L) { int CreatureFunctions::luaCreatureMove(lua_State* L) { // creature:move(direction) // creature:move(tile[, flags = 0]) - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { lua_pushnil(L); return 1; } if (isNumber(L, 2)) { - Direction direction = getNumber<Direction>(L, 2); + const Direction direction = getNumber<Direction>(L, 2); if (direction > DIRECTION_LAST) { lua_pushnil(L); return 1; } lua_pushnumber(L, g_game().internalMoveCreature(creature, direction, FLAG_NOLIMIT)); } else { - std::shared_ptr<Tile> tile = getUserdataShared<Tile>(L, 2); + const auto &tile = getUserdataShared<Tile>(L, 2); if (!tile) { lua_pushnil(L); return 1; @@ -982,7 +982,7 @@ int CreatureFunctions::luaCreatureMove(lua_State* L) { int CreatureFunctions::luaCreatureGetZoneType(lua_State* L) { // creature:getZoneType() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature) { lua_pushnumber(L, creature->getZoneType()); } else { @@ -993,7 +993,7 @@ int CreatureFunctions::luaCreatureGetZoneType(lua_State* L) { int CreatureFunctions::luaCreatureGetZones(lua_State* L) { // creature:getZones() - std::shared_ptr<Creature> creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (creature == nullptr) { lua_pushnil(L); return 1; @@ -1013,7 +1013,7 @@ int CreatureFunctions::luaCreatureGetZones(lua_State* L) { int CreatureFunctions::luaCreatureSetIcon(lua_State* L) { // creature:setIcon(key, category, icon[, number]) - auto creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1024,10 +1024,10 @@ int CreatureFunctions::luaCreatureSetIcon(lua_State* L) { const auto count = getNumber<uint16_t>(L, 5, 0); CreatureIcon creatureIcon; if (category == CreatureIconCategory_t::Modifications) { - auto icon = getNumber<CreatureIconModifications_t>(L, 4); + const auto icon = getNumber<CreatureIconModifications_t>(L, 4); creatureIcon = CreatureIcon(icon, count); } else { - auto icon = getNumber<CreatureIconQuests_t>(L, 4); + const auto icon = getNumber<CreatureIconQuests_t>(L, 4); creatureIcon = CreatureIcon(icon, count); } @@ -1038,7 +1038,7 @@ int CreatureFunctions::luaCreatureSetIcon(lua_State* L) { int CreatureFunctions::luaCreatureGetIcons(lua_State* L) { // creature:getIcons() - const auto creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1059,7 +1059,7 @@ int CreatureFunctions::luaCreatureGetIcons(lua_State* L) { int CreatureFunctions::luaCreatureGetIcon(lua_State* L) { // creature:getIcon(key) - const auto creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1080,7 +1080,7 @@ int CreatureFunctions::luaCreatureGetIcon(lua_State* L) { int CreatureFunctions::luaCreatureRemoveIcon(lua_State* L) { // creature:removeIcon(key) - auto creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); @@ -1094,7 +1094,7 @@ int CreatureFunctions::luaCreatureRemoveIcon(lua_State* L) { int CreatureFunctions::luaCreatureClearIcons(lua_State* L) { // creature:clearIcons() - auto creature = getUserdataShared<Creature>(L, 1); + const auto &creature = getUserdataShared<Creature>(L, 1); if (!creature) { reportErrorFunc(getErrorDesc(LUA_ERROR_CREATURE_NOT_FOUND)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/creature_functions.hpp b/src/lua/functions/creatures/creature_functions.hpp index 0876bb72901..f0f1d12bb77 100644 --- a/src/lua/functions/creatures/creature_functions.hpp +++ b/src/lua/functions/creatures/creature_functions.hpp @@ -17,6 +17,12 @@ class CreatureFunctions final : LuaScriptInterface { public: + explicit CreatureFunctions(lua_State* L) : + LuaScriptInterface("CreatureFunctions") { + init(L); + } + ~CreatureFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Creature", "", CreatureFunctions::luaCreatureCreate); registerMetaMethod(L, "Creature", "__eq", CreatureFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/monster/charm_functions.cpp b/src/lua/functions/creatures/monster/charm_functions.cpp index d456f1c96a8..9d28cfbf886 100644 --- a/src/lua/functions/creatures/monster/charm_functions.cpp +++ b/src/lua/functions/creatures/monster/charm_functions.cpp @@ -16,7 +16,7 @@ int CharmFunctions::luaCharmCreate(lua_State* L) { // charm(id) if (isNumber(L, 2)) { - charmRune_t charmid = getNumber<charmRune_t>(L, 2); + const charmRune_t charmid = getNumber<charmRune_t>(L, 2); const auto charmList = g_game().getCharmList(); for (const auto &charm : charmList) { if (charm->id == charmid) { @@ -33,7 +33,7 @@ int CharmFunctions::luaCharmCreate(lua_State* L) { int CharmFunctions::luaCharmName(lua_State* L) { // get: charm:name() set: charm:name(string) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { pushString(L, charm->name); } else { @@ -45,7 +45,7 @@ int CharmFunctions::luaCharmName(lua_State* L) { int CharmFunctions::luaCharmDescription(lua_State* L) { // get: charm:description() set: charm:description(string) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { pushString(L, charm->description); } else { @@ -57,7 +57,7 @@ int CharmFunctions::luaCharmDescription(lua_State* L) { int CharmFunctions::luaCharmType(lua_State* L) { // get: charm:type() set: charm:type(charm_t) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->type); } else { @@ -69,7 +69,7 @@ int CharmFunctions::luaCharmType(lua_State* L) { int CharmFunctions::luaCharmPoints(lua_State* L) { // get: charm:points() set: charm:points(value) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->points); } else { @@ -81,7 +81,7 @@ int CharmFunctions::luaCharmPoints(lua_State* L) { int CharmFunctions::luaCharmDamageType(lua_State* L) { // get: charm:damageType() set: charm:damageType(type) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->dmgtype); } else { @@ -93,7 +93,7 @@ int CharmFunctions::luaCharmDamageType(lua_State* L) { int CharmFunctions::luaCharmPercentage(lua_State* L) { // get: charm:percentage() set: charm:percentage(value) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->percent); } else { @@ -105,7 +105,7 @@ int CharmFunctions::luaCharmPercentage(lua_State* L) { int CharmFunctions::luaCharmChance(lua_State* L) { // get: charm:chance() set: charm:chance(value) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->chance); } else { @@ -117,7 +117,7 @@ int CharmFunctions::luaCharmChance(lua_State* L) { int CharmFunctions::luaCharmMessageCancel(lua_State* L) { // get: charm:messageCancel() set: charm:messageCancel(string) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { pushString(L, charm->cancelMsg); } else { @@ -129,7 +129,7 @@ int CharmFunctions::luaCharmMessageCancel(lua_State* L) { int CharmFunctions::luaCharmMessageServerLog(lua_State* L) { // get: charm:messageServerLog() set: charm:messageServerLog(string) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { pushString(L, charm->logMsg); } else { @@ -141,7 +141,7 @@ int CharmFunctions::luaCharmMessageServerLog(lua_State* L) { int CharmFunctions::luaCharmEffect(lua_State* L) { // get: charm:effect() set: charm:effect(value) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, charm->effect); } else { @@ -153,7 +153,7 @@ int CharmFunctions::luaCharmEffect(lua_State* L) { int CharmFunctions::luaCharmCastSound(lua_State* L) { // get: charm:castSound() set: charm:castSound(sound) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast<lua_Number>(charm->soundCastEffect)); } else { @@ -165,7 +165,7 @@ int CharmFunctions::luaCharmCastSound(lua_State* L) { int CharmFunctions::luaCharmImpactSound(lua_State* L) { // get: charm:impactSound() set: charm:impactSound(sound) - const auto charm = getUserdataShared<Charm>(L, 1); + const auto &charm = getUserdataShared<Charm>(L, 1); if (lua_gettop(L) == 1) { lua_pushnumber(L, static_cast<lua_Number>(charm->soundImpactEffect)); } else { diff --git a/src/lua/functions/creatures/monster/charm_functions.hpp b/src/lua/functions/creatures/monster/charm_functions.hpp index 7be1c8de635..837c1c14fa7 100644 --- a/src/lua/functions/creatures/monster/charm_functions.hpp +++ b/src/lua/functions/creatures/monster/charm_functions.hpp @@ -13,6 +13,12 @@ class CharmFunctions final : LuaScriptInterface { public: + explicit CharmFunctions(lua_State* L) : + LuaScriptInterface("CharmFunctions") { + init(L); + } + ~CharmFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Charm", "", CharmFunctions::luaCharmCreate); registerMetaMethod(L, "Charm", "__eq", CharmFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/monster/loot_functions.cpp b/src/lua/functions/creatures/monster/loot_functions.cpp index 47e0d8778e3..3663a5dd5e9 100644 --- a/src/lua/functions/creatures/monster/loot_functions.cpp +++ b/src/lua/functions/creatures/monster/loot_functions.cpp @@ -14,7 +14,7 @@ int LootFunctions::luaCreateLoot(lua_State* L) { // Loot() will create a new loot item - const auto loot = std::make_shared<Loot>(); + const auto &loot = std::make_shared<Loot>(); pushUserdata<Loot>(L, loot); setMetatable(L, -1, "Loot"); return 1; @@ -22,7 +22,7 @@ int LootFunctions::luaCreateLoot(lua_State* L) { int LootFunctions::luaLootSetId(lua_State* L) { // loot:setId(id) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { if (isNumber(L, 2)) { loot->lootBlock.id = getNumber<uint16_t>(L, 2); @@ -40,10 +40,10 @@ int LootFunctions::luaLootSetId(lua_State* L) { int LootFunctions::luaLootSetIdFromName(lua_State* L) { // loot:setIdFromName(name) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot && isString(L, 2)) { auto name = getString(L, 2); - auto ids = Item::items.nameToItems.equal_range(asLowerCaseString(name)); + const auto ids = Item::items.nameToItems.equal_range(asLowerCaseString(name)); if (ids.first == Item::items.nameToItems.cend()) { g_logger().warn("[LootFunctions::luaLootSetIdFromName] - " @@ -73,7 +73,7 @@ int LootFunctions::luaLootSetIdFromName(lua_State* L) { int LootFunctions::luaLootSetSubType(lua_State* L) { // loot:setSubType(type) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.subType = getNumber<uint16_t>(L, 2); pushBoolean(L, true); @@ -85,7 +85,7 @@ int LootFunctions::luaLootSetSubType(lua_State* L) { int LootFunctions::luaLootSetChance(lua_State* L) { // loot:setChance(chance) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.chance = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -97,7 +97,7 @@ int LootFunctions::luaLootSetChance(lua_State* L) { int LootFunctions::luaLootSetMinCount(lua_State* L) { // loot:setMinCount(min) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.countmin = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -109,7 +109,7 @@ int LootFunctions::luaLootSetMinCount(lua_State* L) { int LootFunctions::luaLootSetMaxCount(lua_State* L) { // loot:setMaxCount(max) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.countmax = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -121,7 +121,7 @@ int LootFunctions::luaLootSetMaxCount(lua_State* L) { int LootFunctions::luaLootSetActionId(lua_State* L) { // loot:setActionId(actionid) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.actionId = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -133,7 +133,7 @@ int LootFunctions::luaLootSetActionId(lua_State* L) { int LootFunctions::luaLootSetText(lua_State* L) { // loot:setText(text) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.text = getString(L, 2); pushBoolean(L, true); @@ -145,7 +145,7 @@ int LootFunctions::luaLootSetText(lua_State* L) { int LootFunctions::luaLootSetNameItem(lua_State* L) { // loot:setNameItem(name) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.name = getString(L, 2); pushBoolean(L, true); @@ -157,7 +157,7 @@ int LootFunctions::luaLootSetNameItem(lua_State* L) { int LootFunctions::luaLootSetArticle(lua_State* L) { // loot:setArticle(article) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.article = getString(L, 2); pushBoolean(L, true); @@ -169,7 +169,7 @@ int LootFunctions::luaLootSetArticle(lua_State* L) { int LootFunctions::luaLootSetAttack(lua_State* L) { // loot:setAttack(attack) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.attack = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -181,7 +181,7 @@ int LootFunctions::luaLootSetAttack(lua_State* L) { int LootFunctions::luaLootSetDefense(lua_State* L) { // loot:setDefense(defense) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.defense = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -193,7 +193,7 @@ int LootFunctions::luaLootSetDefense(lua_State* L) { int LootFunctions::luaLootSetExtraDefense(lua_State* L) { // loot:setExtraDefense(defense) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.extraDefense = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -205,7 +205,7 @@ int LootFunctions::luaLootSetExtraDefense(lua_State* L) { int LootFunctions::luaLootSetArmor(lua_State* L) { // loot:setArmor(armor) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.armor = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -217,7 +217,7 @@ int LootFunctions::luaLootSetArmor(lua_State* L) { int LootFunctions::luaLootSetShootRange(lua_State* L) { // loot:setShootRange(range) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.shootRange = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -229,7 +229,7 @@ int LootFunctions::luaLootSetShootRange(lua_State* L) { int LootFunctions::luaLootSetHitChance(lua_State* L) { // loot:setHitChance(chance) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { loot->lootBlock.hitChance = getNumber<uint32_t>(L, 2); pushBoolean(L, true); @@ -241,7 +241,7 @@ int LootFunctions::luaLootSetHitChance(lua_State* L) { int LootFunctions::luaLootSetUnique(lua_State* L) { // loot:setUnique(bool) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { if (lua_gettop(L) == 1) { pushBoolean(L, loot->lootBlock.unique); @@ -257,7 +257,7 @@ int LootFunctions::luaLootSetUnique(lua_State* L) { int LootFunctions::luaLootAddChildLoot(lua_State* L) { // loot:addChildLoot(loot) - const auto loot = getUserdataShared<Loot>(L, 1); + const auto &loot = getUserdataShared<Loot>(L, 1); if (loot) { const auto childLoot = getUserdata<Loot>(L, 2); if (childLoot) { diff --git a/src/lua/functions/creatures/monster/loot_functions.hpp b/src/lua/functions/creatures/monster/loot_functions.hpp index 77059307a66..321f6bd8365 100644 --- a/src/lua/functions/creatures/monster/loot_functions.hpp +++ b/src/lua/functions/creatures/monster/loot_functions.hpp @@ -13,6 +13,12 @@ class LootFunctions final : LuaScriptInterface { public: + explicit LootFunctions(lua_State* L) : + LuaScriptInterface("LootFunctions") { + init(L); + } + ~LootFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Loot", "", LootFunctions::luaCreateLoot); diff --git a/src/lua/functions/creatures/monster/monster_functions.cpp b/src/lua/functions/creatures/monster/monster_functions.cpp index 4ba6ea412a8..43bef1b30c5 100644 --- a/src/lua/functions/creatures/monster/monster_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_functions.cpp @@ -49,7 +49,7 @@ int MonsterFunctions::luaMonsterIsMonster(lua_State* L) { int MonsterFunctions::luaMonsterGetType(lua_State* L) { // monster:getType() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { pushUserdata<MonsterType>(L, monster->mType); setMetatable(L, -1, "MonsterType"); @@ -61,7 +61,7 @@ int MonsterFunctions::luaMonsterGetType(lua_State* L) { int MonsterFunctions::luaMonsterSetType(lua_State* L) { // monster:setType(name or raceid) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { std::shared_ptr<MonsterType> mType; if (isNumber(L, 2)) { @@ -106,7 +106,7 @@ int MonsterFunctions::luaMonsterSetType(lua_State* L) { int MonsterFunctions::luaMonsterGetSpawnPosition(lua_State* L) { // monster:getSpawnPosition() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { pushPosition(L, monster->getMasterPos()); } else { @@ -117,7 +117,7 @@ int MonsterFunctions::luaMonsterGetSpawnPosition(lua_State* L) { int MonsterFunctions::luaMonsterIsInSpawnRange(lua_State* L) { // monster:isInSpawnRange([position]) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { pushBoolean(L, monster->isInSpawnRange(lua_gettop(L) >= 2 ? getPosition(L, 2) : monster->getPosition())); } else { @@ -128,7 +128,7 @@ int MonsterFunctions::luaMonsterIsInSpawnRange(lua_State* L) { int MonsterFunctions::luaMonsterIsIdle(lua_State* L) { // monster:isIdle() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { pushBoolean(L, monster->getIdleStatus()); } else { @@ -139,7 +139,7 @@ int MonsterFunctions::luaMonsterIsIdle(lua_State* L) { int MonsterFunctions::luaMonsterSetIdle(lua_State* L) { // monster:setIdle(idle) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -152,9 +152,9 @@ int MonsterFunctions::luaMonsterSetIdle(lua_State* L) { int MonsterFunctions::luaMonsterIsTarget(lua_State* L) { // monster:isTarget(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); pushBoolean(L, monster->isTarget(creature)); } else { lua_pushnil(L); @@ -164,9 +164,9 @@ int MonsterFunctions::luaMonsterIsTarget(lua_State* L) { int MonsterFunctions::luaMonsterIsOpponent(lua_State* L) { // monster:isOpponent(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); pushBoolean(L, monster->isOpponent(creature)); } else { lua_pushnil(L); @@ -176,9 +176,9 @@ int MonsterFunctions::luaMonsterIsOpponent(lua_State* L) { int MonsterFunctions::luaMonsterIsFriend(lua_State* L) { // monster:isFriend(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); pushBoolean(L, monster->isFriend(creature)); } else { lua_pushnil(L); @@ -188,9 +188,9 @@ int MonsterFunctions::luaMonsterIsFriend(lua_State* L) { int MonsterFunctions::luaMonsterAddFriend(lua_State* L) { // monster:addFriend(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); monster->addFriend(creature); pushBoolean(L, true); } else { @@ -201,9 +201,9 @@ int MonsterFunctions::luaMonsterAddFriend(lua_State* L) { int MonsterFunctions::luaMonsterRemoveFriend(lua_State* L) { // monster:removeFriend(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); monster->removeFriend(creature); pushBoolean(L, true); } else { @@ -214,7 +214,7 @@ int MonsterFunctions::luaMonsterRemoveFriend(lua_State* L) { int MonsterFunctions::luaMonsterGetFriendList(lua_State* L) { // monster:getFriendList() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -234,7 +234,7 @@ int MonsterFunctions::luaMonsterGetFriendList(lua_State* L) { int MonsterFunctions::luaMonsterGetFriendCount(lua_State* L) { // monster:getFriendCount() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { lua_pushnumber(L, monster->getFriendList().size()); } else { @@ -245,14 +245,14 @@ int MonsterFunctions::luaMonsterGetFriendCount(lua_State* L) { int MonsterFunctions::luaMonsterAddTarget(lua_State* L) { // monster:addTarget(creature[, pushFront = false]) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; } - std::shared_ptr<Creature> creature = getCreature(L, 2); - bool pushFront = getBoolean(L, 3, false); + const auto &creature = getCreature(L, 2); + const bool pushFront = getBoolean(L, 3, false); monster->addTarget(creature, pushFront); pushBoolean(L, true); return 1; @@ -260,7 +260,7 @@ int MonsterFunctions::luaMonsterAddTarget(lua_State* L) { int MonsterFunctions::luaMonsterRemoveTarget(lua_State* L) { // monster:removeTarget(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; @@ -273,13 +273,13 @@ int MonsterFunctions::luaMonsterRemoveTarget(lua_State* L) { int MonsterFunctions::luaMonsterGetTargetList(lua_State* L) { // monster:getTargetList() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; } - const auto targetList = monster->getTargetList(); + const auto &targetList = monster->getTargetList(); lua_createtable(L, targetList.size(), 0); int index = 0; @@ -293,7 +293,7 @@ int MonsterFunctions::luaMonsterGetTargetList(lua_State* L) { int MonsterFunctions::luaMonsterGetTargetCount(lua_State* L) { // monster:getTargetCount() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { lua_pushnumber(L, monster->getTargetList().size()); } else { @@ -304,10 +304,10 @@ int MonsterFunctions::luaMonsterGetTargetCount(lua_State* L) { int MonsterFunctions::luaMonsterChangeTargetDistance(lua_State* L) { // monster:changeTargetDistance(distance[, duration = 12000]) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - auto distance = getNumber<int32_t>(L, 2, 1); - auto duration = getNumber<uint32_t>(L, 3, 12000); + const auto distance = getNumber<int32_t>(L, 2, 1); + const auto duration = getNumber<uint32_t>(L, 3, 12000); pushBoolean(L, monster->changeTargetDistance(distance, duration)); } else { lua_pushnil(L); @@ -317,7 +317,7 @@ int MonsterFunctions::luaMonsterChangeTargetDistance(lua_State* L) { int MonsterFunctions::luaMonsterIsChallenged(lua_State* L) { // monster:isChallenged() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { pushBoolean(L, monster->isChallenged()); } else { @@ -328,9 +328,9 @@ int MonsterFunctions::luaMonsterIsChallenged(lua_State* L) { int MonsterFunctions::luaMonsterSelectTarget(lua_State* L) { // monster:selectTarget(creature) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); pushBoolean(L, monster->selectTarget(creature)); } else { lua_pushnil(L); @@ -340,7 +340,7 @@ int MonsterFunctions::luaMonsterSelectTarget(lua_State* L) { int MonsterFunctions::luaMonsterSearchTarget(lua_State* L) { // monster:searchTarget([searchType = TARGETSEARCH_DEFAULT]) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (monster) { const auto &searchType = getNumber<TargetSearchType_t>(L, 2, TARGETSEARCH_DEFAULT); pushBoolean(L, monster->searchTarget(searchType)); @@ -352,19 +352,19 @@ int MonsterFunctions::luaMonsterSearchTarget(lua_State* L) { int MonsterFunctions::luaMonsterSetSpawnPosition(lua_State* L) { // monster:setSpawnPosition(interval) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; } - uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); + const uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); const Position &pos = monster->getPosition(); monster->setMasterPos(pos); SpawnMonster &spawnMonster = g_game().map.spawnsMonster.getspawnMonsterList().emplace_back(pos, 5); - uint32_t interval = getNumber<uint32_t>(L, 2, 90) * 1000 * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * eventschedule)); + const uint32_t interval = getNumber<uint32_t>(L, 2, 90) * 1000 * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * eventschedule)); spawnMonster.addMonster(monster->mType->typeName, pos, DIRECTION_NORTH, static_cast<uint32_t>(interval)); spawnMonster.startSpawnMonsterCheck(); @@ -374,14 +374,14 @@ int MonsterFunctions::luaMonsterSetSpawnPosition(lua_State* L) { int MonsterFunctions::luaMonsterGetRespawnType(lua_State* L) { // monster:getRespawnType() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { lua_pushnil(L); return 1; } - RespawnType respawnType = monster->getRespawnType(); + const RespawnType respawnType = monster->getRespawnType(); lua_pushnumber(L, respawnType.period); pushBoolean(L, respawnType.underground); @@ -390,7 +390,7 @@ int MonsterFunctions::luaMonsterGetRespawnType(lua_State* L) { int MonsterFunctions::luaMonsterGetTimeToChangeFiendish(lua_State* L) { // monster:getTimeToChangeFiendish() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -403,8 +403,8 @@ int MonsterFunctions::luaMonsterGetTimeToChangeFiendish(lua_State* L) { int MonsterFunctions::luaMonsterSetTimeToChangeFiendish(lua_State* L) { // monster:setTimeToChangeFiendish(endTime) - time_t endTime = getNumber<uint32_t>(L, 2, 1); - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const time_t endTime = getNumber<uint32_t>(L, 2, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -417,22 +417,22 @@ int MonsterFunctions::luaMonsterSetTimeToChangeFiendish(lua_State* L) { int MonsterFunctions::luaMonsterGetMonsterForgeClassification(lua_State* L) { // monster:getMonsterForgeClassification() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); return 0; } - auto classification = static_cast<lua_Number>(monster->getMonsterForgeClassification()); + const auto classification = static_cast<lua_Number>(monster->getMonsterForgeClassification()); lua_pushnumber(L, classification); return 1; } int MonsterFunctions::luaMonsterSetMonsterForgeClassification(lua_State* L) { // monster:setMonsterForgeClassification(classication) - ForgeClassifications_t classification = getNumber<ForgeClassifications_t>(L, 2); - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const ForgeClassifications_t classification = getNumber<ForgeClassifications_t>(L, 2); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -445,7 +445,7 @@ int MonsterFunctions::luaMonsterSetMonsterForgeClassification(lua_State* L) { int MonsterFunctions::luaMonsterGetForgeStack(lua_State* L) { // monster:getForgeStack() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -458,8 +458,8 @@ int MonsterFunctions::luaMonsterGetForgeStack(lua_State* L) { int MonsterFunctions::luaMonsterSetForgeStack(lua_State* L) { // monster:setForgeStack(stack) - auto stack = getNumber<uint16_t>(L, 2, 0); - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto stack = getNumber<uint16_t>(L, 2, 0); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -467,7 +467,7 @@ int MonsterFunctions::luaMonsterSetForgeStack(lua_State* L) { } monster->setForgeStack(stack); - auto icon = stack < 15 + const auto icon = stack < 15 ? CreatureIconModifications_t::Influenced : CreatureIconModifications_t::Fiendish; monster->setIcon("forge", CreatureIcon(icon, icon == CreatureIconModifications_t::Influenced ? static_cast<uint8_t>(stack) : 0)); @@ -478,7 +478,7 @@ int MonsterFunctions::luaMonsterSetForgeStack(lua_State* L) { int MonsterFunctions::luaMonsterConfigureForgeSystem(lua_State* L) { // monster:configureForgeSystem() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -491,7 +491,7 @@ int MonsterFunctions::luaMonsterConfigureForgeSystem(lua_State* L) { int MonsterFunctions::luaMonsterClearFiendishStatus(lua_State* L) { // monster:clearFiendishStatus() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -504,7 +504,7 @@ int MonsterFunctions::luaMonsterClearFiendishStatus(lua_State* L) { int MonsterFunctions::luaMonsterIsForgeable(lua_State* L) { // monster:isForgeable() - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -530,7 +530,7 @@ int MonsterFunctions::luaMonsterGetName(lua_State* L) { int MonsterFunctions::luaMonsterSetName(lua_State* L) { // monster:setName(name[, nameDescription]) - auto monster = getUserdataShared<Monster>(L, 1); + const auto &monster = getUserdataShared<Monster>(L, 1); if (!monster) { reportErrorFunc(getErrorDesc(LUA_ERROR_MONSTER_NOT_FOUND)); pushBoolean(L, false); @@ -548,8 +548,8 @@ int MonsterFunctions::luaMonsterSetName(lua_State* L) { int MonsterFunctions::luaMonsterHazard(lua_State* L) { // get: monster:hazard() ; set: monster:hazard(hazard) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); - bool hazard = getBoolean(L, 2, false); + const auto &monster = getUserdataShared<Monster>(L, 1); + const bool hazard = getBoolean(L, 2, false); if (monster) { if (lua_gettop(L) == 1) { pushBoolean(L, monster->getHazard()); @@ -565,8 +565,8 @@ int MonsterFunctions::luaMonsterHazard(lua_State* L) { int MonsterFunctions::luaMonsterHazardCrit(lua_State* L) { // get: monster:hazardCrit() ; set: monster:hazardCrit(hazardCrit) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); - bool hazardCrit = getBoolean(L, 2, false); + const auto &monster = getUserdataShared<Monster>(L, 1); + const bool hazardCrit = getBoolean(L, 2, false); if (monster) { if (lua_gettop(L) == 1) { pushBoolean(L, monster->getHazardSystemCrit()); @@ -582,8 +582,8 @@ int MonsterFunctions::luaMonsterHazardCrit(lua_State* L) { int MonsterFunctions::luaMonsterHazardDodge(lua_State* L) { // get: monster:hazardDodge() ; set: monster:hazardDodge(hazardDodge) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); - bool hazardDodge = getBoolean(L, 2, false); + const auto &monster = getUserdataShared<Monster>(L, 1); + const bool hazardDodge = getBoolean(L, 2, false); if (monster) { if (lua_gettop(L) == 1) { pushBoolean(L, monster->getHazardSystemDodge()); @@ -599,8 +599,8 @@ int MonsterFunctions::luaMonsterHazardDodge(lua_State* L) { int MonsterFunctions::luaMonsterHazardDamageBoost(lua_State* L) { // get: monster:hazardDamageBoost() ; set: monster:hazardDamageBoost(hazardDamageBoost) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); - bool hazardDamageBoost = getBoolean(L, 2, false); + const auto &monster = getUserdataShared<Monster>(L, 1); + const bool hazardDamageBoost = getBoolean(L, 2, false); if (monster) { if (lua_gettop(L) == 1) { pushBoolean(L, monster->getHazardSystemDamageBoost()); @@ -616,8 +616,8 @@ int MonsterFunctions::luaMonsterHazardDamageBoost(lua_State* L) { int MonsterFunctions::luaMonsterHazardDefenseBoost(lua_State* L) { // get: monster:hazardDefenseBoost() ; set: monster:hazardDefenseBoost(hazardDefenseBoost) - std::shared_ptr<Monster> monster = getUserdataShared<Monster>(L, 1); - bool hazardDefenseBoost = getBoolean(L, 2, false); + const auto &monster = getUserdataShared<Monster>(L, 1); + const bool hazardDefenseBoost = getBoolean(L, 2, false); if (monster) { if (lua_gettop(L) == 1) { pushBoolean(L, monster->getHazardSystemDefenseBoost()); diff --git a/src/lua/functions/creatures/monster/monster_functions.hpp b/src/lua/functions/creatures/monster/monster_functions.hpp index dd1c3827344..80e1d276c0b 100644 --- a/src/lua/functions/creatures/monster/monster_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_functions.hpp @@ -17,6 +17,12 @@ class MonsterFunctions final : LuaScriptInterface { private: + explicit MonsterFunctions(lua_State* L) : + LuaScriptInterface("MonsterFunctions") { + init(L); + } + ~MonsterFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Monster", "Creature", MonsterFunctions::luaMonsterCreate); registerMetaMethod(L, "Monster", "__eq", MonsterFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.hpp b/src/lua/functions/creatures/monster/monster_spell_functions.hpp index f5d64a3511e..e44c5e53470 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.hpp @@ -13,6 +13,12 @@ class MonsterSpellFunctions final : LuaScriptInterface { public: + explicit MonsterSpellFunctions(lua_State* L) : + LuaScriptInterface("MonsterSpellFunctions") { + init(L); + } + ~MonsterSpellFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "MonsterSpell", "", MonsterSpellFunctions::luaCreateMonsterSpell); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 7aa8ae926ec..0618310d8dd 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -109,7 +109,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsSummonable(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsPreyExclusive(lua_State* L) { // get: monsterType:isPreyExclusive() set: monsterType:isPreyExclusive(bool) - const auto monsterType = getUserdataShared<MonsterType>(L, 1); + const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isPreyExclusive); @@ -125,7 +125,7 @@ int MonsterTypeFunctions::luaMonsterTypeIsPreyExclusive(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeIsPreyable(lua_State* L) { // get: monsterType:isPreyable() set: monsterType:isPreyable(bool) - const auto monsterType = getUserdataShared<MonsterType>(L, 1); + const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { if (lua_gettop(L) == 1) { pushBoolean(L, monsterType->info.isPreyable); @@ -463,7 +463,7 @@ int MonsterTypeFunctions::luaMonsterTypeEnemyFactions(lua_State* L) { lua_rawseti(L, -2, ++index); } } else { - Faction_t faction = getNumber<Faction_t>(L, 2); + const Faction_t faction = getNumber<Faction_t>(L, 2); monsterType->info.enemyFactions.insert(faction); pushBoolean(L, true); } @@ -657,7 +657,7 @@ int MonsterTypeFunctions::luaMonsterTypeBestiaryrace(lua_State* L) { if (lua_gettop(L) == 1) { lua_pushnumber(L, monsterType->info.bestiaryRace); } else { - BestiaryType_t race = getNumber<BestiaryType_t>(L, 2); + const BestiaryType_t race = getNumber<BestiaryType_t>(L, 2); monsterType->info.bestiaryRace = race; pushBoolean(L, true); } @@ -815,7 +815,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddAttack(lua_State* L) { // monsterType:addAttack(monsterspell) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - const auto spell = getUserdataShared<MonsterSpell>(L, 2); + const auto &spell = getUserdataShared<MonsterSpell>(L, 2); if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { @@ -877,7 +877,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddDefense(lua_State* L) { // monsterType:addDefense(monsterspell) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - const auto spell = getUserdataShared<MonsterSpell>(L, 2); + const auto &spell = getUserdataShared<MonsterSpell>(L, 2); if (spell) { spellBlock_t sb; if (g_monsters().deserializeSpell(spell, sb, monsterType->name)) { @@ -898,7 +898,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddElement(lua_State* L) { // monsterType:addElement(type, percent) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - CombatType_t element = getNumber<CombatType_t>(L, 2); + const CombatType_t element = getNumber<CombatType_t>(L, 2); monsterType->info.elementMap[element] = getNumber<int32_t>(L, 3); pushBoolean(L, true); } else { @@ -911,7 +911,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddReflect(lua_State* L) { // monsterType:addReflect(type, percent) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - CombatType_t element = getNumber<CombatType_t>(L, 2); + const CombatType_t element = getNumber<CombatType_t>(L, 2); monsterType->info.reflectMap[element] = getNumber<int32_t>(L, 3); pushBoolean(L, true); } else { @@ -924,7 +924,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddHealing(lua_State* L) { // monsterType:addHealing(type, percent) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - CombatType_t element = getNumber<CombatType_t>(L, 2); + const CombatType_t element = getNumber<CombatType_t>(L, 2); monsterType->info.healingMap[element] = getNumber<int32_t>(L, 3); pushBoolean(L, true); } else { @@ -1001,7 +1001,7 @@ int MonsterTypeFunctions::luaMonsterTypeAddLoot(lua_State* L) { // monsterType:addLoot(loot) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - const auto loot = getUserdataShared<Loot>(L, 2); + const auto &loot = getUserdataShared<Loot>(L, 2); if (loot) { monsterType->loadLoot(monsterType, loot->lootBlock); pushBoolean(L, true); @@ -1035,7 +1035,7 @@ int MonsterTypeFunctions::luaMonsterTypeRegisterEvent(lua_State* L) { // monsterType:registerEvent(name) const auto &monsterType = getUserdataShared<MonsterType>(L, 1); if (monsterType) { - auto eventName = getString(L, 2); + const auto eventName = getString(L, 2); monsterType->info.scripts.insert(eventName); for (const auto &[_, monster] : g_game().getMonsters()) { if (monster->getMonsterType() == monsterType) { @@ -1070,7 +1070,7 @@ int MonsterTypeFunctions::luaMonsterTypeEventOnCallback(lua_State* L) { int MonsterTypeFunctions::luaMonsterTypeEventType(lua_State* L) { // monstertype:eventType(event) - const auto mType = getUserdataShared<MonsterType>(L, 1); + const auto &mType = getUserdataShared<MonsterType>(L, 1); if (mType) { mType->info.eventType = getNumber<MonstersEvent_t>(L, 2); pushBoolean(L, true); @@ -1573,8 +1573,8 @@ int MonsterTypeFunctions::luaMonsterTypeBossRace(lua_State* L) { } pushString(L, monsterType->info.bosstiaryClass); } else { - auto bossRace = getNumber<uint8_t>(L, 2, 0); - auto bossClass = getString(L, 3); + const auto bossRace = getNumber<uint8_t>(L, 2, 0); + const auto bossClass = getString(L, 3); monsterType->info.bosstiaryRace = magic_enum::enum_value<BosstiaryRarity_t>(bossRace); monsterType->info.bosstiaryClass = bossClass; pushBoolean(L, true); @@ -1600,7 +1600,7 @@ int MonsterTypeFunctions::luaMonsterTypeBossRaceId(lua_State* L) { lua_pushnumber(L, static_cast<lua_Number>(monsterType->info.bosstiaryRace)); } } else { - auto raceId = getNumber<uint16_t>(L, 2, 0); + const auto raceId = getNumber<uint16_t>(L, 2, 0); monsterType->info.raceid = raceId; g_ioBosstiary().addBosstiaryMonster(raceId, monsterType->name); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.hpp b/src/lua/functions/creatures/monster/monster_type_functions.hpp index cdbd0c4158a..2312d89a19d 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.hpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.hpp @@ -13,6 +13,12 @@ class MonsterTypeFunctions final : LuaScriptInterface { public: + explicit MonsterTypeFunctions(lua_State* L) : + LuaScriptInterface("MonsterTypeFunctions") { + init(L); + } + ~MonsterTypeFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "MonsterType", "", MonsterTypeFunctions::luaMonsterTypeCreate); registerMetaMethod(L, "MonsterType", "__eq", MonsterTypeFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/npc/npc_functions.cpp b/src/lua/functions/creatures/npc/npc_functions.cpp index 615a026190d..f540dbf2bbb 100644 --- a/src/lua/functions/creatures/npc/npc_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_functions.cpp @@ -151,8 +151,8 @@ int NpcFunctions::luaNpcPlace(lua_State* L) { } const Position &position = getPosition(L, 2); - bool extended = getBoolean(L, 3, false); - bool force = getBoolean(L, 4, true); + const bool extended = getBoolean(L, 3, false); + const bool force = getBoolean(L, 4, true); if (g_game().placeCreature(npc, position, extended, force)) { pushUserdata<Npc>(L, npc); setMetatable(L, -1, "Npc"); @@ -164,7 +164,7 @@ int NpcFunctions::luaNpcPlace(lua_State* L) { int NpcFunctions::luaNpcSay(lua_State* L) { // npc:say(text[, type = TALKTYPE_PRIVATE_NP[, ghost = false[, target = nullptr[, position]]]]) - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); Position position; if (parameters >= 6) { @@ -181,7 +181,7 @@ int NpcFunctions::luaNpcSay(lua_State* L) { target = getCreature(L, 5); } - bool ghost = getBoolean(L, 4, false); + const bool ghost = getBoolean(L, 4, false); const auto &type = getNumber<SpeakClasses>(L, 3, TALKTYPE_PRIVATE_NP); const std::string &text = getString(L, 2); @@ -211,7 +211,7 @@ int NpcFunctions::luaNpcSay(lua_State* L) { int NpcFunctions::luaNpcTurnToCreature(lua_State* L) { // npc:turnToCreature(creature, true) const auto &npc = getUserdataShared<Npc>(L, 1); - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -225,7 +225,7 @@ int NpcFunctions::luaNpcTurnToCreature(lua_State* L) { return 1; } - bool stopEventWalk = getBoolean(L, 3, true); + const bool stopEventWalk = getBoolean(L, 3, true); if (stopEventWalk) { npc->stopEventWalk(); } @@ -237,8 +237,8 @@ int NpcFunctions::luaNpcTurnToCreature(lua_State* L) { int NpcFunctions::luaNpcSetPlayerInteraction(lua_State* L) { // npc:setPlayerInteraction(creature, topic = 0) const auto &npc = getUserdataShared<Npc>(L, 1); - std::shared_ptr<Creature> creature = getCreature(L, 2); - auto topicId = getNumber<uint16_t>(L, 3, 0); + const auto &creature = getCreature(L, 2); + const auto topicId = getNumber<uint16_t>(L, 3, 0); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -260,7 +260,7 @@ int NpcFunctions::luaNpcSetPlayerInteraction(lua_State* L) { int NpcFunctions::luaNpcRemovePlayerInteraction(lua_State* L) { // npc:removePlayerInteraction() const auto &npc = getUserdataShared<Npc>(L, 1); - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -282,7 +282,7 @@ int NpcFunctions::luaNpcRemovePlayerInteraction(lua_State* L) { int NpcFunctions::luaNpcIsInteractingWithPlayer(lua_State* L) { // npc:isInteractingWithPlayer(creature) const auto &npc = getUserdataShared<Npc>(L, 1); - std::shared_ptr<Creature> creature = getCreature(L, 2); + const auto &creature = getCreature(L, 2); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -303,8 +303,8 @@ int NpcFunctions::luaNpcIsInteractingWithPlayer(lua_State* L) { int NpcFunctions::luaNpcIsPlayerInteractingOnTopic(lua_State* L) { // npc:isPlayerInteractingOnTopic(creature, topicId = 0) const auto &npc = getUserdataShared<Npc>(L, 1); - std::shared_ptr<Creature> creature = getCreature(L, 2); - auto topicId = getNumber<uint32_t>(L, 3, 0); + const auto &creature = getCreature(L, 2); + const auto topicId = getNumber<uint32_t>(L, 3, 0); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -326,7 +326,7 @@ int NpcFunctions::luaNpcIsInTalkRange(lua_State* L) { // npc:isInTalkRange(position[, range = 4]) const auto &npc = getUserdataShared<Npc>(L, 1); const Position &position = getPosition(L, 2); - auto range = getNumber<uint32_t>(L, 3, 4); + const auto range = getNumber<uint32_t>(L, 3, 4); if (!npc) { reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); @@ -441,7 +441,7 @@ int NpcFunctions::luaNpcIsMerchant(lua_State* L) { return 1; } - auto playerGUID = getNumber<uint32_t>(L, 2, 0); + const auto playerGUID = getNumber<uint32_t>(L, 2, 0); const auto &shopItems = npc->getShopItemVector(playerGUID); if (shopItems.empty()) { pushBoolean(L, false); @@ -461,7 +461,7 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { return 1; } - auto playerGUID = getNumber<uint32_t>(L, 2, 0); + const auto playerGUID = getNumber<uint32_t>(L, 2, 0); const auto &shopItems = npc->getShopItemVector(playerGUID); for (const ShopBlock &shopBlock : shopItems) { setField(L, "id", shopBlock.itemId); @@ -543,11 +543,11 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { } auto itemId = getNumber<uint16_t>(L, 3); - double amount = getNumber<double>(L, 4); - auto subType = getNumber<uint16_t>(L, 5, 1); - auto actionId = getNumber<uint16_t>(L, 6, 0); - bool ignoreCap = getBoolean(L, 7, false); - bool inBackpacks = getBoolean(L, 8, false); + const double amount = getNumber<double>(L, 4); + const auto subType = getNumber<uint16_t>(L, 5, 1); + const auto actionId = getNumber<uint16_t>(L, 6, 0); + const bool ignoreCap = getBoolean(L, 7, false); + const bool inBackpacks = getBoolean(L, 8, false); const ItemType &it = Item::items[itemId]; if (it.id == 0) { @@ -555,9 +555,9 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { return 1; } - uint32_t shoppingBagPrice = 20; - double shoppingBagSlots = 20; - if (std::shared_ptr<Tile> tile = ignoreCap ? player->getTile() : nullptr; tile) { + constexpr uint32_t shoppingBagPrice = 20; + constexpr double shoppingBagSlots = 20; + if (const auto &tile = ignoreCap ? player->getTile() : nullptr; tile) { double slotsNedeed = 0; if (it.stackable) { slotsNedeed = inBackpacks ? std::ceil(std::ceil(amount / it.stackSize) / shoppingBagSlots) : std::ceil(amount / it.stackSize); @@ -584,8 +584,8 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { const auto &[_, itemsPurchased, backpacksPurchased] = g_game().createItem(player, itemId, amount, subType, actionId, ignoreCap, inBackpacks ? ITEM_SHOPPING_BAG : 0); std::stringstream ss; - uint64_t itemCost = itemsPurchased * pricePerUnit; - uint64_t backpackCost = backpacksPurchased * shoppingBagPrice; + const uint64_t itemCost = itemsPurchased * pricePerUnit; + const uint64_t backpackCost = backpacksPurchased * shoppingBagPrice; if (npc->getCurrency() == ITEM_GOLD_COIN) { if (!g_game().removeMoney(player, itemCost + backpackCost, 0, true)) { g_logger().error("[NpcFunctions::luaNpcSellItem (removeMoney)] - Player {} have a problem for buy item {} on shop for npc {}", player->getName(), itemId, npc->getName()); @@ -653,7 +653,7 @@ int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) { return 1; } - std::shared_ptr<Thing> thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)); + const auto &thing = getScriptEnv()->getThingByUID(getNumber<uint32_t>(L, -1)); pushBoolean(L, thing && thing->isPushable()); if (!thing) { reportErrorFunc(getErrorDesc(LUA_ERROR_THING_NOT_FOUND)); @@ -666,7 +666,7 @@ int NpcFunctions::luaNpcGetDistanceTo(lua_State* L) { if (npcPos.z != thingPos.z) { lua_pushnumber(L, -1); } else { - int32_t dist = std::max<int32_t>(Position::getDistanceX(npcPos, thingPos), Position::getDistanceY(npcPos, thingPos)); + const int32_t dist = std::max<int32_t>(Position::getDistanceX(npcPos, thingPos), Position::getDistanceY(npcPos, thingPos)); lua_pushnumber(L, dist); } return 1; diff --git a/src/lua/functions/creatures/npc/npc_functions.hpp b/src/lua/functions/creatures/npc/npc_functions.hpp index 1622a15c0e7..e03e3f72b25 100644 --- a/src/lua/functions/creatures/npc/npc_functions.hpp +++ b/src/lua/functions/creatures/npc/npc_functions.hpp @@ -15,6 +15,12 @@ class NpcFunctions final : LuaScriptInterface { private: + explicit NpcFunctions(lua_State* L) : + LuaScriptInterface("NpcFunctions") { + init(L); + } + ~NpcFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Npc", "Creature", NpcFunctions::luaNpcCreate); registerMetaMethod(L, "Npc", "__eq", NpcFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/npc/npc_type_functions.cpp b/src/lua/functions/creatures/npc/npc_type_functions.cpp index ef79b671a34..18da7d300e3 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.cpp @@ -191,7 +191,7 @@ int NpcTypeFunctions::luaNpcTypeAddShopItem(lua_State* L) { return 1; } - auto shop = getUserdataShared<Shop>(L, 2); + const auto &shop = getUserdataShared<Shop>(L, 2); if (shop) { npcType->loadShop(npcType, shop->shopBlock); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/npc/npc_type_functions.hpp b/src/lua/functions/creatures/npc/npc_type_functions.hpp index ce799c71f20..ee54f124992 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.hpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.hpp @@ -13,6 +13,12 @@ class NpcTypeFunctions final : LuaScriptInterface { public: + explicit NpcTypeFunctions(lua_State* L) : + LuaScriptInterface("NpcTypeFunctions") { + init(L); + } + ~NpcTypeFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "NpcType", "", NpcTypeFunctions::luaNpcTypeCreate); registerMetaMethod(L, "NpcType", "__eq", NpcTypeFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/npc/shop_functions.cpp b/src/lua/functions/creatures/npc/shop_functions.cpp index 122e249a8db..347494b8325 100644 --- a/src/lua/functions/creatures/npc/shop_functions.cpp +++ b/src/lua/functions/creatures/npc/shop_functions.cpp @@ -42,7 +42,7 @@ int ShopFunctions::luaShopSetIdFromName(lua_State* L) { const auto &shop = getUserdataShared<Shop>(L, 1); if (shop && isString(L, 2)) { auto name = getString(L, 2); - auto ids = Item::items.nameToItems.equal_range(asLowerCaseString(name)); + const auto ids = Item::items.nameToItems.equal_range(asLowerCaseString(name)); if (ids.first == Item::items.nameToItems.cend()) { g_logger().warn("[ShopFunctions::luaShopSetIdFromName] - " diff --git a/src/lua/functions/creatures/npc/shop_functions.hpp b/src/lua/functions/creatures/npc/shop_functions.hpp index e5a6c9943cc..2d326ff73e2 100644 --- a/src/lua/functions/creatures/npc/shop_functions.hpp +++ b/src/lua/functions/creatures/npc/shop_functions.hpp @@ -13,6 +13,12 @@ class ShopFunctions final : LuaScriptInterface { public: + explicit ShopFunctions(lua_State* L) : + LuaScriptInterface("ShopFunctions") { + init(L); + } + ~ShopFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Shop", "", ShopFunctions::luaCreateShop); registerMethod(L, "Shop", "setId", ShopFunctions::luaShopSetId); diff --git a/src/lua/functions/creatures/player/group_functions.cpp b/src/lua/functions/creatures/player/group_functions.cpp index f547eec1590..074da6dabab 100644 --- a/src/lua/functions/creatures/player/group_functions.cpp +++ b/src/lua/functions/creatures/player/group_functions.cpp @@ -15,7 +15,7 @@ int GroupFunctions::luaGroupCreate(lua_State* L) { // Group(id) - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const auto &group = g_game().groups.getGroup(id); if (group) { @@ -103,7 +103,7 @@ int GroupFunctions::luaGroupHasFlag(lua_State* L) { // group:hasFlag(flag) const auto &group = getUserdataShared<Group>(L, 1); if (group) { - auto flag = static_cast<PlayerFlags_t>(getNumber<int>(L, 2)); + const auto flag = static_cast<PlayerFlags_t>(getNumber<int>(L, 2)); pushBoolean(L, group->flags[Groups::getFlagNumber(flag)]); } else { lua_pushnil(L); diff --git a/src/lua/functions/creatures/player/group_functions.hpp b/src/lua/functions/creatures/player/group_functions.hpp index 4a33d1b988e..7729690b771 100644 --- a/src/lua/functions/creatures/player/group_functions.hpp +++ b/src/lua/functions/creatures/player/group_functions.hpp @@ -13,6 +13,12 @@ class GroupFunctions final : LuaScriptInterface { public: + explicit GroupFunctions(lua_State* L) : + LuaScriptInterface("GroupFunctions") { + init(L); + } + ~GroupFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Group", "", GroupFunctions::luaGroupCreate); registerMetaMethod(L, "Group", "__eq", GroupFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/player/guild_functions.cpp b/src/lua/functions/creatures/player/guild_functions.cpp index 55b74ad43c1..8cac6679ca4 100644 --- a/src/lua/functions/creatures/player/guild_functions.cpp +++ b/src/lua/functions/creatures/player/guild_functions.cpp @@ -14,7 +14,7 @@ #include "lua/functions/creatures/player/guild_functions.hpp" int GuildFunctions::luaGuildCreate(lua_State* L) { - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const auto &guild = g_game().getGuild(id); if (guild) { pushUserdata<Guild>(L, guild); @@ -97,9 +97,9 @@ int GuildFunctions::luaGuildAddRank(lua_State* L) { lua_pushnil(L); return 1; } - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const std::string &name = getString(L, 3); - uint8_t level = getNumber<uint8_t>(L, 4); + const uint8_t level = getNumber<uint8_t>(L, 4); guild->addRank(id, name, level); pushBoolean(L, true); return 1; @@ -113,8 +113,8 @@ int GuildFunctions::luaGuildGetRankById(lua_State* L) { return 1; } - uint32_t id = getNumber<uint32_t>(L, 2); - GuildRank_ptr rank = guild->getRankById(id); + const uint32_t id = getNumber<uint32_t>(L, 2); + const GuildRank_ptr rank = guild->getRankById(id); if (rank) { lua_createtable(L, 0, 3); setField(L, "id", rank->id); @@ -134,8 +134,8 @@ int GuildFunctions::luaGuildGetRankByLevel(lua_State* L) { return 1; } - uint8_t level = getNumber<uint8_t>(L, 2); - GuildRank_ptr rank = guild->getRankByLevel(level); + const uint8_t level = getNumber<uint8_t>(L, 2); + const GuildRank_ptr rank = guild->getRankByLevel(level); if (rank) { lua_createtable(L, 0, 3); setField(L, "id", rank->id); diff --git a/src/lua/functions/creatures/player/guild_functions.hpp b/src/lua/functions/creatures/player/guild_functions.hpp index e5c48244415..d8f844de751 100644 --- a/src/lua/functions/creatures/player/guild_functions.hpp +++ b/src/lua/functions/creatures/player/guild_functions.hpp @@ -13,6 +13,12 @@ class GuildFunctions final : LuaScriptInterface { public: + explicit GuildFunctions(lua_State* L) : + LuaScriptInterface("GuildFunctions") { + init(L); + } + ~GuildFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Guild", "", GuildFunctions::luaGuildCreate); registerMetaMethod(L, "Guild", "__eq", GuildFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/player/mount_functions.cpp b/src/lua/functions/creatures/player/mount_functions.cpp index 49f06a2b76a..0d3b3a3aa9c 100644 --- a/src/lua/functions/creatures/player/mount_functions.cpp +++ b/src/lua/functions/creatures/player/mount_functions.cpp @@ -19,7 +19,7 @@ int MountFunctions::luaCreateMount(lua_State* L) { if (isNumber(L, 2)) { mount = g_game().mounts.getMountByID(getNumber<uint8_t>(L, 2)); } else if (isString(L, 2)) { - std::string mountName = getString(L, 2); + const std::string mountName = getString(L, 2); mount = g_game().mounts.getMountByName(mountName); } else { mount = nullptr; diff --git a/src/lua/functions/creatures/player/mount_functions.hpp b/src/lua/functions/creatures/player/mount_functions.hpp index 3a4db6d6f92..a6ce7003ecc 100644 --- a/src/lua/functions/creatures/player/mount_functions.hpp +++ b/src/lua/functions/creatures/player/mount_functions.hpp @@ -13,6 +13,12 @@ class MountFunctions final : LuaScriptInterface { public: + explicit MountFunctions(lua_State* L) : + LuaScriptInterface("MountFunctions") { + init(L); + } + ~MountFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Mount", "", MountFunctions::luaCreateMount); registerMetaMethod(L, "Mount", "__eq", MountFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/player/party_functions.cpp b/src/lua/functions/creatures/player/party_functions.cpp index fac7fa8e910..d4ca963014b 100644 --- a/src/lua/functions/creatures/player/party_functions.cpp +++ b/src/lua/functions/creatures/player/party_functions.cpp @@ -234,7 +234,7 @@ int PartyFunctions::luaPartyIsSharedExperienceEnabled(lua_State* L) { int PartyFunctions::luaPartyShareExperience(lua_State* L) { // party:shareExperience(experience) - uint64_t experience = getNumber<uint64_t>(L, 2); + const uint64_t experience = getNumber<uint64_t>(L, 2); const auto &party = getUserdataShared<Party>(L, 1); if (party) { party->shareExperience(experience); @@ -247,7 +247,7 @@ int PartyFunctions::luaPartyShareExperience(lua_State* L) { int PartyFunctions::luaPartySetSharedExperience(lua_State* L) { // party:setSharedExperience(active) - bool active = getBoolean(L, 2); + const bool active = getBoolean(L, 2); const auto &party = getUserdataShared<Party>(L, 1); if (party) { pushBoolean(L, party->setSharedExperience(party->getLeader(), active)); diff --git a/src/lua/functions/creatures/player/party_functions.hpp b/src/lua/functions/creatures/player/party_functions.hpp index 312a39952fe..79e6a07de71 100644 --- a/src/lua/functions/creatures/player/party_functions.hpp +++ b/src/lua/functions/creatures/player/party_functions.hpp @@ -13,6 +13,12 @@ class PartyFunctions final : LuaScriptInterface { public: + explicit PartyFunctions(lua_State* L) : + LuaScriptInterface("PartyFunctions") { + init(L); + } + ~PartyFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Party", "", PartyFunctions::luaPartyCreate); registerMetaMethod(L, "Party", "__eq", PartyFunctions::luaUserdataCompare); diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 1e4d8a660cb..39d1a8938d1 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -57,7 +57,7 @@ int PlayerFunctions::luaPlayerSendLootStats(lua_State* L) { return 1; } - auto count = getNumber<uint8_t>(L, 3, 0); + const auto count = getNumber<uint8_t>(L, 3, 0); if (count == 0) { lua_pushnil(L); return 1; @@ -120,14 +120,14 @@ int PlayerFunctions::luaPlayerCreate(lua_State* L) { // Player(id or guid or name or userdata) std::shared_ptr<Player> player; if (isNumber(L, 2)) { - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); if (id >= Player::getFirstID() && id <= Player::getLastID()) { player = g_game().getPlayerByID(id); } else { player = g_game().getPlayerByGUID(id); } } else if (isString(L, 2)) { - ReturnValue ret = g_game().getPlayerByNameWildcard(getString(L, 2), player); + const ReturnValue ret = g_game().getPlayerByNameWildcard(getString(L, 2), player); if (ret != RETURNVALUE_NOERROR) { lua_pushnil(L); lua_pushnumber(L, ret); @@ -177,7 +177,7 @@ int PlayerFunctions::luaPlayerUnlockAllCharmRunes(lua_State* L) { for (int8_t i = CHARM_WOUND; i <= CHARM_LAST; i++) { const auto charm = g_iobestiary().getBestiaryCharm(static_cast<charmRune_t>(i)); if (charm) { - int32_t value = g_iobestiary().bitToggle(player->getUnlockedRunesBit(), charm, true); + const int32_t value = g_iobestiary().bitToggle(player->getUnlockedRunesBit(), charm, true); player->setUnlockedRunesBit(value); } } @@ -306,7 +306,7 @@ int PlayerFunctions::luaPlayerAddBestiaryKill(lua_State* L) { // player:addBestiaryKill(name[, amount = 1]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - const auto mtype = g_monsters().getMonsterType(getString(L, 2)); + const auto &mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { g_iobestiary().addBestiaryKill(player, mtype, getNumber<uint32_t>(L, 3, 1)); pushBoolean(L, true); @@ -328,14 +328,14 @@ int PlayerFunctions::luaPlayerIsMonsterBestiaryUnlocked(lua_State* L) { return 0; } - auto raceId = getNumber<uint16_t>(L, 2, 0); + const auto raceId = getNumber<uint16_t>(L, 2, 0); if (!g_monsters().getMonsterTypeByRaceId(raceId)) { reportErrorFunc("Monster race id not exists"); pushBoolean(L, false); return 0; } - for (uint16_t finishedRaceId : g_iobestiary().getBestiaryFinished(player)) { + for (const uint16_t finishedRaceId : g_iobestiary().getBestiaryFinished(player)) { if (raceId == finishedRaceId) { pushBoolean(L, true); return 1; @@ -350,10 +350,10 @@ int PlayerFunctions::luaPlayergetCharmMonsterType(lua_State* L) { // player:getCharmMonsterType(charmRune_t) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - charmRune_t charmid = getNumber<charmRune_t>(L, 2); - uint16_t raceid = player->parseRacebyCharm(charmid, false, 0); + const charmRune_t charmid = getNumber<charmRune_t>(L, 2); + const uint16_t raceid = player->parseRacebyCharm(charmid, false, 0); if (raceid > 0) { - const auto mtype = g_monsters().getMonsterTypeByRaceId(raceid); + const auto &mtype = g_monsters().getMonsterTypeByRaceId(raceid); if (mtype) { pushUserdata<MonsterType>(L, mtype); setMetatable(L, -1, "MonsterType"); @@ -443,7 +443,7 @@ int PlayerFunctions::luaPlayerGetTaskHuntingPoints(lua_State* L) { int PlayerFunctions::luaPlayerAddTaskHuntingPoints(lua_State* L) { // player:addTaskHuntingPoints(amount) if (const auto &player = getUserdataShared<Player>(L, 1)) { - auto points = getNumber<uint64_t>(L, 2); + const auto points = getNumber<uint64_t>(L, 2); player->addTaskHuntingPoints(getNumber<uint64_t>(L, 2)); lua_pushnumber(L, static_cast<lua_Number>(points)); } else { @@ -578,7 +578,7 @@ int PlayerFunctions::luaPlayerSetTraining(lua_State* L) { // player:setTraining(value) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - bool value = getBoolean(L, 2, false); + const bool value = getBoolean(L, 2, false); player->setTraining(value); pushBoolean(L, true); } else { @@ -671,9 +671,9 @@ int PlayerFunctions::luaPlayerGetReward(lua_State* L) { return 1; } - uint64_t rewardId = getNumber<uint64_t>(L, 2); - bool autoCreate = getBoolean(L, 3, false); - if (auto reward = player->getReward(rewardId, autoCreate)) { + const uint64_t rewardId = getNumber<uint64_t>(L, 2); + const bool autoCreate = getBoolean(L, 3, false); + if (const auto &reward = player->getReward(rewardId, autoCreate)) { pushUserdata<Item>(L, reward); setItemMetatable(L, -1, reward); } else { @@ -690,7 +690,7 @@ int PlayerFunctions::luaPlayerRemoveReward(lua_State* L) { return 1; } - uint32_t rewardId = getNumber<uint32_t>(L, 2); + const uint32_t rewardId = getNumber<uint32_t>(L, 2); player->removeReward(rewardId); pushBoolean(L, true); return 1; @@ -736,7 +736,7 @@ int PlayerFunctions::luaPlayerGetDepotLocker(lua_State* L) { return 1; } - uint32_t depotId = getNumber<uint32_t>(L, 2); + const uint32_t depotId = getNumber<uint32_t>(L, 2); const auto &depotLocker = player->getDepotLocker(depotId); if (depotLocker) { depotLocker->setParent(player); @@ -752,7 +752,7 @@ int PlayerFunctions::luaPlayerGetStashCounter(lua_State* L) { // player:getStashCount() const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t sizeStash = getStashSize(player->getStashItems()); + const uint16_t sizeStash = getStashSize(player->getStashItems()); lua_pushnumber(L, sizeStash); } else { lua_pushnil(L); @@ -768,8 +768,8 @@ int PlayerFunctions::luaPlayerGetDepotChest(lua_State* L) { return 1; } - uint32_t depotId = getNumber<uint32_t>(L, 2); - bool autoCreate = getBoolean(L, 3, false); + const uint32_t depotId = getNumber<uint32_t>(L, 2); + const bool autoCreate = getBoolean(L, 3, false); const auto &depotChest = player->getDepotChest(depotId, autoCreate); if (depotChest) { player->setLastDepotId(depotId); @@ -848,8 +848,8 @@ int PlayerFunctions::luaPlayerAddExperience(lua_State* L) { // player:addExperience(experience[, sendText = false]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - int64_t experience = getNumber<int64_t>(L, 2); - bool sendText = getBoolean(L, 3, false); + const int64_t experience = getNumber<int64_t>(L, 2); + const bool sendText = getBoolean(L, 3, false); player->addExperience(nullptr, experience, sendText); pushBoolean(L, true); } else { @@ -862,8 +862,8 @@ int PlayerFunctions::luaPlayerRemoveExperience(lua_State* L) { // player:removeExperience(experience[, sendText = false]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - int64_t experience = getNumber<int64_t>(L, 2); - bool sendText = getBoolean(L, 3, false); + const int64_t experience = getNumber<int64_t>(L, 2); + const bool sendText = getBoolean(L, 3, false); player->removeExperience(experience, sendText); pushBoolean(L, true); } else { @@ -912,8 +912,8 @@ int PlayerFunctions::luaPlayerSendSpellCooldown(lua_State* L) { lua_pushnil(L); return 1; } - uint8_t spellId = getNumber<uint32_t>(L, 2, 1); - auto time = getNumber<uint32_t>(L, 3, 0); + const uint8_t spellId = getNumber<uint32_t>(L, 2, 1); + const auto time = getNumber<uint32_t>(L, 3, 0); player->sendSpellCooldown(spellId, time); pushBoolean(L, true); @@ -928,8 +928,8 @@ int PlayerFunctions::luaPlayerSendSpellGroupCooldown(lua_State* L) { lua_pushnil(L); return 1; } - auto groupId = getNumber<SpellGroup_t>(L, 2, SPELLGROUP_ATTACK); - auto time = getNumber<uint32_t>(L, 3, 0); + const auto groupId = getNumber<SpellGroup_t>(L, 2, SPELLGROUP_ATTACK); + const auto time = getNumber<uint32_t>(L, 3, 0); player->sendSpellGroupCooldown(groupId, time); pushBoolean(L, true); @@ -978,8 +978,8 @@ int PlayerFunctions::luaPlayerAddMana(lua_State* L) { return 1; } - int32_t manaChange = getNumber<int32_t>(L, 2); - bool animationOnLoss = getBoolean(L, 3, false); + const int32_t manaChange = getNumber<int32_t>(L, 2); + const bool animationOnLoss = getBoolean(L, 3, false); if (!animationOnLoss && manaChange < 0) { player->changeMana(manaChange); } else { @@ -1066,7 +1066,7 @@ int PlayerFunctions::luaPlayerGetBaseMaxMana(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillLevel(lua_State* L) { // player:getSkillLevel(skillType) - skills_t skillType = getNumber<skills_t>(L, 2); + const skills_t skillType = getNumber<skills_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].level); @@ -1078,7 +1078,7 @@ int PlayerFunctions::luaPlayerGetSkillLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetEffectiveSkillLevel(lua_State* L) { // player:getEffectiveSkillLevel(skillType) - skills_t skillType = getNumber<skills_t>(L, 2); + const skills_t skillType = getNumber<skills_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->getSkillLevel(skillType)); @@ -1090,7 +1090,7 @@ int PlayerFunctions::luaPlayerGetEffectiveSkillLevel(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillPercent(lua_State* L) { // player:getSkillPercent(skillType) - skills_t skillType = getNumber<skills_t>(L, 2); + const skills_t skillType = getNumber<skills_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].percent); @@ -1102,7 +1102,7 @@ int PlayerFunctions::luaPlayerGetSkillPercent(lua_State* L) { int PlayerFunctions::luaPlayerGetSkillTries(lua_State* L) { // player:getSkillTries(skillType) - skills_t skillType = getNumber<skills_t>(L, 2); + const skills_t skillType = getNumber<skills_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player && skillType <= SKILL_LAST) { lua_pushnumber(L, player->skills[skillType].tries); @@ -1116,8 +1116,8 @@ int PlayerFunctions::luaPlayerAddSkillTries(lua_State* L) { // player:addSkillTries(skillType, tries) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - skills_t skillType = getNumber<skills_t>(L, 2); - uint64_t tries = getNumber<uint64_t>(L, 3); + const skills_t skillType = getNumber<skills_t>(L, 2); + const uint64_t tries = getNumber<uint64_t>(L, 3); player->addSkillAdvance(skillType, tries); pushBoolean(L, true); } else { @@ -1130,7 +1130,7 @@ int PlayerFunctions::luaPlayerSetLevel(lua_State* L) { // player:setLevel(level) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t level = getNumber<uint16_t>(L, 2); + const uint16_t level = getNumber<uint16_t>(L, 2); player->level = level; player->experience = Player::getExpForLevel(level); player->sendStats(); @@ -1146,11 +1146,11 @@ int PlayerFunctions::luaPlayerSetMagicLevel(lua_State* L) { // player:setMagicLevel(level[, manaSpent]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t level = getNumber<uint16_t>(L, 2); + const uint16_t level = getNumber<uint16_t>(L, 2); player->magLevel = level; if (getNumber<uint64_t>(L, 3, 0) > 0) { - uint64_t manaSpent = getNumber<uint64_t>(L, 3); - uint64_t nextReqMana = player->vocation->getReqMana(level + 1); + const uint64_t manaSpent = getNumber<uint64_t>(L, 3); + const uint64_t nextReqMana = player->vocation->getReqMana(level + 1); player->manaSpent = manaSpent; player->magLevelPercent = Player::getPercentLevel(manaSpent, nextReqMana); } else { @@ -1170,12 +1170,12 @@ int PlayerFunctions::luaPlayerSetSkillLevel(lua_State* L) { // player:setSkillLevel(skillType, level[, tries]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - skills_t skillType = getNumber<skills_t>(L, 2); - uint16_t level = getNumber<uint16_t>(L, 3); + const skills_t skillType = getNumber<skills_t>(L, 2); + const uint16_t level = getNumber<uint16_t>(L, 3); player->skills[skillType].level = level; if (getNumber<uint64_t>(L, 4, 0) > 0) { - uint64_t tries = getNumber<uint64_t>(L, 4); - uint64_t nextReqTries = player->vocation->getReqSkillTries(skillType, level + 1); + const uint64_t tries = getNumber<uint64_t>(L, 4); + const uint64_t nextReqTries = player->vocation->getReqSkillTries(skillType, level + 1); player->skills[skillType].tries = tries; player->skills[skillType].percent = Player::getPercentLevel(tries, nextReqTries); } else { @@ -1195,7 +1195,7 @@ int PlayerFunctions::luaPlayerAddOfflineTrainingTime(lua_State* L) { // player:addOfflineTrainingTime(time) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - int32_t time = getNumber<int32_t>(L, 2); + const int32_t time = getNumber<int32_t>(L, 2); player->addOfflineTrainingTime(time); player->sendStats(); pushBoolean(L, true); @@ -1220,7 +1220,7 @@ int PlayerFunctions::luaPlayerRemoveOfflineTrainingTime(lua_State* L) { // player:removeOfflineTrainingTime(time) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - int32_t time = getNumber<int32_t>(L, 2); + const int32_t time = getNumber<int32_t>(L, 2); player->removeOfflineTrainingTime(time); player->sendStats(); pushBoolean(L, true); @@ -1234,8 +1234,8 @@ int PlayerFunctions::luaPlayerAddOfflineTrainingTries(lua_State* L) { // player:addOfflineTrainingTries(skillType, tries) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - skills_t skillType = getNumber<skills_t>(L, 2); - uint64_t tries = getNumber<uint64_t>(L, 3); + const skills_t skillType = getNumber<skills_t>(L, 2); + const uint64_t tries = getNumber<uint64_t>(L, 3); pushBoolean(L, player->addOfflineTrainingTries(skillType, tries)); } else { lua_pushnil(L); @@ -1258,7 +1258,7 @@ int PlayerFunctions::luaPlayerSetOfflineTrainingSkill(lua_State* L) { // player:setOfflineTrainingSkill(skillId) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - int8_t skillId = getNumber<int8_t>(L, 2); + const int8_t skillId = getNumber<int8_t>(L, 2); player->setOfflineTrainingSkill(skillId); pushBoolean(L, true); } else { @@ -1270,7 +1270,7 @@ int PlayerFunctions::luaPlayerSetOfflineTrainingSkill(lua_State* L) { int PlayerFunctions::luaPlayerOpenStash(lua_State* L) { // player:openStash(isNpc) const auto &player = getUserdataShared<Player>(L, 1); - bool isNpc = getBoolean(L, 2, false); + const bool isNpc = getBoolean(L, 2, false); if (player) { player->sendOpenStash(isNpc); pushBoolean(L, true); @@ -1300,7 +1300,7 @@ int PlayerFunctions::luaPlayerGetItemCount(lua_State* L) { } } - auto subType = getNumber<int32_t>(L, 3, -1); + const auto subType = getNumber<int32_t>(L, 3, -1); lua_pushnumber(L, player->getItemTypeCount(itemId, subType)); return 1; } @@ -1352,8 +1352,8 @@ int PlayerFunctions::luaPlayerGetItemById(lua_State* L) { return 1; } } - bool deepSearch = getBoolean(L, 3); - auto subType = getNumber<int32_t>(L, 4, -1); + const bool deepSearch = getBoolean(L, 3); + const auto subType = getNumber<int32_t>(L, 4, -1); const auto &item = g_game().findItemOfType(player, itemId, deepSearch, subType); if (item) { @@ -1437,7 +1437,7 @@ int PlayerFunctions::luaPlayerSetSex(lua_State* L) { // player:setSex(newSex) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - PlayerSex_t newSex = getNumber<PlayerSex_t>(L, 2); + const PlayerSex_t newSex = getNumber<PlayerSex_t>(L, 2); player->setSex(newSex); pushBoolean(L, true); } else { @@ -1461,7 +1461,7 @@ int PlayerFunctions::luaPlayerSetPronoun(lua_State* L) { // player:setPronoun(newPronoun) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - PlayerPronoun_t newPronoun = getNumber<PlayerPronoun_t>(L, 2); + const PlayerPronoun_t newPronoun = getNumber<PlayerPronoun_t>(L, 2); player->setPronoun(newPronoun); pushBoolean(L, true); } else { @@ -1508,7 +1508,7 @@ int PlayerFunctions::luaPlayerGetGuild(lua_State* L) { return 1; } - const auto guild = player->getGuild(); + const auto &guild = player->getGuild(); if (!guild) { lua_pushnil(L); return 1; @@ -1527,7 +1527,7 @@ int PlayerFunctions::luaPlayerSetGuild(lua_State* L) { return 1; } - const auto guild = getUserdataShared<Guild>(L, 2); + const auto &guild = getUserdataShared<Guild>(L, 2); player->setGuild(guild); pushBoolean(L, true); @@ -1547,14 +1547,14 @@ int PlayerFunctions::luaPlayerGetGuildLevel(lua_State* L) { int PlayerFunctions::luaPlayerSetGuildLevel(lua_State* L) { // player:setGuildLevel(level) - uint8_t level = getNumber<uint8_t>(L, 2); + const uint8_t level = getNumber<uint8_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (!player || !player->getGuild()) { lua_pushnil(L); return 1; } - GuildRank_ptr rank = player->getGuild()->getRankByLevel(level); + const auto &rank = player->getGuild()->getRankByLevel(level); if (!rank) { pushBoolean(L, false); } else { @@ -1621,9 +1621,9 @@ int PlayerFunctions::luaPlayerSetGroup(lua_State* L) { int PlayerFunctions::luaPlayerSetSpecialContainersAvailable(lua_State* L) { // player:setSpecialContainersAvailable(stashMenu, marketMenu, depotSearchMenu) - bool supplyStashMenu = getBoolean(L, 2, false); - bool marketMenu = getBoolean(L, 3, false); - bool depotSearchMenu = getBoolean(L, 4, false); + const bool supplyStashMenu = getBoolean(L, 2, false); + const bool marketMenu = getBoolean(L, 3, false); + const bool depotSearchMenu = getBoolean(L, 4, false); const auto &player = getUserdataShared<Player>(L, 1); if (player) { player->setSpecialMenuAvailable(supplyStashMenu, marketMenu, depotSearchMenu); @@ -1647,7 +1647,7 @@ int PlayerFunctions::luaPlayerGetStamina(lua_State* L) { int PlayerFunctions::luaPlayerSetStamina(lua_State* L) { // player:setStamina(stamina) - uint16_t stamina = getNumber<uint16_t>(L, 2); + const uint16_t stamina = getNumber<uint16_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player) { player->staminaMinutes = std::min<uint16_t>(2520, stamina); @@ -1671,7 +1671,7 @@ int PlayerFunctions::luaPlayerGetSoul(lua_State* L) { int PlayerFunctions::luaPlayerAddSoul(lua_State* L) { // player:addSoul(soulChange) - int32_t soulChange = getNumber<int32_t>(L, 2); + const int32_t soulChange = getNumber<int32_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player) { player->changeSoul(soulChange); @@ -1725,15 +1725,15 @@ int PlayerFunctions::luaPlayerGetStorageValue(lua_State* L) { return 1; } - uint32_t key = getNumber<uint32_t>(L, 2); + const uint32_t key = getNumber<uint32_t>(L, 2); lua_pushnumber(L, player->getStorageValue(key)); return 1; } int PlayerFunctions::luaPlayerSetStorageValue(lua_State* L) { // player:setStorageValue(key, value) - int32_t value = getNumber<int32_t>(L, 3); - uint32_t key = getNumber<uint32_t>(L, 2); + const int32_t value = getNumber<int32_t>(L, 3); + const uint32_t key = getNumber<uint32_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (IS_IN_KEYRANGE(key, RESERVED_RANGE)) { std::ostringstream ss; @@ -1767,7 +1767,7 @@ int PlayerFunctions::luaPlayerGetStorageValueByName(lua_State* L) { } g_logger().warn("The function 'player:getStorageValueByName' is deprecated and will be removed in future versions, please use KV system"); - auto name = getString(L, 2); + const auto name = getString(L, 2); lua_pushnumber(L, player->getStorageValueByName(name)); return 1; } @@ -1782,8 +1782,8 @@ int PlayerFunctions::luaPlayerSetStorageValueByName(lua_State* L) { } g_logger().warn("The function 'player:setStorageValueByName' is deprecated and will be removed in future versions, please use KV system"); - auto storageName = getString(L, 2); - int32_t value = getNumber<int32_t>(L, 3); + const auto storageName = getString(L, 2); + const int32_t value = getNumber<int32_t>(L, 3); player->addStorageValueByName(storageName, value); pushBoolean(L, true); @@ -1809,18 +1809,18 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { } } - auto count = getNumber<int32_t>(L, 3, 1); + const auto count = getNumber<int32_t>(L, 3, 1); auto subType = getNumber<int32_t>(L, 5, 1); const ItemType &it = Item::items[itemId]; int32_t itemCount = 1; - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); if (parameters >= 4) { itemCount = std::max<int32_t>(1, count); } else if (it.hasSubType()) { if (it.stackable) { - itemCount = std::ceil(count / (float_t)it.stackSize); + itemCount = std::ceil(count / static_cast<float_t>(it.stackSize)); } subType = count; @@ -1828,7 +1828,7 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { itemCount = std::max<int32_t>(1, count); } - bool hasTable = itemCount > 1; + const bool hasTable = itemCount > 1; if (hasTable) { lua_newtable(L); } else if (itemCount == 0) { @@ -1836,9 +1836,9 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { return 1; } - bool canDropOnMap = getBoolean(L, 4, true); - auto slot = getNumber<Slots_t>(L, 6, CONST_SLOT_WHEREEVER); - auto tier = getNumber<uint8_t>(L, 7, 0); + const bool canDropOnMap = getBoolean(L, 4, true); + const auto slot = getNumber<Slots_t>(L, 6, CONST_SLOT_WHEREEVER); + const auto tier = getNumber<uint8_t>(L, 7, 0); for (int32_t i = 1; i <= itemCount; ++i) { int32_t stackCount = subType; if (it.stackable) { @@ -1858,7 +1858,7 @@ int PlayerFunctions::luaPlayerAddItem(lua_State* L) { item->setTier(tier); } - ReturnValue ret = g_game().internalPlayerAddItem(player, item, canDropOnMap, slot); + const ReturnValue ret = g_game().internalPlayerAddItem(player, item, canDropOnMap, slot); if (ret != RETURNVALUE_NOERROR) { if (!hasTable) { lua_pushnil(L); @@ -1901,14 +1901,14 @@ int PlayerFunctions::luaPlayerAddItemEx(lua_State* L) { return 1; } - bool canDropOnMap = getBoolean(L, 3, false); + const bool canDropOnMap = getBoolean(L, 3, false); ReturnValue returnValue; if (canDropOnMap) { - auto slot = getNumber<Slots_t>(L, 4, CONST_SLOT_WHEREEVER); + const auto slot = getNumber<Slots_t>(L, 4, CONST_SLOT_WHEREEVER); returnValue = g_game().internalPlayerAddItem(player, item, true, slot); } else { - auto index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER); - auto flags = getNumber<uint32_t>(L, 5, 0); + const auto index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER); + const auto flags = getNumber<uint32_t>(L, 5, 0); returnValue = g_game().internalAddItem(player, item, index, flags); } @@ -1927,8 +1927,8 @@ int PlayerFunctions::luaPlayerAddItemStash(lua_State* L) { return 1; } - auto itemId = getNumber<uint16_t>(L, 2); - auto count = getNumber<uint32_t>(L, 3, 1); + const auto itemId = getNumber<uint16_t>(L, 2); + const auto count = getNumber<uint32_t>(L, 3, 1); player->addItemOnStash(itemId, count); pushBoolean(L, true); @@ -1960,7 +1960,7 @@ int PlayerFunctions::luaPlayerRemoveStashItem(lua_State* L) { return 1; } - uint32_t count = getNumber<uint32_t>(L, 3); + const uint32_t count = getNumber<uint32_t>(L, 3); pushBoolean(L, player->withdrawItem(itemType.id, count)); return 1; } @@ -1984,9 +1984,9 @@ int PlayerFunctions::luaPlayerRemoveItem(lua_State* L) { } } - uint32_t count = getNumber<uint32_t>(L, 3); - auto subType = getNumber<int32_t>(L, 4, -1); - bool ignoreEquipped = getBoolean(L, 5, false); + const uint32_t count = getNumber<uint32_t>(L, 3); + const auto subType = getNumber<int32_t>(L, 4, -1); + const bool ignoreEquipped = getBoolean(L, 5, false); pushBoolean(L, player->removeItemOfType(itemId, count, subType, ignoreEquipped)); return 1; } @@ -2018,7 +2018,7 @@ int PlayerFunctions::luaPlayerSendUpdateContainer(lua_State* L) { return 1; } - const auto container = getUserdataShared<Container>(L, 2); + const auto &container = getUserdataShared<Container>(L, 2); if (!container) { reportErrorFunc("Container is nullptr"); return 1; @@ -2042,7 +2042,7 @@ int PlayerFunctions::luaPlayerGetMoney(lua_State* L) { int PlayerFunctions::luaPlayerAddMoney(lua_State* L) { // player:addMoney(money) - uint64_t money = getNumber<uint64_t>(L, 2); + const uint64_t money = getNumber<uint64_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player) { g_game().addMoney(player, money); @@ -2057,9 +2057,9 @@ int PlayerFunctions::luaPlayerRemoveMoney(lua_State* L) { // player:removeMoney(money[, flags = 0[, useBank = true]]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint64_t money = getNumber<uint64_t>(L, 2); - auto flags = getNumber<int32_t>(L, 3, 0); - bool useBank = getBoolean(L, 4, true); + const uint64_t money = getNumber<uint64_t>(L, 2); + const auto flags = getNumber<int32_t>(L, 3, 0); + const bool useBank = getBoolean(L, 4, true); pushBoolean(L, g_game().removeMoney(player, money, flags, useBank)); } else { lua_pushnil(L); @@ -2076,10 +2076,10 @@ int PlayerFunctions::luaPlayerShowTextDialog(lua_State* L) { } auto length = getNumber<int32_t>(L, 5, -1); - bool canWrite = getBoolean(L, 4, false); + const bool canWrite = getBoolean(L, 4, false); std::string text; - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); if (parameters >= 3) { text = getString(L, 3); } @@ -2132,11 +2132,11 @@ int PlayerFunctions::luaPlayerSendTextMessage(lua_State* L) { return 1; } - int parameters = lua_gettop(L); + const int parameters = lua_gettop(L); TextMessage message(getNumber<MessageClasses>(L, 2), getString(L, 3)); if (parameters == 4) { - uint16_t channelId = getNumber<uint16_t>(L, 4); + const uint16_t channelId = getNumber<uint16_t>(L, 4); const auto &channel = g_chat().getChannel(player, channelId); if (!channel || !channel->hasUser(player)) { pushBoolean(L, false); @@ -2170,8 +2170,8 @@ int PlayerFunctions::luaPlayerSendChannelMessage(lua_State* L) { return 1; } - uint16_t channelId = getNumber<uint16_t>(L, 5); - SpeakClasses type = getNumber<SpeakClasses>(L, 4); + const uint16_t channelId = getNumber<uint16_t>(L, 5); + const SpeakClasses type = getNumber<SpeakClasses>(L, 4); const std::string &text = getString(L, 3); const std::string &author = getString(L, 2); player->sendChannelMessage(author, text, type, channelId); @@ -2189,7 +2189,7 @@ int PlayerFunctions::luaPlayerSendPrivateMessage(lua_State* L) { const auto &speaker = getUserdataShared<Player>(L, 2); const std::string &text = getString(L, 3); - auto type = getNumber<SpeakClasses>(L, 4, TALKTYPE_PRIVATE_FROM); + const auto type = getNumber<SpeakClasses>(L, 4, TALKTYPE_PRIVATE_FROM); player->sendPrivateMessage(speaker, type, text); pushBoolean(L, true); return 1; @@ -2204,9 +2204,9 @@ int PlayerFunctions::luaPlayerChannelSay(lua_State* L) { } const auto &speaker = getCreature(L, 2); - SpeakClasses type = getNumber<SpeakClasses>(L, 3); + const SpeakClasses type = getNumber<SpeakClasses>(L, 3); const std::string &text = getString(L, 4); - uint16_t channelId = getNumber<uint16_t>(L, 5); + const uint16_t channelId = getNumber<uint16_t>(L, 5); player->sendToChannel(speaker, type, text, channelId); pushBoolean(L, true); return 1; @@ -2214,7 +2214,7 @@ int PlayerFunctions::luaPlayerChannelSay(lua_State* L) { int PlayerFunctions::luaPlayerOpenChannel(lua_State* L) { // player:openChannel(channelId) - uint16_t channelId = getNumber<uint16_t>(L, 2); + const uint16_t channelId = getNumber<uint16_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player) { g_game().playerOpenChannel(player->getID(), channelId); @@ -2233,7 +2233,7 @@ int PlayerFunctions::luaPlayerGetSlotItem(lua_State* L) { return 1; } - uint32_t slot = getNumber<uint32_t>(L, 2); + const uint32_t slot = getNumber<uint32_t>(L, 2); const auto &thing = player->getThing(slot); if (!thing) { lua_pushnil(L); @@ -2284,8 +2284,8 @@ int PlayerFunctions::luaPlayerAddOutfitAddon(lua_State* L) { // player:addOutfitAddon(lookType, addon) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); - uint8_t addon = getNumber<uint8_t>(L, 3); + const uint16_t lookType = getNumber<uint16_t>(L, 2); + const uint8_t addon = getNumber<uint8_t>(L, 3); player->addOutfit(lookType, addon); pushBoolean(L, true); } else { @@ -2298,7 +2298,7 @@ int PlayerFunctions::luaPlayerRemoveOutfit(lua_State* L) { // player:removeOutfit(lookType) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); + const uint16_t lookType = getNumber<uint16_t>(L, 2); pushBoolean(L, player->removeOutfit(lookType)); } else { lua_pushnil(L); @@ -2310,8 +2310,8 @@ int PlayerFunctions::luaPlayerRemoveOutfitAddon(lua_State* L) { // player:removeOutfitAddon(lookType, addon) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); - uint8_t addon = getNumber<uint8_t>(L, 3); + const uint16_t lookType = getNumber<uint16_t>(L, 2); + const uint8_t addon = getNumber<uint8_t>(L, 3); pushBoolean(L, player->removeOutfitAddon(lookType, addon)); } else { lua_pushnil(L); @@ -2323,8 +2323,8 @@ int PlayerFunctions::luaPlayerHasOutfit(lua_State* L) { // player:hasOutfit(lookType[, addon = 0]) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); - auto addon = getNumber<uint8_t>(L, 3, 0); + const uint16_t lookType = getNumber<uint16_t>(L, 2); + const auto addon = getNumber<uint8_t>(L, 3, 0); pushBoolean(L, player->canWear(lookType, addon)); } else { lua_pushnil(L); @@ -2429,7 +2429,7 @@ int PlayerFunctions::luaPlayerRemoveFamiliar(lua_State* L) { // player:removeFamiliar(lookType) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); + const uint16_t lookType = getNumber<uint16_t>(L, 2); pushBoolean(L, player->removeFamiliar(lookType)); } else { lua_pushnil(L); @@ -2441,7 +2441,7 @@ int PlayerFunctions::luaPlayerHasFamiliar(lua_State* L) { // player:hasFamiliar(lookType) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t lookType = getNumber<uint16_t>(L, 2); + const uint16_t lookType = getNumber<uint16_t>(L, 2); pushBoolean(L, player->canFamiliar(lookType)); } else { lua_pushnil(L); @@ -2491,13 +2491,13 @@ int PlayerFunctions::luaPlayerAddPremiumDays(lua_State* L) { return 1; } - auto premiumDays = player->getAccount()->getPremiumRemainingDays(); + const auto premiumDays = player->getAccount()->getPremiumRemainingDays(); if (premiumDays == std::numeric_limits<uint16_t>::max()) { return 1; } - int32_t addDays = std::min<int32_t>(0xFFFE - premiumDays, getNumber<uint16_t>(L, 2)); + const int32_t addDays = std::min<int32_t>(0xFFFE - premiumDays, getNumber<uint16_t>(L, 2)); if (addDays <= 0) { return 1; } @@ -2520,13 +2520,13 @@ int PlayerFunctions::luaPlayerRemovePremiumDays(lua_State* L) { return 1; } - auto premiumDays = player->getAccount()->getPremiumRemainingDays(); + const auto premiumDays = player->getAccount()->getPremiumRemainingDays(); if (premiumDays == std::numeric_limits<uint16_t>::max()) { return 1; } - int32_t removeDays = std::min<int32_t>(0xFFFE - premiumDays, getNumber<uint16_t>(L, 2)); + const int32_t removeDays = std::min<int32_t>(0xFFFE - premiumDays, getNumber<uint16_t>(L, 2)); if (removeDays <= 0) { return 1; } @@ -2682,7 +2682,7 @@ int PlayerFunctions::luaPlayerRemoveTransferableCoins(lua_State* L) { int PlayerFunctions::luaPlayerHasBlessing(lua_State* L) { // player:hasBlessing(blessing) - uint8_t blessing = getNumber<uint8_t>(L, 2); + const uint8_t blessing = getNumber<uint8_t>(L, 2); const auto &player = getUserdataShared<Player>(L, 1); if (player) { pushBoolean(L, player->hasBlessing(blessing)); @@ -2700,8 +2700,8 @@ int PlayerFunctions::luaPlayerAddBlessing(lua_State* L) { return 1; } - uint8_t blessing = getNumber<uint8_t>(L, 2); - uint8_t count = getNumber<uint8_t>(L, 3); + const uint8_t blessing = getNumber<uint8_t>(L, 2); + const uint8_t count = getNumber<uint8_t>(L, 3); player->addBlessing(blessing, count); player->sendBlessStatus(); @@ -2717,8 +2717,8 @@ int PlayerFunctions::luaPlayerRemoveBlessing(lua_State* L) { return 1; } - uint8_t blessing = getNumber<uint8_t>(L, 2); - uint8_t count = getNumber<uint8_t>(L, 3); + const uint8_t blessing = getNumber<uint8_t>(L, 2); + const uint8_t count = getNumber<uint8_t>(L, 3); if (!player->hasBlessing(blessing)) { pushBoolean(L, false); @@ -2755,7 +2755,7 @@ int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { } const std::string &spellName = getString(L, 2); - const auto spell = g_spells().getInstantSpellByName(spellName); + const auto &spell = g_spells().getInstantSpellByName(spellName); if (!spell) { reportErrorFunc("Spell \"" + spellName + "\" not found"); pushBoolean(L, false); @@ -2768,7 +2768,7 @@ int PlayerFunctions::luaPlayerCanLearnSpell(lua_State* L) { } const auto vocMap = spell->getVocMap(); - if (vocMap.count(player->getVocationId()) == 0) { + if (!vocMap.contains(player->getVocationId())) { pushBoolean(L, false); } else if (player->getLevel() < spell->getLevel()) { pushBoolean(L, false); @@ -2822,7 +2822,7 @@ int PlayerFunctions::luaPlayerSendTutorial(lua_State* L) { // player:sendTutorial(tutorialId) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint8_t tutorialId = getNumber<uint8_t>(L, 2); + const uint8_t tutorialId = getNumber<uint8_t>(L, 2); player->sendTutorial(tutorialId); pushBoolean(L, true); } else { @@ -2869,7 +2869,7 @@ int PlayerFunctions::luaPlayerAddMapMark(lua_State* L) { const auto &player = getUserdataShared<Player>(L, 1); if (player) { const Position &position = getPosition(L, 2); - uint8_t type = getNumber<uint8_t>(L, 3); + const uint8_t type = getNumber<uint8_t>(L, 3); const std::string &description = getString(L, 4); player->sendAddMarker(position, type, description); pushBoolean(L, true); @@ -2962,7 +2962,7 @@ int PlayerFunctions::luaPlayerSendHouseWindow(lua_State* L) { return 1; } - uint32_t listId = getNumber<uint32_t>(L, 3); + const uint32_t listId = getNumber<uint32_t>(L, 3); player->sendHouseWindow(house, listId); pushBoolean(L, true); return 1; @@ -2982,7 +2982,7 @@ int PlayerFunctions::luaPlayerSetEditHouse(lua_State* L) { return 1; } - uint32_t listId = getNumber<uint32_t>(L, 3); + const uint32_t listId = getNumber<uint32_t>(L, 3); player->setEditHouse(house, listId); pushBoolean(L, true); return 1; @@ -2996,7 +2996,7 @@ int PlayerFunctions::luaPlayerSetGhostMode(lua_State* L) { return 1; } - bool enabled = getBoolean(L, 2); + const bool enabled = getBoolean(L, 2); if (player->isInGhostMode() == enabled) { pushBoolean(L, true); return 1; @@ -3092,8 +3092,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { } std::vector<std::shared_ptr<InstantSpell>> spells; - spells.reserve(30); - for (auto &[key, spell] : g_spells().getInstantSpells()) { + for (const auto &[key, spell] : g_spells().getInstantSpells()) { if (spell->canCast(player)) { spells.push_back(spell); } @@ -3112,7 +3111,7 @@ int PlayerFunctions::luaPlayerGetInstantSpells(lua_State* L) { int PlayerFunctions::luaPlayerCanCast(lua_State* L) { // player:canCast(spell) const auto &player = getUserdataShared<Player>(L, 1); - const auto spell = getUserdataShared<InstantSpell>(L, 2); + const auto &spell = getUserdataShared<InstantSpell>(L, 2); if (player && spell) { pushBoolean(L, spell->canCast(player)); } else { @@ -3241,7 +3240,7 @@ int PlayerFunctions::luaPlayerSetXpBoostPercent(lua_State* L) { // player:setXpBoostPercent(value) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t percent = getNumber<uint16_t>(L, 2); + const uint16_t percent = getNumber<uint16_t>(L, 2); player->setXpBoostPercent(percent); pushBoolean(L, true); } else { @@ -3278,7 +3277,7 @@ int PlayerFunctions::luaPlayerSetXpBoostTime(lua_State* L) { // player:setXpBoostTime(timeLeft) const auto &player = getUserdataShared<Player>(L, 1); if (player) { - uint16_t timeLeft = getNumber<uint16_t>(L, 2); + const uint16_t timeLeft = getNumber<uint16_t>(L, 2); player->setXpBoostTime(timeLeft); player->sendStats(); pushBoolean(L, true); @@ -3507,7 +3506,7 @@ int PlayerFunctions::luaPlayerSetFaction(lua_State* L) { return 0; } - Faction_t factionId = getNumber<Faction_t>(L, 2); + const Faction_t factionId = getNumber<Faction_t>(L, 2); player->setFaction(factionId); pushBoolean(L, true); return 1; @@ -3535,7 +3534,7 @@ int PlayerFunctions::luaPlayerIsUIExhausted(lua_State* L) { return 0; } - uint16_t time = getNumber<uint16_t>(L, 2); + const uint16_t time = getNumber<uint16_t>(L, 2); pushBoolean(L, player->isUIExhausted(time)); return 1; } @@ -3573,14 +3572,14 @@ int PlayerFunctions::luaPlayerGetBosstiaryLevel(lua_State* L) { // player:getBosstiaryLevel(name) if (const auto &player = getUserdataShared<Player>(L, 1); player) { - const auto mtype = g_monsters().getMonsterType(getString(L, 2)); + const auto &mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { - uint32_t bossId = mtype->info.raceid; + const uint32_t bossId = mtype->info.raceid; if (bossId == 0) { lua_pushnil(L); return 0; } - auto level = g_ioBosstiary().getBossCurrentLevel(player, bossId); + const auto level = g_ioBosstiary().getBossCurrentLevel(player, bossId); lua_pushnumber(L, level); } else { lua_pushnil(L); @@ -3595,14 +3594,14 @@ int PlayerFunctions::luaPlayerGetBosstiaryKills(lua_State* L) { // player:getBosstiaryKills(name) if (const auto &player = getUserdataShared<Player>(L, 1); player) { - const auto mtype = g_monsters().getMonsterType(getString(L, 2)); + const auto &mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { - uint32_t bossId = mtype->info.raceid; + const uint32_t bossId = mtype->info.raceid; if (bossId == 0) { lua_pushnil(L); return 0; } - uint32_t currentKills = player->getBestiaryKillCount(static_cast<uint16_t>(bossId)); + const uint32_t currentKills = player->getBestiaryKillCount(static_cast<uint16_t>(bossId)); lua_pushnumber(L, currentKills); } else { lua_pushnil(L); @@ -3617,7 +3616,7 @@ int PlayerFunctions::luaPlayerAddBosstiaryKill(lua_State* L) { // player:addBosstiaryKill(name[, amount = 1]) if (const auto &player = getUserdataShared<Player>(L, 1); player) { - const auto mtype = g_monsters().getMonsterType(getString(L, 2)); + const auto &mtype = g_monsters().getMonsterType(getString(L, 2)); if (mtype) { g_ioBosstiary().addBosstiaryKill(player, mtype, getNumber<uint32_t>(L, 3, 1)); pushBoolean(L, true); @@ -3667,8 +3666,8 @@ int PlayerFunctions::luaPlayerGetSlotBossId(lua_State* L) { return 0; } - uint8_t slotId = getNumber<uint8_t>(L, 2); - auto bossId = player->getSlotBossId(slotId); + const uint8_t slotId = getNumber<uint8_t>(L, 2); + const auto bossId = player->getSlotBossId(slotId); lua_pushnumber(L, static_cast<lua_Number>(bossId)); return 1; } @@ -3682,14 +3681,14 @@ int PlayerFunctions::luaPlayerGetBossBonus(lua_State* L) { return 0; } - uint8_t slotId = getNumber<uint8_t>(L, 2); - auto bossId = player->getSlotBossId(slotId); + const uint8_t slotId = getNumber<uint8_t>(L, 2); + const auto bossId = player->getSlotBossId(slotId); - uint32_t playerBossPoints = player->getBossPoints(); - uint16_t currentBonus = g_ioBosstiary().calculateLootBonus(playerBossPoints); + const uint32_t playerBossPoints = player->getBossPoints(); + const uint16_t currentBonus = g_ioBosstiary().calculateLootBonus(playerBossPoints); - auto bossLevel = g_ioBosstiary().getBossCurrentLevel(player, bossId); - uint16_t bonusBoss = currentBonus + (bossLevel == 3 ? 25 : 0); + const auto bossLevel = g_ioBosstiary().getBossCurrentLevel(player, bossId); + const uint16_t bonusBoss = currentBonus + (bossLevel == 3 ? 25 : 0); lua_pushnumber(L, static_cast<lua_Number>(bonusBoss)); return 1; @@ -3704,8 +3703,8 @@ int PlayerFunctions::luaPlayerSendSingleSoundEffect(lua_State* L) { return 0; } - SoundEffect_t soundEffect = getNumber<SoundEffect_t>(L, 2); - bool actor = getBoolean(L, 3, true); + const SoundEffect_t soundEffect = getNumber<SoundEffect_t>(L, 2); + const bool actor = getBoolean(L, 3, true); player->sendSingleSoundEffect(player->getPosition(), soundEffect, actor ? SourceEffect_t::OWN : SourceEffect_t::GLOBAL); pushBoolean(L, true); @@ -3721,9 +3720,9 @@ int PlayerFunctions::luaPlayerSendDoubleSoundEffect(lua_State* L) { return 0; } - SoundEffect_t mainSoundEffect = getNumber<SoundEffect_t>(L, 2); - SoundEffect_t secondarySoundEffect = getNumber<SoundEffect_t>(L, 3); - bool actor = getBoolean(L, 4, true); + const SoundEffect_t mainSoundEffect = getNumber<SoundEffect_t>(L, 2); + const SoundEffect_t secondarySoundEffect = getNumber<SoundEffect_t>(L, 3); + const bool actor = getBoolean(L, 4, true); player->sendDoubleSoundEffect(player->getPosition(), mainSoundEffect, actor ? SourceEffect_t::OWN : SourceEffect_t::GLOBAL, secondarySoundEffect, actor ? SourceEffect_t::OWN : SourceEffect_t::GLOBAL); pushBoolean(L, true); @@ -3755,7 +3754,7 @@ int PlayerFunctions::luaPlayerChangeName(lua_State* L) { player->removePlayer(true, true); } player->kv()->remove("namelock"); - auto newName = getString(L, 2); + const auto newName = getString(L, 2); player->setName(newName); g_saveManager().savePlayer(player); return 1; @@ -3899,7 +3898,7 @@ int PlayerFunctions::luaPlayerInstantSkillWOD(lua_State* L) { return 1; } - std::string name = getString(L, 2); + const std::string name = getString(L, 2); if (lua_gettop(L) == 2) { pushBoolean(L, player->wheel()->getInstant(name)); } else { @@ -3922,13 +3921,13 @@ int PlayerFunctions::luaPlayerUpgradeSpellWOD(lua_State* L) { return 1; } - std::string name = getString(L, 2); + const std::string name = getString(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, static_cast<lua_Number>(player->wheel()->getSpellUpgrade(name))); return 1; } - bool add = getBoolean(L, 3); + const bool add = getBoolean(L, 3); if (add) { player->wheel()->upgradeSpell(name); } else { @@ -3952,13 +3951,13 @@ int PlayerFunctions::luaPlayerRevelationStageWOD(lua_State* L) { return 1; } - std::string name = getString(L, 2); + const std::string name = getString(L, 2); if (lua_gettop(L) == 2) { lua_pushnumber(L, static_cast<lua_Number>(player->wheel()->getStage(name))); return 1; } - bool value = getNumber<uint8_t>(L, 3); + const bool value = getNumber<uint8_t>(L, 3); player->wheel()->setSpellInstant(name, value); pushBoolean(L, true); @@ -4004,7 +4003,7 @@ int PlayerFunctions::luaPlayerAvatarTimer(lua_State* L) { } if (lua_gettop(L) == 1) { - lua_pushnumber(L, (lua_Number)player->wheel()->getOnThinkTimer(WheelOnThink_t::AVATAR_SPELL)); + lua_pushnumber(L, static_cast<lua_Number>(player->wheel()->getOnThinkTimer(WheelOnThink_t::AVATAR_SPELL))); } else { player->wheel()->setOnThinkTimer(WheelOnThink_t::AVATAR_SPELL, getNumber<int64_t>(L, 2)); pushBoolean(L, true); @@ -4021,14 +4020,14 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalArea(lua_State* L) { return 0; } - auto spellName = getString(L, 2); + const auto spellName = getString(L, 2); if (spellName.empty()) { reportErrorFunc("Spell name is empty"); pushBoolean(L, false); return 0; } - auto spell = g_spells().getInstantSpellByName(spellName); + const auto &spell = g_spells().getInstantSpellByName(spellName); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); @@ -4048,14 +4047,14 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalTarget(lua_State* L) { return 0; } - auto spellName = getString(L, 2); + const auto spellName = getString(L, 2); if (spellName.empty()) { reportErrorFunc("Spell name is empty"); pushBoolean(L, false); return 0; } - auto spell = g_spells().getInstantSpellByName(spellName); + const auto &spell = g_spells().getInstantSpellByName(spellName); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); @@ -4075,14 +4074,14 @@ int PlayerFunctions::luaPlayerGetWheelSpellAdditionalDuration(lua_State* L) { return 0; } - auto spellName = getString(L, 2); + const auto spellName = getString(L, 2); if (spellName.empty()) { reportErrorFunc("Spell name is empty"); pushBoolean(L, false); return 0; } - auto spell = g_spells().getInstantSpellByName(spellName); + const auto &spell = g_spells().getInstantSpellByName(spellName); if (!spell) { reportErrorFunc(getErrorDesc(LUA_ERROR_SPELL_NOT_FOUND)); pushBoolean(L, false); @@ -4157,7 +4156,7 @@ int PlayerFunctions::luaPlayerGetVipTime(lua_State* L) { int PlayerFunctions::luaPlayerKV(lua_State* L) { // player:kv() - auto player = getUserdataShared<Player>(L, 1); + const auto &player = getUserdataShared<Player>(L, 1); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -4177,7 +4176,7 @@ int PlayerFunctions::luaPlayerGetStoreInbox(lua_State* L) { return 1; } - if (auto item = player->getStoreInbox()) { + if (const auto &item = player->getStoreInbox()) { pushUserdata<Item>(L, item); setItemMetatable(L, -1, item); } else { @@ -4220,7 +4219,7 @@ int PlayerFunctions::luaPlayerAddAchievement(lua_State* L) { achievementId = g_game().getAchievementByName(getString(L, 2)).id; } - bool success = player->achiev()->add(achievementId, getBoolean(L, 3, true)); + const bool success = player->achiev()->add(achievementId, getBoolean(L, 3, true)); if (success) { player->sendTakeScreenshot(SCREENSHOT_TYPE_ACHIEVEMENT); } @@ -4268,7 +4267,7 @@ int PlayerFunctions::luaPlayerAddAchievementPoints(lua_State* L) { return 1; } - auto points = getNumber<uint16_t>(L, 2); + const auto points = getNumber<uint16_t>(L, 2); if (points > 0) { player->achiev()->addPoints(points); } @@ -4284,7 +4283,7 @@ int PlayerFunctions::luaPlayerRemoveAchievementPoints(lua_State* L) { return 1; } - auto points = getNumber<uint16_t>(L, 2); + const auto points = getNumber<uint16_t>(L, 2); if (points > 0) { player->achiev()->removePoints(points); } @@ -4326,7 +4325,7 @@ int PlayerFunctions::luaPlayerGetTitles(lua_State* L) { return 1; } - auto playerTitles = player->title()->getUnlockedTitles(); + const auto playerTitles = player->title()->getUnlockedTitles(); lua_createtable(L, static_cast<int>(playerTitles.size()), 0); int index = 0; @@ -4367,14 +4366,14 @@ int PlayerFunctions::luaPlayerCreateTransactionSummary(lua_State* L) { return 1; } - auto type = getNumber<uint8_t>(L, 2, 0); + const auto type = getNumber<uint8_t>(L, 2, 0); if (type == 0) { reportErrorFunc(getErrorDesc(LUA_ERROR_VARIANT_NOT_FOUND)); return 1; } - auto amount = getNumber<uint16_t>(L, 3, 1); - auto id = getString(L, 4, ""); + const auto amount = getNumber<uint16_t>(L, 3, 1); + const auto id = getString(L, 4, ""); player->cyclopedia()->updateStoreSummary(type, amount, id); pushBoolean(L, true); @@ -4389,7 +4388,7 @@ int PlayerFunctions::luaPlayerTakeScreenshot(lua_State* L) { return 1; } - auto screenshotType = getNumber<Screenshot_t>(L, 2); + const auto screenshotType = getNumber<Screenshot_t>(L, 2); player->sendTakeScreenshot(screenshotType); pushBoolean(L, true); return 1; @@ -4403,7 +4402,7 @@ int PlayerFunctions::luaPlayerSendIconBakragore(lua_State* L) { return 1; } - auto iconType = getNumber<IconBakragore>(L, 2); + const auto iconType = getNumber<IconBakragore>(L, 2); player->sendIconBakragore(iconType); pushBoolean(L, true); return 1; @@ -4417,7 +4416,7 @@ int PlayerFunctions::luaPlayerRemoveIconBakragore(lua_State* L) { return 1; } - auto iconType = getNumber<IconBakragore>(L, 2, IconBakragore::None); + const auto iconType = getNumber<IconBakragore>(L, 2, IconBakragore::None); if (iconType == IconBakragore::None) { player->removeBakragoreIcons(); } else { diff --git a/src/lua/functions/creatures/player/vocation_functions.cpp b/src/lua/functions/creatures/player/vocation_functions.cpp index 5cd64cbe1d3..0b1c31bfa65 100644 --- a/src/lua/functions/creatures/player/vocation_functions.cpp +++ b/src/lua/functions/creatures/player/vocation_functions.cpp @@ -90,8 +90,8 @@ int VocationFunctions::luaVocationGetRequiredSkillTries(lua_State* L) { // vocation:getRequiredSkillTries(skillType, skillLevel) const auto &vocation = getUserdataShared<Vocation>(L, 1); if (vocation) { - skills_t skillType = getNumber<skills_t>(L, 2); - uint16_t skillLevel = getNumber<uint16_t>(L, 3); + const skills_t skillType = getNumber<skills_t>(L, 2); + const uint16_t skillLevel = getNumber<uint16_t>(L, 3); lua_pushnumber(L, vocation->getReqSkillTries(skillType, skillLevel)); } else { lua_pushnil(L); @@ -103,7 +103,7 @@ int VocationFunctions::luaVocationGetRequiredManaSpent(lua_State* L) { // vocation:getRequiredManaSpent(magicLevel) const auto &vocation = getUserdataShared<Vocation>(L, 1); if (vocation) { - uint32_t magicLevel = getNumber<uint32_t>(L, 2); + const uint32_t magicLevel = getNumber<uint32_t>(L, 2); lua_pushnumber(L, vocation->getReqMana(magicLevel)); } else { lua_pushnil(L); @@ -251,7 +251,7 @@ int VocationFunctions::luaVocationGetDemotion(lua_State* L) { return 1; } - uint16_t fromId = vocation->getFromVocation(); + const uint16_t fromId = vocation->getFromVocation(); if (fromId == VOCATION_NONE) { lua_pushnil(L); return 1; @@ -275,7 +275,7 @@ int VocationFunctions::luaVocationGetPromotion(lua_State* L) { return 1; } - uint16_t promotedId = g_vocations().getPromotedVocation(vocation->getId()); + const uint16_t promotedId = g_vocations().getPromotedVocation(vocation->getId()); if (promotedId == VOCATION_NONE) { lua_pushnil(L); return 1; diff --git a/src/lua/functions/creatures/player/vocation_functions.hpp b/src/lua/functions/creatures/player/vocation_functions.hpp index 0895f6ac8d6..7d98131ecb3 100644 --- a/src/lua/functions/creatures/player/vocation_functions.hpp +++ b/src/lua/functions/creatures/player/vocation_functions.hpp @@ -13,6 +13,12 @@ class VocationFunctions final : LuaScriptInterface { public: + explicit VocationFunctions(lua_State* L) : + LuaScriptInterface("VocationFunctions") { + init(L); + } + ~VocationFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Vocation", "", VocationFunctions::luaVocationCreate); registerMetaMethod(L, "Vocation", "__eq", VocationFunctions::luaUserdataCompare); diff --git a/src/lua/functions/events/action_functions.cpp b/src/lua/functions/events/action_functions.cpp index 6260cb78614..ef346594490 100644 --- a/src/lua/functions/events/action_functions.cpp +++ b/src/lua/functions/events/action_functions.cpp @@ -60,7 +60,7 @@ int ActionFunctions::luaActionItemId(lua_State* L) { // action:id(ids) const auto &action = getUserdataShared<Action>(L, 1); if (action) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { action->setItemIdsVector(getNumber<uint16_t>(L, 2 + i)); @@ -80,7 +80,7 @@ int ActionFunctions::luaActionActionId(lua_State* L) { // action:aid(aids) const auto &action = getUserdataShared<Action>(L, 1); if (action) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { action->setActionIdsVector(getNumber<uint16_t>(L, 2 + i)); @@ -100,7 +100,7 @@ int ActionFunctions::luaActionUniqueId(lua_State* L) { // action:uid(uids) const auto &action = getUserdataShared<Action>(L, 1); if (action) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { action->setUniqueIdsVector(getNumber<uint16_t>(L, 2 + i)); @@ -129,10 +129,10 @@ int ActionFunctions::luaActionPosition(lua_State* L) { return 1; } - Position position = getPosition(L, 2); + const Position position = getPosition(L, 2); // The parameter "- 1" because self is a parameter aswell, which we want to skip L 1 (UserData) // isNumber(L, 2) is for skip the itemId - if (int parameters = lua_gettop(L) - 1; + if (const int parameters = lua_gettop(L) - 1; parameters > 1 && isNumber(L, 2)) { for (int i = 0; i < parameters; ++i) { action->setPositionsVector(getPosition(L, 2 + i)); diff --git a/src/lua/functions/events/action_functions.hpp b/src/lua/functions/events/action_functions.hpp index 952ee746a5a..0816ca9d334 100644 --- a/src/lua/functions/events/action_functions.hpp +++ b/src/lua/functions/events/action_functions.hpp @@ -13,6 +13,12 @@ class ActionFunctions final : LuaScriptInterface { public: + explicit ActionFunctions(lua_State* L) : + LuaScriptInterface("ActionFunctions") { + init(L); + } + ~ActionFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Action", "", ActionFunctions::luaCreateAction); registerMethod(L, "Action", "onUse", ActionFunctions::luaActionOnUse); diff --git a/src/lua/functions/events/creature_event_functions.cpp b/src/lua/functions/events/creature_event_functions.cpp index a82f1105723..10aa8742552 100644 --- a/src/lua/functions/events/creature_event_functions.cpp +++ b/src/lua/functions/events/creature_event_functions.cpp @@ -27,7 +27,7 @@ int CreatureEventFunctions::luaCreatureEventType(lua_State* L) { const auto &creatureEvent = getUserdataShared<CreatureEvent>(L, 1); if (creatureEvent) { std::string typeName = getString(L, 2); - std::string tmpStr = asLowerCaseString(typeName); + const std::string tmpStr = asLowerCaseString(typeName); if (tmpStr == "login") { creatureEvent->setEventType(CREATURE_EVENT_LOGIN); } else if (tmpStr == "logout") { diff --git a/src/lua/functions/events/creature_event_functions.hpp b/src/lua/functions/events/creature_event_functions.hpp index 64b9e6e4eb8..f605d517fbf 100644 --- a/src/lua/functions/events/creature_event_functions.hpp +++ b/src/lua/functions/events/creature_event_functions.hpp @@ -13,6 +13,12 @@ class CreatureEventFunctions final : LuaScriptInterface { public: + explicit CreatureEventFunctions(lua_State* L) : + LuaScriptInterface("CreatureEventFunctions") { + init(L); + } + ~CreatureEventFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "CreatureEvent", "", CreatureEventFunctions::luaCreateCreatureEvent); registerMethod(L, "CreatureEvent", "type", CreatureEventFunctions::luaCreatureEventType); diff --git a/src/lua/functions/events/event_callback_functions.hpp b/src/lua/functions/events/event_callback_functions.hpp index a5fa9e8900c..9623a52169b 100644 --- a/src/lua/functions/events/event_callback_functions.hpp +++ b/src/lua/functions/events/event_callback_functions.hpp @@ -18,8 +18,14 @@ * @details This class encapsulates the Lua binding functions related to event callbacks, * allowing for interaction between the C++ codebase and Lua scripts. */ -class EventCallbackFunctions : public LuaScriptInterface { +class EventCallbackFunctions final : public LuaScriptInterface { public: + explicit EventCallbackFunctions(lua_State* L) : + LuaScriptInterface("EventCallbackFunctions") { + init(L); + } + ~EventCallbackFunctions() override = default; + /** * @brief Initializes the Lua state with the event callback functions. * diff --git a/src/lua/functions/events/events_functions.hpp b/src/lua/functions/events/events_functions.hpp index 6830b7c1a73..4a4e3570a12 100644 --- a/src/lua/functions/events/events_functions.hpp +++ b/src/lua/functions/events/events_functions.hpp @@ -20,6 +20,12 @@ class EventFunctions final : LuaScriptInterface { public: + explicit EventFunctions(lua_State* L) : + LuaScriptInterface("EventFunctions") { + init(L); + } + ~EventFunctions() override = default; + static void init(lua_State* L) { ActionFunctions::init(L); CreatureEventFunctions::init(L); @@ -30,6 +36,4 @@ class EventFunctions final : LuaScriptInterface { EventCallbackFunctions::init(L); /* Move, Creature, Talk, Global events goes all here */ } - -private: }; diff --git a/src/lua/functions/events/events_scheduler_functions.hpp b/src/lua/functions/events/events_scheduler_functions.hpp index bedbf16b4a1..9059bf1fdfb 100644 --- a/src/lua/functions/events/events_scheduler_functions.hpp +++ b/src/lua/functions/events/events_scheduler_functions.hpp @@ -13,6 +13,12 @@ class EventsSchedulerFunctions final : private LuaScriptInterface { public: + explicit EventsSchedulerFunctions(lua_State* L) : + LuaScriptInterface("EventsSchedulerFunctions") { + init(L); + } + ~EventsSchedulerFunctions() override = default; + static void init(lua_State* L) { registerTable(L, "EventsScheduler"); diff --git a/src/lua/functions/events/global_event_functions.cpp b/src/lua/functions/events/global_event_functions.cpp index 16227aeb08b..c753e781f25 100644 --- a/src/lua/functions/events/global_event_functions.cpp +++ b/src/lua/functions/events/global_event_functions.cpp @@ -27,8 +27,8 @@ int GlobalEventFunctions::luaGlobalEventType(lua_State* L) { // globalevent:type(callback) const auto &global = getUserdataShared<GlobalEvent>(L, 1); if (global) { - std::string typeName = getString(L, 2); - std::string tmpStr = asLowerCaseString(typeName); + const std::string typeName = getString(L, 2); + const std::string tmpStr = asLowerCaseString(typeName); if (tmpStr == "startup") { global->setEventType(GLOBALEVENT_STARTUP); } else if (tmpStr == "shutdown") { @@ -93,9 +93,9 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { const auto &globalevent = getUserdataShared<GlobalEvent>(L, 1); if (globalevent) { std::string timer = getString(L, 2); - std::vector<int32_t> params = vectorAtoi(explodeString(timer, ":")); + const std::vector<int32_t> params = vectorAtoi(explodeString(timer, ":")); - int32_t hour = params.front(); + const int32_t hour = params.front(); if (hour < 0 || hour > 23) { g_logger().error("[GlobalEventFunctions::luaGlobalEventTime] - " "Invalid hour {} for globalevent with name: {}", @@ -130,7 +130,7 @@ int GlobalEventFunctions::luaGlobalEventTime(lua_State* L) { } } - time_t current_time = time(nullptr); + const time_t current_time = time(nullptr); tm* timeinfo = localtime(¤t_time); timeinfo->tm_hour = hour; timeinfo->tm_min = min; diff --git a/src/lua/functions/events/global_event_functions.hpp b/src/lua/functions/events/global_event_functions.hpp index e04072a24e4..41fc57fdfea 100644 --- a/src/lua/functions/events/global_event_functions.hpp +++ b/src/lua/functions/events/global_event_functions.hpp @@ -13,6 +13,12 @@ class GlobalEventFunctions final : LuaScriptInterface { public: + explicit GlobalEventFunctions(lua_State* L) : + LuaScriptInterface("GlobalEventFunctions") { + init(L); + } + ~GlobalEventFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "GlobalEvent", "", GlobalEventFunctions::luaCreateGlobalEvent); registerMethod(L, "GlobalEvent", "type", GlobalEventFunctions::luaGlobalEventType); diff --git a/src/lua/functions/events/move_event_functions.cpp b/src/lua/functions/events/move_event_functions.cpp index 29d80fc20ce..8392a2f3eca 100644 --- a/src/lua/functions/events/move_event_functions.cpp +++ b/src/lua/functions/events/move_event_functions.cpp @@ -26,7 +26,7 @@ int MoveEventFunctions::luaMoveEventType(lua_State* L) { const auto &moveevent = getUserdataShared<MoveEvent>(L, 1); if (moveevent) { std::string typeName = getString(L, 2); - std::string tmpStr = asLowerCaseString(typeName); + const std::string tmpStr = asLowerCaseString(typeName); if (tmpStr == "stepin") { moveevent->setEventType(MOVE_EVENT_STEP_IN); moveevent->stepFunction = moveevent->StepInField; @@ -219,7 +219,7 @@ int MoveEventFunctions::luaMoveEventItemId(lua_State* L) { // moveevent:id(ids) const auto &moveevent = getUserdataShared<MoveEvent>(L, 1); if (moveevent) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { moveevent->setItemId(getNumber<uint32_t>(L, 2 + i)); @@ -238,7 +238,7 @@ int MoveEventFunctions::luaMoveEventActionId(lua_State* L) { // moveevent:aid(ids) const auto &moveevent = getUserdataShared<MoveEvent>(L, 1); if (moveevent) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { moveevent->setActionId(getNumber<uint32_t>(L, 2 + i)); @@ -257,7 +257,7 @@ int MoveEventFunctions::luaMoveEventUniqueId(lua_State* L) { // moveevent:uid(ids) const auto &moveevent = getUserdataShared<MoveEvent>(L, 1); if (moveevent) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { moveevent->setUniqueId(getNumber<uint32_t>(L, 2 + i)); @@ -276,7 +276,7 @@ int MoveEventFunctions::luaMoveEventPosition(lua_State* L) { // moveevent:position(positions) const auto &moveevent = getUserdataShared<MoveEvent>(L, 1); if (moveevent) { - int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc + const int parameters = lua_gettop(L) - 1; // - 1 because self is a parameter aswell, which we want to skip ofc if (parameters > 1) { for (int i = 0; i < parameters; ++i) { moveevent->setPosition(getPosition(L, 2 + i)); diff --git a/src/lua/functions/events/move_event_functions.hpp b/src/lua/functions/events/move_event_functions.hpp index 6e6412bec73..202006257e6 100644 --- a/src/lua/functions/events/move_event_functions.hpp +++ b/src/lua/functions/events/move_event_functions.hpp @@ -13,6 +13,12 @@ class MoveEventFunctions final : LuaScriptInterface { public: + explicit MoveEventFunctions(lua_State* L) : + LuaScriptInterface("MoveEventFunctions") { + init(L); + } + ~MoveEventFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "MoveEvent", "", MoveEventFunctions::luaCreateMoveEvent); registerMethod(L, "MoveEvent", "type", MoveEventFunctions::luaMoveEventType); diff --git a/src/lua/functions/events/talk_action_functions.cpp b/src/lua/functions/events/talk_action_functions.cpp index 432b948e4ba..1a07c921121 100644 --- a/src/lua/functions/events/talk_action_functions.cpp +++ b/src/lua/functions/events/talk_action_functions.cpp @@ -57,7 +57,7 @@ int TalkActionFunctions::luaTalkActionGroupType(lua_State* L) { } GroupType groupType; - int type = lua_type(L, 2); + const int type = lua_type(L, 2); if (type == LUA_TNUMBER) { groupType = enumFromValue<GroupType>(getNumber<uint8_t>(L, 2)); } else if (type == LUA_TSTRING) { @@ -75,13 +75,13 @@ int TalkActionFunctions::luaTalkActionGroupType(lua_State* L) { } else if (strValue == "god") { groupType = GROUP_TYPE_GOD; } else { - auto string = fmt::format("Invalid group type string value {} for group type for script: {}", strValue, getScriptEnv()->getScriptInterface()->getLoadingScriptName()); + const auto string = fmt::format("Invalid group type string value {} for group type for script: {}", strValue, getScriptEnv()->getScriptInterface()->getLoadingScriptName()); reportErrorFunc(string); pushBoolean(L, false); return 1; } } else { - auto string = fmt::format("Expected number or string value for group type for script: {}", getScriptEnv()->getScriptInterface()->getLoadingScriptName()); + const auto string = fmt::format("Expected number or string value for group type for script: {}", getScriptEnv()->getScriptInterface()->getLoadingScriptName()); reportErrorFunc(string); pushBoolean(L, false); return 1; @@ -107,7 +107,7 @@ int TalkActionFunctions::luaTalkActionRegister(lua_State* L) { } if (talkactionSharedPtr->getGroupType() == GROUP_TYPE_NONE) { - auto string = fmt::format("TalkAction with name {} does't have groupType", talkactionSharedPtr->getWords()); + const auto string = fmt::format("TalkAction with name {} does't have groupType", talkactionSharedPtr->getWords()); reportErrorFunc(string); pushBoolean(L, false); return 1; diff --git a/src/lua/functions/events/talk_action_functions.hpp b/src/lua/functions/events/talk_action_functions.hpp index 384688b4722..487f2046d2f 100644 --- a/src/lua/functions/events/talk_action_functions.hpp +++ b/src/lua/functions/events/talk_action_functions.hpp @@ -13,6 +13,12 @@ class TalkActionFunctions final : LuaScriptInterface { public: + explicit TalkActionFunctions(lua_State* L) : + LuaScriptInterface("TalkActionFunctions") { + init(L); + } + ~TalkActionFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "TalkAction", "", TalkActionFunctions::luaCreateTalkAction); registerMethod(L, "TalkAction", "onSay", TalkActionFunctions::luaTalkActionOnSay); diff --git a/src/lua/functions/items/container_functions.cpp b/src/lua/functions/items/container_functions.cpp index ca17ec48180..e0ed2937fa2 100644 --- a/src/lua/functions/items/container_functions.cpp +++ b/src/lua/functions/items/container_functions.cpp @@ -15,7 +15,7 @@ int ContainerFunctions::luaContainerCreate(lua_State* L) { // Container(uid) - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const auto &container = getScriptEnv()->getContainerByUID(id); if (container) { @@ -69,10 +69,10 @@ int ContainerFunctions::luaContainerGetEmptySlots(lua_State* L) { } uint32_t slots = container->capacity() - container->size(); - bool recursive = getBoolean(L, 2, false); + const bool recursive = getBoolean(L, 2, false); if (recursive) { for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { - if (auto tmpContainer = (*it)->getContainer()) { + if (const auto &tmpContainer = (*it)->getContainer()) { slots += tmpContainer->capacity() - tmpContainer->size(); } } @@ -100,7 +100,7 @@ int ContainerFunctions::luaContainerGetItem(lua_State* L) { return 1; } - uint32_t index = getNumber<uint32_t>(L, 2); + const uint32_t index = getNumber<uint32_t>(L, 2); const auto &item = container->getItemByIndex(index); if (item) { pushUserdata<Item>(L, item); @@ -157,10 +157,10 @@ int ContainerFunctions::luaContainerAddItem(lua_State* L) { return 1; } - auto index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER); - auto flags = getNumber<uint32_t>(L, 5, 0); + const auto index = getNumber<int32_t>(L, 4, INDEX_WHEREEVER); + const auto flags = getNumber<uint32_t>(L, 5, 0); - ReturnValue ret = g_game().internalAddItem(container, item, index, flags); + const ReturnValue ret = g_game().internalAddItem(container, item, index, flags); if (ret == RETURNVALUE_NOERROR) { pushUserdata<Item>(L, item); setItemMetatable(L, -1, item); @@ -191,8 +191,8 @@ int ContainerFunctions::luaContainerAddItemEx(lua_State* L) { return 1; } - auto index = getNumber<int32_t>(L, 3, INDEX_WHEREEVER); - auto flags = getNumber<uint32_t>(L, 4, 0); + const auto index = getNumber<int32_t>(L, 3, INDEX_WHEREEVER); + const auto flags = getNumber<uint32_t>(L, 4, 0); ReturnValue ret = g_game().internalAddItem(container, item, index, flags); if (ret == RETURNVALUE_NOERROR) { ScriptEnvironment::removeTempItem(item); @@ -231,7 +231,7 @@ int ContainerFunctions::luaContainerGetItemCountById(lua_State* L) { } } - auto subType = getNumber<int32_t>(L, 3, -1); + const auto subType = getNumber<int32_t>(L, 3, -1); lua_pushnumber(L, container->getItemTypeCount(itemId, subType)); return 1; } @@ -255,8 +255,8 @@ int ContainerFunctions::luaContainerGetItems(lua_State* L) { return 1; } - bool recursive = getBoolean(L, 2, false); - std::vector<std::shared_ptr<Item>> items = container->getItems(recursive); + const bool recursive = getBoolean(L, 2, false); + const std::vector<std::shared_ptr<Item>> items = container->getItems(recursive); lua_createtable(L, static_cast<int>(items.size()), 0); @@ -278,7 +278,7 @@ int ContainerFunctions::luaContainerRegisterReward(lua_State* L) { return 1; } - int64_t rewardId = getTimeMsNow(); + const int64_t rewardId = getTimeMsNow(); const auto &rewardContainer = Item::CreateItem(ITEM_REWARD_CONTAINER); rewardContainer->setAttribute(ItemAttribute_t::DATE, rewardId); container->setAttribute(ItemAttribute_t::DATE, rewardId); diff --git a/src/lua/functions/items/container_functions.hpp b/src/lua/functions/items/container_functions.hpp index 568018b45fd..52bb33e6b52 100644 --- a/src/lua/functions/items/container_functions.hpp +++ b/src/lua/functions/items/container_functions.hpp @@ -12,8 +12,13 @@ #include "lua/scripts/luascript.hpp" class ContainerFunctions final : LuaScriptInterface { -public: private: + explicit ContainerFunctions(lua_State* L) : + LuaScriptInterface("ContainerFunctions") { + init(L); + } + ~ContainerFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Container", "Item", ContainerFunctions::luaContainerCreate); registerMetaMethod(L, "Container", "__eq", ContainerFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/imbuement_functions.cpp b/src/lua/functions/items/imbuement_functions.cpp index f0db5fcd411..074ef15b0f0 100644 --- a/src/lua/functions/items/imbuement_functions.cpp +++ b/src/lua/functions/items/imbuement_functions.cpp @@ -15,7 +15,7 @@ int ImbuementFunctions::luaCreateImbuement(lua_State* L) { // Imbuement(id) - uint16_t imbuementId = getNumber<uint16_t>(L, 2); + const uint16_t imbuementId = getNumber<uint16_t>(L, 2); Imbuement* imbuement = g_imbuements().getImbuement(imbuementId); if (imbuement) { @@ -29,7 +29,7 @@ int ImbuementFunctions::luaCreateImbuement(lua_State* L) { int ImbuementFunctions::luaImbuementGetName(lua_State* L) { // imbuement:getName() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (imbuement) { pushString(L, imbuement->getName()); } else { @@ -40,7 +40,7 @@ int ImbuementFunctions::luaImbuementGetName(lua_State* L) { int ImbuementFunctions::luaImbuementGetId(lua_State* L) { // imbuement:getId() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->getID()); } else { @@ -51,7 +51,7 @@ int ImbuementFunctions::luaImbuementGetId(lua_State* L) { int ImbuementFunctions::luaImbuementGetItems(lua_State* L) { // imbuement:getItems() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -72,7 +72,7 @@ int ImbuementFunctions::luaImbuementGetItems(lua_State* L) { int ImbuementFunctions::luaImbuementGetBase(lua_State* L) { // imbuement:getBase() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -97,12 +97,12 @@ int ImbuementFunctions::luaImbuementGetBase(lua_State* L) { int ImbuementFunctions::luaImbuementGetCategory(lua_State* L) { // imbuement:getCategory() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (!imbuement) { lua_pushnil(L); return 1; } - uint16_t categoryId = imbuement->getCategory(); + const uint16_t categoryId = imbuement->getCategory(); const CategoryImbuement* categoryImbuement = g_imbuements().getCategoryByID(categoryId); if (categoryImbuement) { @@ -118,7 +118,7 @@ int ImbuementFunctions::luaImbuementGetCategory(lua_State* L) { int ImbuementFunctions::luaImbuementIsPremium(lua_State* L) { // imbuement:isPremium() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (!imbuement) { lua_pushnil(L); return 1; @@ -130,7 +130,7 @@ int ImbuementFunctions::luaImbuementIsPremium(lua_State* L) { int ImbuementFunctions::luaImbuementGetElementDamage(lua_State* L) { // imbuement:getElementDamage() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->elementDamage); } else { @@ -141,7 +141,7 @@ int ImbuementFunctions::luaImbuementGetElementDamage(lua_State* L) { int ImbuementFunctions::luaImbuementGetCombatType(lua_State* L) { // imbuement:getCombatType() - auto* imbuement = getUserdata<Imbuement>(L, 1); + const auto* imbuement = getUserdata<Imbuement>(L, 1); if (imbuement) { lua_pushnumber(L, imbuement->combatType); } else { diff --git a/src/lua/functions/items/imbuement_functions.hpp b/src/lua/functions/items/imbuement_functions.hpp index 516fe91a3b1..f86882b1cd2 100644 --- a/src/lua/functions/items/imbuement_functions.hpp +++ b/src/lua/functions/items/imbuement_functions.hpp @@ -13,6 +13,12 @@ class ImbuementFunctions final : LuaScriptInterface { public: + explicit ImbuementFunctions(lua_State* L) : + LuaScriptInterface("ImbuementFunctions") { + init(L); + } + ~ImbuementFunctions() override = default; + static void init(lua_State* L) { registerClass(L, "Imbuement", "", ImbuementFunctions::luaCreateImbuement); registerMetaMethod(L, "Imbuement", "__eq", ImbuementFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/item_classification_functions.hpp b/src/lua/functions/items/item_classification_functions.hpp index ebbd9fddd47..29b04268282 100644 --- a/src/lua/functions/items/item_classification_functions.hpp +++ b/src/lua/functions/items/item_classification_functions.hpp @@ -13,6 +13,12 @@ class ItemClassificationFunctions final : LuaScriptInterface { public: + explicit ItemClassificationFunctions(lua_State* L) : + LuaScriptInterface("ItemClassificationFunctions") { + init(L); + } + ~ItemClassificationFunctions() override = default; + static void init(lua_State* L) { registerClass(L, "ItemClassification", "", ItemClassificationFunctions::luaItemClassificationCreate); registerMetaMethod(L, "ItemClassification", "__eq", ItemClassificationFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/item_functions.cpp b/src/lua/functions/items/item_functions.cpp index 7a4bed600de..e8a2cedd9f7 100644 --- a/src/lua/functions/items/item_functions.cpp +++ b/src/lua/functions/items/item_functions.cpp @@ -21,7 +21,7 @@ class Imbuement; // Item int ItemFunctions::luaItemCreate(lua_State* L) { // Item(uid) - uint32_t id = getNumber<uint32_t>(L, 2); + const uint32_t id = getNumber<uint32_t>(L, 2); const auto &item = getScriptEnv()->getItemByUID(id); if (item) { @@ -122,8 +122,8 @@ int ItemFunctions::luaItemSplit(lua_State* L) { return 1; } - uint16_t count = std::min<uint16_t>(getNumber<uint16_t>(L, 2, 1), item->getItemCount()); - uint16_t diff = item->getItemCount() - count; + const uint16_t count = std::min<uint16_t>(getNumber<uint16_t>(L, 2, 1), item->getItemCount()); + const uint16_t diff = item->getItemCount() - count; const auto &splitItem = item->clone(); if (!splitItem) { @@ -134,7 +134,7 @@ int ItemFunctions::luaItemSplit(lua_State* L) { splitItem->setItemCount(count); ScriptEnvironment* env = getScriptEnv(); - uint32_t uid = env->addThing(item); + const uint32_t uid = env->addThing(item); const auto &newItem = g_game().transformItem(item, item->getID(), diff); if (item->isRemoved()) { @@ -159,7 +159,7 @@ int ItemFunctions::luaItemRemove(lua_State* L) { // item:remove([count = -1]) const auto &item = getUserdataShared<Item>(L, 1); if (item) { - auto count = getNumber<int32_t>(L, 2, -1); + const auto count = getNumber<int32_t>(L, 2, -1); pushBoolean(L, g_game().internalRemoveItem(item, count) == RETURNVALUE_NOERROR); } else { lua_pushnil(L); @@ -186,7 +186,7 @@ int ItemFunctions::luaItemGetActionId(lua_State* L) { // item:getActionId() const auto &item = getUserdataShared<Item>(L, 1); if (item) { - auto actionId = item->getAttribute<uint16_t>(ItemAttribute_t::ACTIONID); + const auto actionId = item->getAttribute<uint16_t>(ItemAttribute_t::ACTIONID); lua_pushnumber(L, actionId); } else { lua_pushnil(L); @@ -196,7 +196,7 @@ int ItemFunctions::luaItemGetActionId(lua_State* L) { int ItemFunctions::luaItemSetActionId(lua_State* L) { // item:setActionId(actionId) - uint16_t actionId = getNumber<uint16_t>(L, 2); + const uint16_t actionId = getNumber<uint16_t>(L, 2); const auto &item = getUserdataShared<Item>(L, 1); if (item) { item->setAttribute(ItemAttribute_t::ACTIONID, actionId); @@ -397,7 +397,7 @@ int ItemFunctions::luaItemSetAttribute(lua_State* L) { if (item->isAttributeInteger(attribute)) { switch (attribute) { case ItemAttribute_t::DECAYSTATE: { - if (ItemDecayState_t decayState = getNumber<ItemDecayState_t>(L, 3); + if (const auto decayState = getNumber<ItemDecayState_t>(L, 3); decayState == DECAYING_FALSE || decayState == DECAYING_STOPPING) { g_decay().stopDecay(item); } else { @@ -426,7 +426,7 @@ int ItemFunctions::luaItemSetAttribute(lua_State* L) { item->updateTileFlags(); pushBoolean(L, true); } else if (item->isAttributeString(attribute)) { - auto newAttributeString = getString(L, 3); + const auto newAttributeString = getString(L, 3); item->setAttribute(attribute, newAttributeString); item->updateTileFlags(); pushBoolean(L, true); @@ -517,7 +517,7 @@ int ItemFunctions::luaItemSetCustomAttribute(lua_State* L) { if (std::floor(doubleValue) < doubleValue) { item->setCustomAttribute(key, doubleValue); } else { - int64_t int64 = getNumber<int64_t>(L, 3); + const int64_t int64 = getNumber<int64_t>(L, 3); item->setCustomAttribute(key, int64); } } else if (isString(L, 3)) { @@ -626,13 +626,13 @@ int ItemFunctions::luaItemMoveTo(lua_State* L) { return 1; } - auto flags = getNumber<uint32_t>(L, 3, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVABLE); + const auto flags = getNumber<uint32_t>(L, 3, FLAG_NOLIMIT | FLAG_IGNOREBLOCKITEM | FLAG_IGNOREBLOCKCREATURE | FLAG_IGNORENOTMOVABLE); if (item->getParent() == VirtualCylinder::virtualCylinder) { pushBoolean(L, g_game().internalAddItem(toCylinder, item, INDEX_WHEREEVER, flags) == RETURNVALUE_NOERROR); } else { std::shared_ptr<Item> moveItem = nullptr; - ReturnValue ret = g_game().internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, flags); + const ReturnValue ret = g_game().internalMoveItem(item->getParent(), toCylinder, INDEX_WHEREEVER, item, item->getItemCount(), &moveItem, flags); if (moveItem) { *itemPtr = moveItem; } @@ -678,7 +678,7 @@ int ItemFunctions::luaItemTransform(lua_State* L) { } ScriptEnvironment* env = getScriptEnv(); - uint32_t uid = env->addThing(item); + const uint32_t uid = env->addThing(item); const auto &newItem = g_game().transformItem(item, itemId, subType); if (item->isRemoved()) { @@ -713,7 +713,7 @@ int ItemFunctions::luaItemDecay(lua_State* L) { int ItemFunctions::luaItemMoveToSlot(lua_State* L) { // item:moveToSlot(player, slot) - auto item = getUserdataShared<Item>(L, 1); + const auto &item = getUserdataShared<Item>(L, 1); if (!item || item->isRemoved()) { lua_pushnil(L); return 1; @@ -725,13 +725,9 @@ int ItemFunctions::luaItemMoveToSlot(lua_State* L) { return 1; } - auto slot = getNumber<Slots_t>(L, 3, CONST_SLOT_WHEREEVER); + const auto slot = getNumber<Slots_t>(L, 3, CONST_SLOT_WHEREEVER); - std::shared_ptr<Item> moveItem = nullptr; - ReturnValue ret = g_game().internalMoveItem(item->getParent(), player, slot, item, item->getItemCount(), nullptr); - if (moveItem) { - item = moveItem; - } + const ReturnValue ret = g_game().internalMoveItem(item->getParent(), player, slot, item, item->getItemCount(), nullptr); pushBoolean(L, ret == RETURNVALUE_NOERROR); return 1; @@ -741,7 +737,7 @@ int ItemFunctions::luaItemGetDescription(lua_State* L) { // item:getDescription(distance) const auto &item = getUserdataShared<Item>(L, 1); if (item) { - int32_t distance = getNumber<int32_t>(L, 2); + const int32_t distance = getNumber<int32_t>(L, 2); pushString(L, item->getDescription(distance)); } else { lua_pushnil(L); @@ -753,7 +749,7 @@ int ItemFunctions::luaItemHasProperty(lua_State* L) { // item:hasProperty(property) const auto &item = getUserdataShared<Item>(L, 1); if (item) { - ItemProperty property = getNumber<ItemProperty>(L, 2); + const ItemProperty property = getNumber<ItemProperty>(L, 2); pushBoolean(L, item->hasProperty(property)); } else { lua_pushnil(L); @@ -815,7 +811,7 @@ int ItemFunctions::luaItemSetDuration(lua_State* L) { return 1; } - uint32_t minDuration = getNumber<uint32_t>(L, 2); + const uint32_t minDuration = getNumber<uint32_t>(L, 2); uint32_t maxDuration = 0; if (lua_gettop(L) > 2) { maxDuration = uniform_random(minDuration, getNumber<uint32_t>(L, 3)); @@ -858,7 +854,7 @@ int ItemFunctions::luaItemIsInsideDepot(lua_State* L) { int ItemFunctions::luaItemIsContainer(lua_State* L) { // item:isContainer() - const auto item = getUserdataShared<const Item>(L, 1); + const auto &item = getUserdataShared<const Item>(L, 1); if (!item) { reportErrorFunc(getErrorDesc(LUA_ERROR_ITEM_NOT_FOUND)); pushBoolean(L, false); @@ -942,7 +938,7 @@ int ItemFunctions::luaItemSetOwner(lua_State* L) { return 1; } - auto creatureId = getNumber<uint32_t>(L, 2); + const auto creatureId = getNumber<uint32_t>(L, 2); if (creatureId != 0) { item->setOwner(creatureId); pushBoolean(L, true); @@ -961,7 +957,7 @@ int ItemFunctions::luaItemGetOwnerId(lua_State* L) { return 0; } - if (auto ownerId = item->getOwnerId()) { + if (const auto ownerId = item->getOwnerId()) { lua_pushnumber(L, ownerId); return 1; } @@ -988,7 +984,7 @@ int ItemFunctions::luaItemIsOwner(lua_State* L) { return 1; } - auto creatureId = getNumber<uint32_t>(L, 2); + const auto creatureId = getNumber<uint32_t>(L, 2); if (creatureId != 0) { pushBoolean(L, item->isOwner(creatureId)); return 1; @@ -1006,7 +1002,7 @@ int ItemFunctions::luaItemGetOwnerName(lua_State* L) { return 0; } - if (auto ownerName = item->getOwnerName(); !ownerName.empty()) { + if (const auto ownerName = item->getOwnerName(); !ownerName.empty()) { pushString(L, ownerName); return 1; } diff --git a/src/lua/functions/items/item_functions.hpp b/src/lua/functions/items/item_functions.hpp index 44e111479a3..bbb21ae96fb 100644 --- a/src/lua/functions/items/item_functions.hpp +++ b/src/lua/functions/items/item_functions.hpp @@ -17,6 +17,12 @@ class ItemFunctions final : LuaScriptInterface { public: + explicit ItemFunctions(lua_State* L) : + LuaScriptInterface("ItemFunctions") { + init(L); + } + ~ItemFunctions() override = default; + static void init(lua_State* L) { registerSharedClass(L, "Item", "", ItemFunctions::luaItemCreate); registerMetaMethod(L, "Item", "__eq", ItemFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/item_type_functions.cpp b/src/lua/functions/items/item_type_functions.cpp index cdb80012cc9..d24cf97aef8 100644 --- a/src/lua/functions/items/item_type_functions.cpp +++ b/src/lua/functions/items/item_type_functions.cpp @@ -272,10 +272,10 @@ int ItemTypeFunctions::luaItemTypeGetArticle(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetDescription(lua_State* L) { // itemType:getDescription([count]) - auto itemType = getUserdata<ItemType>(L, 1); + const auto &itemType = getUserdata<ItemType>(L, 1); if (itemType) { - auto count = getNumber<uint16_t>(L, 2, -1); - auto description = Item::getDescription(*itemType, 1, nullptr, count); + const auto count = getNumber<uint16_t>(L, 2, -1); + const auto description = Item::getDescription(*itemType, 1, nullptr, count); pushString(L, description); } else { lua_pushnil(L); @@ -329,7 +329,7 @@ int ItemTypeFunctions::luaItemTypeGetCapacity(lua_State* L) { int ItemTypeFunctions::luaItemTypeGetWeight(lua_State* L) { // itemType:getWeight([count = 1]) - auto count = getNumber<uint16_t>(L, 2, 1); + const auto count = getNumber<uint16_t>(L, 2, 1); const auto* itemType = getUserdata<const ItemType>(L, 1); if (!itemType) { @@ -337,7 +337,7 @@ int ItemTypeFunctions::luaItemTypeGetWeight(lua_State* L) { return 1; } - uint64_t weight = static_cast<uint64_t>(itemType->weight) * std::max<int32_t>(1, count); + const uint64_t weight = static_cast<uint64_t>(itemType->weight) * std::max<int32_t>(1, count); lua_pushnumber(L, weight); return 1; } @@ -350,7 +350,7 @@ int ItemTypeFunctions::luaItemTypeGetStackSize(lua_State* L) { return 1; } - auto stackSize = static_cast<uint64_t>(itemType->stackSize); + const auto stackSize = static_cast<uint64_t>(itemType->stackSize); lua_pushnumber(L, stackSize); return 1; } diff --git a/src/lua/functions/items/item_type_functions.hpp b/src/lua/functions/items/item_type_functions.hpp index ce53d429804..254831fba56 100644 --- a/src/lua/functions/items/item_type_functions.hpp +++ b/src/lua/functions/items/item_type_functions.hpp @@ -14,6 +14,12 @@ class ItemTypeFunctions final : LuaScriptInterface { public: + explicit ItemTypeFunctions(lua_State* L) : + LuaScriptInterface("ItemTypeFunctions") { + init(L); + } + ~ItemTypeFunctions() override = default; + static void init(lua_State* L) { registerClass(L, "ItemType", "", ItemTypeFunctions::luaItemTypeCreate); registerMetaMethod(L, "ItemType", "__eq", ItemTypeFunctions::luaUserdataCompare); diff --git a/src/lua/functions/items/weapon_functions.cpp b/src/lua/functions/items/weapon_functions.cpp index 21cd0332735..a0471c8c8f2 100644 --- a/src/lua/functions/items/weapon_functions.cpp +++ b/src/lua/functions/items/weapon_functions.cpp @@ -18,12 +18,12 @@ int WeaponFunctions::luaCreateWeapon(lua_State* L) { // Weapon(type) - WeaponType_t type = getNumber<WeaponType_t>(L, 2); + const WeaponType_t type = getNumber<WeaponType_t>(L, 2); switch (type) { case WEAPON_SWORD: case WEAPON_AXE: case WEAPON_CLUB: { - if (auto weaponPtr = g_luaEnvironment().createWeaponObject<WeaponMelee>(getScriptEnv()->getScriptInterface())) { + if (const auto &weaponPtr = g_luaEnvironment().createWeaponObject<WeaponMelee>(getScriptEnv()->getScriptInterface())) { pushUserdata<WeaponMelee>(L, weaponPtr); setMetatable(L, -1, "Weapon"); weaponPtr->weaponType = type; @@ -35,7 +35,7 @@ int WeaponFunctions::luaCreateWeapon(lua_State* L) { case WEAPON_MISSILE: case WEAPON_DISTANCE: case WEAPON_AMMO: { - if (auto weaponPtr = g_luaEnvironment().createWeaponObject<WeaponDistance>(getScriptEnv()->getScriptInterface())) { + if (const auto &weaponPtr = g_luaEnvironment().createWeaponObject<WeaponDistance>(getScriptEnv()->getScriptInterface())) { pushUserdata<WeaponDistance>(L, weaponPtr); setMetatable(L, -1, "Weapon"); weaponPtr->weaponType = type; @@ -45,7 +45,7 @@ int WeaponFunctions::luaCreateWeapon(lua_State* L) { break; } case WEAPON_WAND: { - if (auto weaponPtr = g_luaEnvironment().createWeaponObject<WeaponWand>(getScriptEnv()->getScriptInterface())) { + if (const auto &weaponPtr = g_luaEnvironment().createWeaponObject<WeaponWand>(getScriptEnv()->getScriptInterface())) { pushUserdata<WeaponWand>(L, weaponPtr); setMetatable(L, -1, "Weapon"); weaponPtr->weaponType = type; @@ -67,7 +67,7 @@ int WeaponFunctions::luaWeaponAction(lua_State* L) { const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { std::string typeName = getString(L, 2); - std::string tmpStr = asLowerCaseString(typeName); + const std::string tmpStr = asLowerCaseString(typeName); if (tmpStr == "removecount") { weapon->action = WEAPONACTION_REMOVECOUNT; } else if (tmpStr == "removecharge") { @@ -89,7 +89,7 @@ int WeaponFunctions::luaWeaponAction(lua_State* L) { int WeaponFunctions::luaWeaponRegister(lua_State* L) { // weapon:register() - WeaponShared_ptr* weaponPtr = getRawUserDataShared<Weapon>(L, 1); + const WeaponShared_ptr* weaponPtr = getRawUserDataShared<Weapon>(L, 1); if (weaponPtr && *weaponPtr) { WeaponShared_ptr weapon = *weaponPtr; if (weapon->weaponType == WEAPON_DISTANCE || weapon->weaponType == WEAPON_AMMO || weapon->weaponType == WEAPON_MISSILE) { @@ -100,7 +100,7 @@ int WeaponFunctions::luaWeaponRegister(lua_State* L) { weapon = getUserdataShared<WeaponMelee>(L, 1); } - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.weaponType = weapon->weaponType; @@ -269,7 +269,7 @@ int WeaponFunctions::luaWeaponElement(lua_State* L) { if (weapon) { if (!getNumber<CombatType_t>(L, 2)) { std::string element = getString(L, 2); - std::string tmpStrValue = asLowerCaseString(element); + const std::string tmpStrValue = asLowerCaseString(element); if (tmpStrValue == "earth") { weapon->params.combatType = COMBAT_EARTHDAMAGE; } else if (tmpStrValue == "ice") { @@ -365,7 +365,7 @@ int WeaponFunctions::luaWeaponAttack(lua_State* L) { // weapon:attack(atk) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.attack = getNumber<int32_t>(L, 2); pushBoolean(L, true); @@ -379,7 +379,7 @@ int WeaponFunctions::luaWeaponDefense(lua_State* L) { // weapon:defense(defense[, extraDefense]) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.defense = getNumber<int32_t>(L, 2); if (lua_gettop(L) > 2) { @@ -396,7 +396,7 @@ int WeaponFunctions::luaWeaponRange(lua_State* L) { // weapon:range(range) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.shootRange = getNumber<uint8_t>(L, 2); pushBoolean(L, true); @@ -414,7 +414,7 @@ int WeaponFunctions::luaWeaponCharges(lua_State* L) { if (lua_gettop(L) > 2) { showCharges = getBoolean(L, 3); } - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.charges = getNumber<uint8_t>(L, 2); it.showCharges = showCharges; @@ -433,7 +433,7 @@ int WeaponFunctions::luaWeaponDuration(lua_State* L) { if (lua_gettop(L) > 2) { showDuration = getBoolean(L, 3); } - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.decayTime = getNumber<uint8_t>(L, 2); it.showDuration = showDuration; @@ -452,7 +452,7 @@ int WeaponFunctions::luaWeaponDecayTo(lua_State* L) { if (lua_gettop(L) > 1) { itemid = getNumber<uint16_t>(L, 2); } - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.decayTo = itemid; pushBoolean(L, true); @@ -466,7 +466,7 @@ int WeaponFunctions::luaWeaponTransformEquipTo(lua_State* L) { // weapon:transformEquipTo(itemid) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.transformEquipTo = getNumber<uint16_t>(L, 2); pushBoolean(L, true); @@ -480,7 +480,7 @@ int WeaponFunctions::luaWeaponTransformDeEquipTo(lua_State* L) { // weapon:transformDeEquipTo(itemid) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.transformDeEquipTo = getNumber<uint16_t>(L, 2); pushBoolean(L, true); @@ -494,7 +494,7 @@ int WeaponFunctions::luaWeaponShootType(lua_State* L) { // weapon:shootType(type) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.shootType = getNumber<ShootType_t>(L, 2); pushBoolean(L, true); @@ -508,9 +508,9 @@ int WeaponFunctions::luaWeaponSlotType(lua_State* L) { // weapon:slotType(slot) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); - std::string slot = getString(L, 2); + const std::string slot = getString(L, 2); if (slot == "two-handed") { it.slotPosition = SLOTP_TWO_HAND; @@ -528,7 +528,7 @@ int WeaponFunctions::luaWeaponAmmoType(lua_State* L) { // weapon:ammoType(type) const auto &weapon = getUserdataShared<WeaponDistance>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); std::string type = getString(L, 2); @@ -554,7 +554,7 @@ int WeaponFunctions::luaWeaponHitChance(lua_State* L) { // weapon:hitChance(chance) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.hitChance = getNumber<int8_t>(L, 2); pushBoolean(L, true); @@ -568,7 +568,7 @@ int WeaponFunctions::luaWeaponMaxHitChance(lua_State* L) { // weapon:maxHitChance(max) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); + const uint16_t id = weapon->getID(); ItemType &it = Item::items.getItemType(id); it.maxHitChance = getNumber<int32_t>(L, 2); pushBoolean(L, true); @@ -582,13 +582,13 @@ int WeaponFunctions::luaWeaponExtraElement(lua_State* L) { // weapon:extraElement(atk, combatType) const WeaponShared_ptr &weapon = getUserdataShared<Weapon>(L, 1); if (weapon) { - uint16_t id = weapon->getID(); - ItemType &it = Item::items.getItemType(id); + const uint16_t id = weapon->getID(); + const ItemType &it = Item::items.getItemType(id); it.abilities->elementDamage = getNumber<uint16_t>(L, 2); if (!getNumber<CombatType_t>(L, 3)) { std::string element = getString(L, 3); - std::string tmpStrValue = asLowerCaseString(element); + const std::string tmpStrValue = asLowerCaseString(element); if (tmpStrValue == "earth") { it.abilities->elementType = COMBAT_EARTHDAMAGE; } else if (tmpStrValue == "ice") { From 7e58677c349d4a564d3d6e27022a6057375bb0e5 Mon Sep 17 00:00:00 2001 From: Beats <daniel15042014@hotmail.com> Date: Mon, 16 Sep 2024 22:30:49 -0400 Subject: [PATCH 33/34] up --- src/items/containers/container.cpp | 132 ++++++++-------- src/items/containers/container.hpp | 12 +- src/items/containers/depot/depotchest.cpp | 14 +- src/items/containers/depot/depotlocker.cpp | 6 +- src/items/containers/inbox/inbox.cpp | 10 +- src/items/containers/mailbox/mailbox.cpp | 8 +- src/items/containers/mailbox/mailbox.hpp | 2 +- src/items/containers/rewards/reward.cpp | 8 +- src/items/containers/rewards/reward.hpp | 16 +- src/items/containers/rewards/rewardchest.cpp | 10 +- src/items/containers/rewards/rewardchest.hpp | 12 +- src/items/decay/decay.cpp | 20 +-- src/items/functions/item/attribute.cpp | 14 +- src/items/functions/item/item_parse.cpp | 58 +++---- src/items/weapons/weapons.cpp | 154 +++++++++---------- src/items/weapons/weapons.hpp | 20 +-- 16 files changed, 249 insertions(+), 247 deletions(-) diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index a120310dd6c..958c0fbfb57 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -47,9 +47,9 @@ std::shared_ptr<Container> Container::create(uint16_t type, uint16_t size, bool std::shared_ptr<Container> Container::create(const std::shared_ptr<Tile> &tile) { auto container = std::make_shared<Container>(ITEM_BROWSEFIELD, 30, false, true); - TileItemVector* itemVector = tile->getItemList(); + const TileItemVector* itemVector = tile->getItemList(); if (itemVector) { - for (auto &item : *itemVector) { + for (const auto &item : *itemVector) { if (((item->getContainer() || item->hasProperty(CONST_PROP_MOVABLE)) || (item->isWrapable() && !item->hasProperty(CONST_PROP_MOVABLE) && !item->hasProperty(CONST_PROP_BLOCKPATH))) && !item->hasAttribute(ItemAttribute_t::UNIQUEID)) { container->itemlist.push_front(item); item->setParent(container); @@ -74,7 +74,7 @@ Container::~Container() { } std::shared_ptr<Item> Container::clone() const { - std::shared_ptr<Container> clone = std::static_pointer_cast<Container>(Item::clone()); + const std::shared_ptr<Container> &clone = std::static_pointer_cast<Container>(Item::clone()); for (const std::shared_ptr<Item> &item : itemlist) { clone->addItem(item->clone()); } @@ -83,7 +83,7 @@ std::shared_ptr<Item> Container::clone() const { } std::shared_ptr<Container> Container::getParentContainer() { - std::shared_ptr<Thing> thing = getParent(); + const std::shared_ptr<Thing> &thing = getParent(); if (!thing) { return nullptr; } @@ -114,12 +114,12 @@ std::shared_ptr<Container> Container::getRootContainer() { } bool Container::hasParent() { - auto parent = getParent(); + const auto &parent = getParent(); if (!parent) { return false; } - auto creature = parent->getCreature(); - bool isPlayer = creature && creature->getPlayer() != nullptr; + const auto &creature = parent->getCreature(); + const bool &isPlayer = creature && creature->getPlayer() != nullptr; return getID() != ITEM_BROWSEFIELD && !isPlayer; } @@ -132,9 +132,9 @@ StashContainerList Container::getStowableItems() const { StashContainerList toReturnList; for (const auto &item : itemlist) { if (item->getContainer() != nullptr) { - auto subContainer = item->getContainer()->getStowableItems(); + const auto &subContainer = item->getContainer()->getStowableItems(); for (const auto &key : subContainer | std::views::keys) { - std::shared_ptr<Item> containerItem = key; + const auto &containerItem = key; toReturnList.emplace_back(containerItem, static_cast<uint32_t>(containerItem->getItemCount())); } } else if (item->isItemStorable()) { @@ -156,12 +156,12 @@ Attr_ReadValue Container::readAttr(AttrTypes_t attr, PropStream &propStream) { } bool Container::unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, PropStream &propStream, Position &itemPosition) { - bool ret = Item::unserializeItemNode(loader, node, propStream, itemPosition); + const bool ret = Item::unserializeItemNode(loader, node, propStream, itemPosition); if (!ret) { return false; } - for (auto &itemNode : node.children) { + for (const auto &itemNode : node.children) { // load container items if (itemNode.type != OTBM_ITEM) { // unknown type @@ -178,7 +178,7 @@ bool Container::unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, return false; } - const auto item = Item::CreateItem(id, itemPosition); + const auto &item = Item::CreateItem(id, itemPosition); if (!item) { continue; } @@ -193,7 +193,7 @@ bool Container::unserializeItemNode(OTB::Loader &loader, const OTB::Node &node, return true; } -bool Container::countsToLootAnalyzerBalance() { +bool Container::countsToLootAnalyzerBalance() const { if (isCorpse()) { return true; } @@ -227,7 +227,7 @@ std::ostringstream &Container::getContentDescription(std::ostringstream &os, boo for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { const auto item = *it; - std::shared_ptr<Container> container = item->getContainer(); + const auto &container = item->getContainer(); if (container && !container->empty()) { continue; } @@ -260,7 +260,7 @@ bool Container::isStoreInbox() const { } bool Container::isStoreInboxFiltered() const { - auto attribute = getAttribute<std::string>(ItemAttribute_t::STORE_INBOX_CATEGORY); + const auto attribute = getAttribute<std::string>(ItemAttribute_t::STORE_INBOX_CATEGORY); if (isStoreInbox() && !attribute.empty() && attribute != "All") { return true; } @@ -274,8 +274,8 @@ std::deque<std::shared_ptr<Item>> Container::getStoreInboxFilteredItems() const if (isStoreInboxFiltered()) { for (const std::shared_ptr<Item> &item : getItemList()) { auto itemId = item->getID(); - auto attribute = item->getCustomAttribute("unWrapId"); - uint16_t unWrapId = attribute ? static_cast<uint16_t>(attribute->getInteger()) : 0; + const auto attribute = item->getCustomAttribute("unWrapId"); + const uint16_t unWrapId = attribute ? static_cast<uint16_t>(attribute->getInteger()) : 0; if (unWrapId != 0) { itemId = unWrapId; } @@ -296,8 +296,8 @@ std::vector<ContainerCategory_t> Container::getStoreInboxValidCategories() const stdext::vector_set<ContainerCategory_t> validCategories; for (const auto &item : itemlist) { auto itemId = item->getID(); - auto attribute = item->getCustomAttribute("unWrapId"); - uint16_t unWrapId = attribute ? static_cast<uint16_t>(attribute->getInteger()) : 0; + const auto attribute = item->getCustomAttribute("unWrapId"); + const uint16_t unWrapId = attribute ? static_cast<uint16_t>(attribute->getInteger()) : 0; if (unWrapId != 0) { itemId = unWrapId; } @@ -315,14 +315,14 @@ std::vector<ContainerCategory_t> Container::getStoreInboxValidCategories() const } std::shared_ptr<Item> Container::getFilteredItemByIndex(size_t index) const { - const auto filteredItems = getStoreInboxFilteredItems(); + const auto &filteredItems = getStoreInboxFilteredItems(); if (index >= filteredItems.size()) { return nullptr; } const auto &item = filteredItems[index]; - auto it = std::find(itemlist.begin(), itemlist.end(), item); + const auto it = std::ranges::find(itemlist, item); if (it == itemlist.end()) { return nullptr; } @@ -367,7 +367,7 @@ bool Container::isHoldingItem(const std::shared_ptr<Item> &item) { bool Container::isHoldingItemWithId(const uint16_t id) { for (ContainerIterator it = iterator(); it.hasNext(); it.advance()) { - const auto item = *it; + const auto &item = *it; if (item->getID() == id) { return true; } @@ -399,7 +399,7 @@ bool Container::isBrowseFieldAndHoldsRewardChest() { } void Container::onAddContainerItem(const std::shared_ptr<Item> &item) { - auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); + const auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); // send to client for (const auto &spectator : spectators) { @@ -413,7 +413,7 @@ void Container::onAddContainerItem(const std::shared_ptr<Item> &item) { } void Container::onUpdateContainerItem(uint32_t index, const std::shared_ptr<Item> &oldItem, const std::shared_ptr<Item> &newItem) { - auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); + const auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); // send to client for (const auto &spectator : spectators) { @@ -427,7 +427,7 @@ void Container::onUpdateContainerItem(uint32_t index, const std::shared_ptr<Item } void Container::onRemoveContainerItem(uint32_t index, const std::shared_ptr<Item> &item) { - auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); + const auto spectators = Spectators().find<Player>(getPosition(), false, 2, 2, 2, 2); // send change to client for (const auto &spectator : spectators) { @@ -441,7 +441,7 @@ void Container::onRemoveContainerItem(uint32_t index, const std::shared_ptr<Item } ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> &addThing, uint32_t addCount, uint32_t flags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { - bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); + const bool childIsOwner = hasBitSet(FLAG_CHILDISOWNER, flags); if (childIsOwner) { // a child container is querying, since we are the top container (not carried by a player) // just return with no error. @@ -466,7 +466,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> & } if (item->hasOwner()) { // a non-owner can move the item around but not pick it up - auto toPlayer = getTopParent()->getPlayer(); + const auto &toPlayer = getTopParent()->getPlayer(); if (toPlayer && !item->isOwner(toPlayer)) { return RETURNVALUE_ITEMISNOTYOURS; } @@ -478,16 +478,16 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> & } std::shared_ptr<Cylinder> cylinder = getParent(); - auto noLimit = hasBitSet(FLAG_NOLIMIT, flags); + const auto noLimit = hasBitSet(FLAG_NOLIMIT, flags); while (cylinder) { if (cylinder == addThing) { return RETURNVALUE_THISISIMPOSSIBLE; } - std::shared_ptr<Container> container = cylinder->getContainer(); + const std::shared_ptr<Container> &container = cylinder->getContainer(); if (!noLimit && container && container->isInbox()) { return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - std::shared_ptr<Cylinder> parent = cylinder->getParent(); + const std::shared_ptr<Cylinder> &parent = cylinder->getParent(); if (cylinder == parent) { g_logger().error("Container::queryAdd: parent == cylinder. Preventing infinite loop."); return RETURNVALUE_NOTPOSSIBLE; @@ -499,15 +499,15 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> & return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - if (const auto topParentContainer = getTopParentContainer()) { - if (const auto addContainer = item->getContainer()) { - uint32_t addContainerCount = addContainer->getContainerHoldingCount() + 1; - uint32_t maxContainer = static_cast<uint32_t>(g_configManager().getNumber(MAX_CONTAINER, __FUNCTION__)); + if (const auto &topParentContainer = getTopParentContainer()) { + if (const auto &addContainer = item->getContainer()) { + const uint32_t addContainerCount = addContainer->getContainerHoldingCount() + 1; + const uint32_t maxContainer = static_cast<uint32_t>(g_configManager().getNumber(MAX_CONTAINER, __FUNCTION__)); if (addContainerCount + topParentContainer->getContainerHoldingCount() > maxContainer) { return RETURNVALUE_CONTAINERISFULL; } - uint32_t addItemCount = addContainer->getItemHoldingCount() + 1; + const uint32_t addItemCount = addContainer->getItemHoldingCount() + 1; if (addItemCount + topParentContainer->getItemHoldingCount() > m_maxItems) { return RETURNVALUE_CONTAINERISFULL; } @@ -522,7 +522,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> & return RETURNVALUE_ONLYAMMOINQUIVER; } - std::shared_ptr<Cylinder> topParent = getTopParent(); + const std::shared_ptr<Cylinder> &topParent = getTopParent(); if (topParent != getContainer()) { return topParent->queryAdd(INDEX_WHEREEVER, item, addCount, flags | FLAG_CHILDISOWNER, actor); } else { @@ -531,7 +531,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr<Thing> & } ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t &maxQueryCount, uint32_t flags) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { maxQueryCount = 0; return RETURNVALUE_NOTPOSSIBLE; @@ -542,7 +542,7 @@ ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr<Thing> return RETURNVALUE_NOERROR; } - int32_t freeSlots = std::max<int32_t>(capacity() - size(), 0); + const int32_t freeSlots = std::max<int32_t>(capacity() - size(), 0); if (item->isStackable()) { uint32_t n = 0; @@ -550,16 +550,16 @@ ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr<Thing> if (index == INDEX_WHEREEVER) { // Iterate through every item and check how much free stackable slots there is. uint32_t slotIndex = 0; - for (const std::shared_ptr<Item> &containerItem : itemlist) { + for (const auto &containerItem : itemlist) { if (containerItem != item && containerItem->equals(item) && containerItem->getItemCount() < containerItem->getStackSize()) { - uint32_t remainder = (containerItem->getStackSize() - containerItem->getItemCount()); + const uint32_t remainder = (containerItem->getStackSize() - containerItem->getItemCount()); if (queryAdd(slotIndex++, item, remainder, flags) == RETURNVALUE_NOERROR) { n += remainder; } } } } else { - std::shared_ptr<Item> destItem = getItemByIndex(index); + const auto &destItem = getItemByIndex(index); if (item->equals(destItem) && destItem->getItemCount() < destItem->getStackSize()) { n = destItem->getStackSize() - destItem->getItemCount(); } @@ -580,13 +580,13 @@ ReturnValue Container::queryMaxCount(int32_t index, const std::shared_ptr<Thing> } ReturnValue Container::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor /*= nullptr */) { - int32_t index = getThingIndex(thing); + const int32_t index = getThingIndex(thing); if (index == -1) { g_logger().debug("{} - Failed to get thing index", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { g_logger().debug("{} - Item is nullptr", __FUNCTION__); return RETURNVALUE_NOTPOSSIBLE; @@ -601,7 +601,7 @@ ReturnValue Container::queryRemove(const std::shared_ptr<Thing> &thing, uint32_t g_logger().debug("{} - Item is not movable", __FUNCTION__); return RETURNVALUE_NOTMOVABLE; } - std::shared_ptr<HouseTile> houseTile = std::dynamic_pointer_cast<HouseTile>(getTopParent()); + const std::shared_ptr<HouseTile> &houseTile = std::dynamic_pointer_cast<HouseTile>(getTopParent()); if (houseTile) { return houseTile->queryRemove(thing, count, flags, actor); } @@ -618,7 +618,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: index = INDEX_WHEREEVER; destItem = nullptr; - std::shared_ptr<Container> parentContainer = std::dynamic_pointer_cast<Container>(getParent()); + const auto &parentContainer = std::dynamic_pointer_cast<Container>(getParent()); if (parentContainer) { return parentContainer; } @@ -646,12 +646,12 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: } if (index != INDEX_WHEREEVER) { - std::shared_ptr<Item> itemFromIndex = getItemByIndex(index); + const auto &itemFromIndex = getItemByIndex(index); if (itemFromIndex) { destItem = itemFromIndex; } - std::shared_ptr<Cylinder> subCylinder = std::dynamic_pointer_cast<Cylinder>(destItem); + const auto &subCylinder = std::dynamic_pointer_cast<Cylinder>(destItem); if (subCylinder) { index = INDEX_WHEREEVER; destItem = nullptr; @@ -659,7 +659,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: } } - bool autoStack = !hasBitSet(FLAG_IGNOREAUTOSTACK, flags); + const bool autoStack = !hasBitSet(FLAG_IGNOREAUTOSTACK, flags); if (autoStack && item->isStackable() && item->getParent() != getContainer()) { if (destItem && (destItem)->equals(item) && (destItem)->getItemCount() < (destItem)->getStackSize()) { return getContainer(); @@ -667,7 +667,7 @@ std::shared_ptr<Cylinder> Container::queryDestination(int32_t &index, const std: // try find a suitable item to stack with uint32_t n = 0; - for (const std::shared_ptr<Item> &listItem : itemlist) { + for (const auto &listItem : itemlist) { if (listItem != item && listItem->equals(item) && listItem->getItemCount() < listItem->getStackSize()) { destItem = listItem; index = n; @@ -692,7 +692,7 @@ void Container::addThing(int32_t index, const std::shared_ptr<Thing> &thing) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -718,7 +718,7 @@ void Container::addItemBack(const std::shared_ptr<Item> &item) { } void Container::updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) { - int32_t index = getThingIndex(thing); + const int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -745,7 +745,7 @@ void Container::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing return /*RETURNVALUE_NOTPOSSIBLE*/; } - std::shared_ptr<Item> replacedItem = getItemByIndex(index); + const auto &replacedItem = getItemByIndex(index); if (!replacedItem) { return /*RETURNVALUE_NOTPOSSIBLE*/; } @@ -763,18 +763,18 @@ void Container::replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing } void Container::removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return /*RETURNVALUE_NOTPOSSIBLE*/; } - int32_t index = getThingIndex(thing); + const int32_t index = getThingIndex(thing); if (index == -1) { return /*RETURNVALUE_NOTPOSSIBLE*/; } if (item->isStackable() && count != item->getItemCount()) { - uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, item->getItemCount() - count)); + const uint8_t newCount = static_cast<uint8_t>(std::max<int32_t>(0, item->getItemCount() - count)); const int32_t oldWeight = item->getWeight(); item->setItemCount(newCount); updateItemWeight(-oldWeight + item->getWeight()); @@ -851,7 +851,7 @@ ItemVector Container::getItems(bool recursive /*= false*/) { } void Container::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> topParent = getTopParent(); + const std::shared_ptr<Cylinder> &topParent = getTopParent(); if (topParent->getCreature()) { topParent->postAddNotification(thing, oldParent, index, LINK_TOPPARENT); } else if (topParent == getContainer()) { @@ -865,7 +865,7 @@ void Container::postAddNotification(const std::shared_ptr<Thing> &thing, const s } void Container::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> topParent = getTopParent(); + const std::shared_ptr<Cylinder> &topParent = getTopParent(); if (topParent->getCreature()) { topParent->postRemoveNotification(thing, newParent, index, LINK_TOPPARENT); } else if (topParent == getContainer()) { @@ -887,7 +887,7 @@ void Container::internalAddThing(uint32_t, const std::shared_ptr<Thing> &thing) return; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return; } @@ -911,7 +911,7 @@ void Container::stopDecaying() { } } -uint16_t Container::getFreeSlots() { +uint16_t Container::getFreeSlots() const { uint16_t counter = std::max<uint16_t>(0, capacity() - size()); for (const auto &item : itemlist) { @@ -932,20 +932,20 @@ ContainerIterator Container::iterator() { return cit; } -void Container::removeItem(std::shared_ptr<Thing> thing, bool sendUpdateToClient /* = false*/) { +void Container::removeItem(const std::shared_ptr<Thing> &thing, bool sendUpdateToClient /* = false*/) { if (thing == nullptr) { return; } - auto itemToRemove = thing->getItem(); + const auto &itemToRemove = thing->getItem(); if (itemToRemove == nullptr) { return; } - auto it = std::ranges::find(itemlist.begin(), itemlist.end(), itemToRemove); + const auto it = std::ranges::find(itemlist.begin(), itemlist.end(), itemToRemove); if (it != itemlist.end()) { // Send change to client - if (auto thingIndex = getThingIndex(thing); sendUpdateToClient && thingIndex != -1 && getParent()) { + if (const auto thingIndex = getThingIndex(thing); sendUpdateToClient && thingIndex != -1 && getParent()) { onRemoveContainerItem(thingIndex, itemToRemove); } @@ -954,13 +954,13 @@ void Container::removeItem(std::shared_ptr<Thing> thing, bool sendUpdateToClient } } -std::shared_ptr<Item> ContainerIterator::operator*() { +std::shared_ptr<Item> ContainerIterator::operator*() const { return *cur; } void ContainerIterator::advance() { - if (std::shared_ptr<Item> i = *cur) { - if (std::shared_ptr<Container> c = i->getContainer()) { + if (const auto &i = *cur) { + if (const auto &c = i->getContainer()) { if (!c->empty()) { over.push_back(c); } diff --git a/src/items/containers/container.hpp b/src/items/containers/container.hpp index c373eaa5e43..f21efff1fd4 100644 --- a/src/items/containers/container.hpp +++ b/src/items/containers/container.hpp @@ -26,7 +26,7 @@ class ContainerIterator { } void advance(); - std::shared_ptr<Item> operator*(); + std::shared_ptr<Item> operator*() const; private: std::list<std::shared_ptr<Container>> over; @@ -59,7 +59,7 @@ class Container : public Item, public Cylinder { return static_self_cast<Container>(); } - std::shared_ptr<Cylinder> getCylinder() override final { + std::shared_ptr<Cylinder> getCylinder() final { return getContainer(); } @@ -112,7 +112,7 @@ class Container : public Item, public Cylinder { return itemlist.rend(); } - bool countsToLootAnalyzerBalance(); + bool countsToLootAnalyzerBalance() const; bool hasParent(); void addItem(const std::shared_ptr<Item> &item); StashContainerList getStowableItems() const; @@ -127,7 +127,7 @@ class Container : public Item, public Cylinder { uint32_t getItemHoldingCount(); uint32_t getContainerHoldingCount(); - uint16_t getFreeSlots(); + uint16_t getFreeSlots() const; uint32_t getWeight() const final; bool isUnlocked() const { @@ -148,7 +148,7 @@ class Container : public Item, public Cylinder { void addItemBack(const std::shared_ptr<Item> &item); void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) final; - void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) override final; + void replaceThing(uint32_t index, const std::shared_ptr<Thing> &thing) final; void removeThing(const std::shared_ptr<Thing> &thing, uint32_t count) final; @@ -169,7 +169,7 @@ class Container : public Item, public Cylinder { void startDecaying() override; void stopDecaying() override; - virtual void removeItem(std::shared_ptr<Thing> thing, bool sendUpdateToClient = false); + virtual void removeItem(const std::shared_ptr<Thing> &thing, bool sendUpdateToClient = false); uint32_t getOwnerId() const final; diff --git a/src/items/containers/depot/depotchest.cpp b/src/items/containers/depot/depotchest.cpp index 049190f849a..24bb023f0b7 100644 --- a/src/items/containers/depot/depotchest.cpp +++ b/src/items/containers/depot/depotchest.cpp @@ -20,7 +20,7 @@ DepotChest::DepotChest(uint16_t type) : } ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor /* = nullptr*/) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item == nullptr) { return RETURNVALUE_NOTPOSSIBLE; } @@ -28,7 +28,7 @@ ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &th return RETURNVALUE_ITEMISNOTYOURS; } - bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); + const bool skipLimit = hasBitSet(FLAG_NOLIMIT, flags); if (!skipLimit) { int32_t addCount = 0; @@ -37,14 +37,14 @@ ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &th } if (item->getTopParent().get() != this) { - if (std::shared_ptr<Container> container = item->getContainer()) { + if (const std::shared_ptr<Container> &container = item->getContainer()) { addCount = container->getItemHoldingCount() + 1; } else { addCount = 1; } } - if (std::shared_ptr<Cylinder> localParent = getRealParent()) { + if (const std::shared_ptr<Cylinder> &localParent = getRealParent()) { if (localParent->getContainer()->getItemHoldingCount() + addCount > maxDepotItems) { return RETURNVALUE_DEPOTISFULL; } @@ -57,21 +57,21 @@ ReturnValue DepotChest::queryAdd(int32_t index, const std::shared_ptr<Thing> &th } void DepotChest::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } void DepotChest::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } std::shared_ptr<Cylinder> DepotChest::getParent() { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked && parentLocked->getParent()) { return parentLocked->getParent()->getParent(); } diff --git a/src/items/containers/depot/depotlocker.cpp b/src/items/containers/depot/depotlocker.cpp index 087cb293135..a0150b195fa 100644 --- a/src/items/containers/depot/depotlocker.cpp +++ b/src/items/containers/depot/depotlocker.cpp @@ -29,21 +29,21 @@ ReturnValue DepotLocker::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint3 } void DepotLocker::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postAddNotification(thing, oldParent, index, LINK_PARENT); } } void DepotLocker::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } void DepotLocker::removeInbox(const std::shared_ptr<Inbox> &inbox) { - auto cit = std::find(itemlist.begin(), itemlist.end(), inbox); + const auto cit = std::ranges::find(itemlist, inbox); if (cit == itemlist.end()) { return; } diff --git a/src/items/containers/inbox/inbox.cpp b/src/items/containers/inbox/inbox.cpp index 7376c87ff83..426fbdb12c6 100644 --- a/src/items/containers/inbox/inbox.cpp +++ b/src/items/containers/inbox/inbox.cpp @@ -24,7 +24,7 @@ ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32 return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } @@ -38,7 +38,7 @@ ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32 } if (item->getTopParent().get() != this) { // MY - if (std::shared_ptr<Container> container = item->getContainer()) { + if (const std::shared_ptr<Container> &container = item->getContainer()) { addCount = container->getItemHoldingCount() + 1; } else { addCount = 1; @@ -53,21 +53,21 @@ ReturnValue Inbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32 } void Inbox::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } void Inbox::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } std::shared_ptr<Cylinder> Inbox::getParent() { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked) { return parentLocked->getParent(); } diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index 7e5e056ba69..f6c42f45adf 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -16,7 +16,7 @@ #include "map/spectators.hpp" ReturnValue Mailbox::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, const std::shared_ptr<Creature> &) { - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item && Mailbox::canSend(item)) { return RETURNVALUE_NOERROR; } @@ -45,7 +45,7 @@ void Mailbox::addThing(int32_t, const std::shared_ptr<Thing> &thing) { return; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (item && Mailbox::canSend(item)) { sendItem(item); } @@ -99,7 +99,7 @@ bool Mailbox::sendItem(const std::shared_ptr<Item> &item) const { } if (player && item) { if (g_game().internalMoveItem(item->getParent(), player->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT) == RETURNVALUE_NOERROR) { - auto newItem = g_game().transformItem(item, item->getID() + 1); + const auto &newItem = g_game().transformItem(item, item->getID() + 1); if (newItem && newItem->getID() == ITEM_LETTER_STAMPED && !writer.empty()) { newItem->setAttribute(ItemAttribute_t::WRITER, writer); newItem->setAttribute(ItemAttribute_t::DATE, date); @@ -117,7 +117,7 @@ bool Mailbox::sendItem(const std::shared_ptr<Item> &item) const { } bool Mailbox::getReceiver(const std::shared_ptr<Item> &item, std::string &name) const { - std::shared_ptr<Container> container = item->getContainer(); + const std::shared_ptr<Container> &container = item->getContainer(); if (container) { for (const std::shared_ptr<Item> &containerItem : container->getItemList()) { if (containerItem->getID() == ITEM_LABEL && getReceiver(containerItem, name)) { diff --git a/src/items/containers/mailbox/mailbox.hpp b/src/items/containers/mailbox/mailbox.hpp index 353606bfb59..8891c00339e 100644 --- a/src/items/containers/mailbox/mailbox.hpp +++ b/src/items/containers/mailbox/mailbox.hpp @@ -21,7 +21,7 @@ class Mailbox final : public Item, public Cylinder { return static_self_cast<Mailbox>(); } - std::shared_ptr<Cylinder> getCylinder() final { + std::shared_ptr<Cylinder> getCylinder() override { return getMailbox(); } diff --git a/src/items/containers/rewards/reward.cpp b/src/items/containers/rewards/reward.cpp index a89f6543aa5..eac41217e14 100644 --- a/src/items/containers/rewards/reward.cpp +++ b/src/items/containers/rewards/reward.cpp @@ -19,11 +19,11 @@ Reward::Reward() : } ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint32_t, uint32_t, const std::shared_ptr<Creature> &actor /* = nullptr*/) { - if (actor) { + if (actor || !thing) { return RETURNVALUE_NOTPOSSIBLE; } - const auto item = thing->getItem(); + const auto &item = thing->getItem(); if (!item) { return RETURNVALUE_NOTPOSSIBLE; } @@ -40,14 +40,14 @@ ReturnValue Reward::queryAdd(int32_t, const std::shared_ptr<Thing> &thing, uint3 } void Reward::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postAddNotification(thing, oldParent, index, LINK_PARENT); } } void Reward::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - std::shared_ptr<Cylinder> localParent = getParent(); + const std::shared_ptr<Cylinder> &localParent = getParent(); if (localParent != nullptr) { localParent->postRemoveNotification(thing, newParent, index, LINK_PARENT); } diff --git a/src/items/containers/rewards/reward.hpp b/src/items/containers/rewards/reward.hpp index 47925dab2e3..afdcd1c0d5f 100644 --- a/src/items/containers/rewards/reward.hpp +++ b/src/items/containers/rewards/reward.hpp @@ -11,27 +11,27 @@ #include "items/containers/container.hpp" -class Reward : public Container { +class Reward final : public Container { public: explicit Reward(); - std::shared_ptr<Reward> getReward() final { + std::shared_ptr<Reward> getReward() override { return static_self_cast<Reward>(); } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) final; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; // overrides - bool canRemove() const final { + bool canRemove() const override { return true; } - std::shared_ptr<Cylinder> getParent() final; - std::shared_ptr<Cylinder> getRealParent() final { + std::shared_ptr<Cylinder> getParent() override; + std::shared_ptr<Cylinder> getRealParent() override { return m_parent.lock(); } }; diff --git a/src/items/containers/rewards/rewardchest.cpp b/src/items/containers/rewards/rewardchest.cpp index b203115199f..7fd7c929eaa 100644 --- a/src/items/containers/rewards/rewardchest.cpp +++ b/src/items/containers/rewards/rewardchest.cpp @@ -27,31 +27,31 @@ ReturnValue RewardChest::queryAdd(int32_t, const std::shared_ptr<Thing> &, uint3 } void RewardChest::postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t) { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postAddNotification(thing, oldParent, index, LINK_PARENT); } } void RewardChest::postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t) { - auto parentLocked = m_parent.lock(); + const auto &parentLocked = m_parent.lock(); if (parentLocked) { parentLocked->postRemoveNotification(thing, newParent, index, LINK_PARENT); } } // Second argument is disabled by default because not need to send to client in the RewardChest -void RewardChest::removeItem(std::shared_ptr<Thing> thing, bool /* sendToClient = false*/) { +void RewardChest::removeItem(const std::shared_ptr<Thing> &thing, bool /* sendToClient = false*/) { if (thing == nullptr) { return; } - auto itemToRemove = thing->getItem(); + const auto &itemToRemove = thing->getItem(); if (itemToRemove == nullptr) { return; } - auto it = std::ranges::find(itemlist.begin(), itemlist.end(), itemToRemove); + const auto it = std::ranges::find(itemlist.begin(), itemlist.end(), itemToRemove); if (it != itemlist.end()) { itemlist.erase(it); itemToRemove->resetParent(); diff --git a/src/items/containers/rewards/rewardchest.hpp b/src/items/containers/rewards/rewardchest.hpp index 574f5c6b1fa..6c66865699b 100644 --- a/src/items/containers/rewards/rewardchest.hpp +++ b/src/items/containers/rewards/rewardchest.hpp @@ -15,19 +15,19 @@ class RewardChest final : public Container { public: explicit RewardChest(uint16_t type); - std::shared_ptr<RewardChest> getRewardChest() final { + std::shared_ptr<RewardChest> getRewardChest() override { return static_self_cast<RewardChest>(); } // cylinder implementations - ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) final; + ReturnValue queryAdd(int32_t index, const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; - void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; - void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) final; + void postAddNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &oldParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; + void postRemoveNotification(const std::shared_ptr<Thing> &thing, const std::shared_ptr<Cylinder> &newParent, int32_t index, CylinderLink_t link = LINK_OWNER) override; - bool canRemove() const final { + bool canRemove() const override { return false; } - void removeItem(std::shared_ptr<Thing> thing, bool sendToClient = false) override; + void removeItem(const std::shared_ptr<Thing> &thing, bool sendToClient = false) override; }; diff --git a/src/items/decay/decay.cpp b/src/items/decay/decay.cpp index 81ef6bc708c..8a0d402d8f8 100644 --- a/src/items/decay/decay.cpp +++ b/src/items/decay/decay.cpp @@ -45,7 +45,7 @@ void Decay::startDecay(const std::shared_ptr<Item> &item) { stopDecay(item); } - int64_t timestamp = OTSYS_TIME() + duration; + const int64_t timestamp = OTSYS_TIME() + duration; if (decayMap.empty()) { eventId = g_dispatcher().scheduleEvent( std::max<int32_t>(SCHEDULER_MINTICKS, duration), [this] { checkDecay(); }, "Decay::checkDecay" @@ -67,13 +67,14 @@ void Decay::startDecay(const std::shared_ptr<Item> &item) { void Decay::stopDecay(const std::shared_ptr<Item> &item) { if (item->hasAttribute(ItemAttribute_t::DECAYSTATE)) { - auto timestamp = item->getAttribute<int64_t>(ItemAttribute_t::DURATION_TIMESTAMP); + const auto timestamp = item->getAttribute<int64_t>(ItemAttribute_t::DURATION_TIMESTAMP); if (item->hasAttribute(ItemAttribute_t::DURATION_TIMESTAMP)) { - auto it = decayMap.find(timestamp); + const auto it = decayMap.find(timestamp); if (it != decayMap.end()) { auto &decayItems = it->second; - size_t i = 0, end = decayItems.size(); + size_t i = 0; + const size_t end = decayItems.size(); auto decayItem = decayItems[i]; if (end == 1) { if (item == decayItem) { @@ -111,12 +112,13 @@ void Decay::stopDecay(const std::shared_ptr<Item> &item) { } void Decay::checkDecay() { - int64_t timestamp = OTSYS_TIME(); + const int64_t timestamp = OTSYS_TIME(); std::vector<std::shared_ptr<Item>> tempItems; tempItems.reserve(32); // Small preallocation - auto it = decayMap.begin(), end = decayMap.end(); + auto it = decayMap.begin(); + const auto end = decayMap.end(); while (it != end) { if (it->first > timestamp) { break; @@ -126,7 +128,7 @@ void Decay::checkDecay() { auto &decayItems = it->second; tempItems.reserve(tempItems.size() + decayItems.size()); for (auto &decayItem : decayItems) { - tempItems.push_back(decayItem); + tempItems.emplace_back(decayItem); } it = decayMap.erase(it); } @@ -153,7 +155,7 @@ void Decay::internalDecayItem(const std::shared_ptr<Item> &item) { // Remove the item and halt the decay process if a player triggers a bug where the item's decay ID matches its equip or de-equip transformation ID if (it.id == it.transformEquipTo || it.id == it.transformDeEquipTo) { g_game().internalRemoveItem(item); - auto player = item->getHoldingPlayer(); + const auto &player = item->getHoldingPlayer(); if (player) { g_logger().error("[{}] - internalDecayItem failed to player {}, item id is same from transform equip/deequip, " " item id: {}, equip to id: '{}', deequip to id '{}'", @@ -204,7 +206,7 @@ void Decay::internalDecayItem(const std::shared_ptr<Item> &item) { return; } - ReturnValue ret = g_game().internalRemoveItem(item); + const ReturnValue ret = g_game().internalRemoveItem(item); if (ret != RETURNVALUE_NOERROR) { g_logger().error("[Decay::internalDecayItem] - internalDecayItem failed, " "error code: {}, item id: {}", diff --git a/src/items/functions/item/attribute.cpp b/src/items/functions/item/attribute.cpp index b3ee3d64e0e..a65d0f2d9d4 100644 --- a/src/items/functions/item/attribute.cpp +++ b/src/items/functions/item/attribute.cpp @@ -22,7 +22,7 @@ const std::string &ItemAttribute::getAttributeString(ItemAttribute_t type) const return emptyString; } - auto attribute = getAttribute(type); + const auto attribute = getAttribute(type); if (!attribute) { return emptyString; } @@ -36,7 +36,7 @@ const int64_t &ItemAttribute::getAttributeValue(ItemAttribute_t type) const { return emptyInt; } - auto attribute = getAttribute(type); + const auto attribute = getAttribute(type); if (!attribute) { return emptyInt; } @@ -119,22 +119,22 @@ const CustomAttribute* ItemAttribute::getCustomAttribute(const std::string &attr } void ItemAttribute::setCustomAttribute(const std::string &key, const int64_t value) { - CustomAttribute attribute(key, value); + const CustomAttribute attribute(key, value); customAttributeMap[asLowerCaseString(key)] = attribute; } void ItemAttribute::setCustomAttribute(const std::string &key, const std::string &value) { - CustomAttribute attribute(key, value); + const CustomAttribute attribute(key, value); customAttributeMap[asLowerCaseString(key)] = attribute; } void ItemAttribute::setCustomAttribute(const std::string &key, const double value) { - CustomAttribute attribute(key, value); + const CustomAttribute attribute(key, value); customAttributeMap[asLowerCaseString(key)] = attribute; } void ItemAttribute::setCustomAttribute(const std::string &key, const bool value) { - CustomAttribute attribute(key, value); + const CustomAttribute attribute(key, value); customAttributeMap[asLowerCaseString(key)] = attribute; } @@ -143,7 +143,7 @@ void ItemAttribute::addCustomAttribute(const std::string &key, const CustomAttri } bool ItemAttribute::removeCustomAttribute(const std::string &attributeName) { - auto it = customAttributeMap.find(asLowerCaseString(attributeName)); + const auto it = customAttributeMap.find(asLowerCaseString(attributeName)); if (it == customAttributeMap.end()) { return false; } diff --git a/src/items/functions/item/item_parse.cpp b/src/items/functions/item/item_parse.cpp index 06215ccf650..49adcae2899 100644 --- a/src/items/functions/item/item_parse.cpp +++ b/src/items/functions/item/item_parse.cpp @@ -82,7 +82,7 @@ void ItemParse::initParse(const std::string &tmpStrValue, pugi::xml_node attribu } void ItemParse::parseDummyRate(pugi::xml_node attributeNode, ItemType &itemType) { - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -95,7 +95,7 @@ void ItemParse::parseDummyRate(pugi::xml_node attributeNode, ItemType &itemType) auto stringValue = asLowerCaseString(subKeyAttribute.as_string()); if (stringValue == "rate") { - uint16_t rate = subValueAttribute.as_uint(); + const uint16_t rate = subValueAttribute.as_uint(); Item::items.addDummyId(itemType.id, rate); } } @@ -105,7 +105,7 @@ void ItemParse::parseType(const std::string &tmpStrValue, pugi::xml_node attribu std::string stringValue = tmpStrValue; if (stringValue == "type") { stringValue = asLowerCaseString(valueAttribute.as_string()); - auto itemMap = ItemTypesMap.find(stringValue); + const auto &itemMap = ItemTypesMap.find(stringValue); if (itemMap != ItemTypesMap.end()) { itemType.type = itemMap->second; if (itemType.type == ITEM_TYPE_CONTAINER) { @@ -231,7 +231,7 @@ void ItemParse::parseFloorChange(const std::string &tmpStrValue, pugi::xml_attri std::string stringValue = tmpStrValue; if (stringValue == "floorchange") { stringValue = asLowerCaseString(valueAttribute.as_string()); - auto itemMap = TileStatesMap.find(stringValue); + const auto &itemMap = TileStatesMap.find(stringValue); if (itemMap != TileStatesMap.end()) { itemType.floorChange = itemMap->second; } else { @@ -251,7 +251,7 @@ void ItemParse::parseFluidSource(const std::string &tmpStrValue, pugi::xml_attri std::string stringValue = tmpStrValue; if (stringValue == "fluidsource") { stringValue = asLowerCaseString(valueAttribute.as_string()); - auto itemMap = FluidTypesMap.find(stringValue); + const auto &itemMap = FluidTypesMap.find(stringValue); if (itemMap != FluidTypesMap.end()) { itemType.fluidSource = itemMap->second; } else { @@ -278,7 +278,7 @@ void ItemParse::parseWeaponType(const std::string &tmpStrValue, pugi::xml_attrib std::string stringValue = tmpStrValue; if (stringValue == "weapontype") { stringValue = asLowerCaseString(valueAttribute.as_string()); - auto itemMap = WeaponTypesMap.find(stringValue); + const auto &itemMap = WeaponTypesMap.find(stringValue); if (itemMap != WeaponTypesMap.end()) { if (tmpStrValue == "spellbook") { itemType.spellbook = true; @@ -338,7 +338,7 @@ void ItemParse::parseAmmoType(const std::string &tmpStrValue, pugi::xml_attribut void ItemParse::parseShootType(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { const std::string &stringValue = tmpStrValue; if (stringValue == "shoottype") { - ShootType_t shoot = getShootType(asLowerCaseString(valueAttribute.as_string())); + const ShootType_t &shoot = getShootType(asLowerCaseString(valueAttribute.as_string())); if (shoot != CONST_ANI_NONE) { itemType.shootType = shoot; } else { @@ -350,7 +350,7 @@ void ItemParse::parseShootType(const std::string &tmpStrValue, pugi::xml_attribu void ItemParse::parseMagicEffect(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { const std::string &stringValue = tmpStrValue; if (stringValue == "effect") { - MagicEffectClasses effect = getMagicEffect(asLowerCaseString(valueAttribute.as_string())); + const MagicEffectClasses &effect = getMagicEffect(asLowerCaseString(valueAttribute.as_string())); if (effect != CONST_ME_NONE) { itemType.magicEffect = effect; } else { @@ -427,7 +427,7 @@ void ItemParse::parseCharges(const std::string &tmpStrValue, pugi::xml_attribute } void ItemParse::parseShowAttributes(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { - std::string lowerStringValue = asLowerCaseString(tmpStrValue); + const std::string lowerStringValue = asLowerCaseString(tmpStrValue); if (lowerStringValue == "showattributes") { itemType.showAttributes = valueAttribute.as_bool(); } @@ -556,20 +556,20 @@ void ItemParse::parseFieldAbsorbPercent(const std::string &tmpStrValue, pugi::xm void ItemParse::parseAbsorbPercent(const std::string &tmpStrValue, pugi::xml_attribute valueAttribute, ItemType &itemType) { const std::string &stringValue = tmpStrValue; if (stringValue == "absorbpercentall") { - auto value = pugi::cast<int16_t>(valueAttribute.value()); + const auto value = pugi::cast<int16_t>(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); for (auto &i : abilities.absorbPercent) { i += value; } } else if (stringValue == "absorbpercentelements") { - auto value = pugi::cast<int16_t>(valueAttribute.value()); + const auto value = pugi::cast<int16_t>(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_EARTHDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_ICEDAMAGE)] += value; } else if (stringValue == "absorbpercentmagic") { - auto value = pugi::cast<int16_t>(valueAttribute.value()); + const auto value = pugi::cast<int16_t>(valueAttribute.value()); Abilities &abilities = itemType.getAbilities(); abilities.absorbPercent[combatTypeToIndex(COMBAT_ENERGYDAMAGE)] += value; abilities.absorbPercent[combatTypeToIndex(COMBAT_FIREDAMAGE)] += value; @@ -679,7 +679,7 @@ void ItemParse::parseFieldCombatDamage(const std::shared_ptr<ConditionDamage> &c int32_t combatStart = 0; int32_t combatCount = 1; - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -705,7 +705,7 @@ void ItemParse::parseFieldCombatDamage(const std::shared_ptr<ConditionDamage> &c std::list<int32_t> damageList; ConditionDamage::generateDamageList(combatDamage, combatStart, damageList); - for (int32_t damageValue : damageList) { + for (const int32_t damageValue : damageList) { conditionDamage->addDamage(1, combatTicks, -damageValue); } @@ -764,7 +764,7 @@ void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute va } if (stringValue == "maletransformto") { - auto valueMale = pugi::cast<uint16_t>(valueAttribute.value()); + const auto valueMale = pugi::cast<uint16_t>(valueAttribute.value()); ItemType &other = Item::items.getItemType(valueMale); itemType.transformToOnUse[PLAYERSEX_MALE] = valueMale; if (other.transformToFree == 0) { @@ -775,7 +775,7 @@ void ItemParse::parseBeds(const std::string &tmpStrValue, pugi::xml_attribute va itemType.transformToOnUse[PLAYERSEX_FEMALE] = valueMale; } } else if (stringValue == "femaletransformto") { - auto valueFemale = pugi::cast<uint16_t>(valueAttribute.value()); + const auto valueFemale = pugi::cast<uint16_t>(valueAttribute.value()); ItemType &other = Item::items.getItemType(valueFemale); itemType.transformToOnUse[PLAYERSEX_FEMALE] = valueFemale; @@ -847,7 +847,7 @@ void ItemParse::parseImbuement(const std::string &tmpStrValue, pugi::xml_node at } itemType.imbuementSlot = pugi::cast<uint8_t>(valueAttribute.value()); - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -858,9 +858,9 @@ void ItemParse::parseImbuement(const std::string &tmpStrValue, pugi::xml_node at continue; } - auto itemMap = ImbuementsTypeMap.find(asLowerCaseString(subKeyAttribute.as_string())); + const auto &itemMap = ImbuementsTypeMap.find(asLowerCaseString(subKeyAttribute.as_string())); if (itemMap != ImbuementsTypeMap.end()) { - ImbuementTypes_t imbuementType = getImbuementType(asLowerCaseString(subKeyAttribute.as_string())); + const ImbuementTypes_t imbuementType = getImbuementType(asLowerCaseString(subKeyAttribute.as_string())); if (imbuementType != IMBUEMENT_NONE) { itemType.setImbuementType(imbuementType, pugi::cast<uint16_t>(subValueAttribute.value())); continue; @@ -1000,7 +1000,7 @@ void ItemParse::parseReflectDamage(const std::string &tmpStrValue, pugi::xml_att abilities.reflectFlat[combatTypeToIndex(COMBAT_PHYSICALDAMAGE)] += pugi::cast<int32_t>(valueAttribute.value()); } else if (stringValue == "reflectpercentall") { auto value = pugi::cast<int32_t>(valueAttribute.value()); - std::transform(std::begin(abilities.reflectPercent), std::end(abilities.reflectPercent), std::begin(abilities.reflectPercent), [&](const auto &i) { + std::ranges::transform(abilities.reflectPercent, std::begin(abilities.reflectPercent), [&](const auto &i) { return i + value; }); } @@ -1064,7 +1064,7 @@ void ItemParse::createAndRegisterScript(ItemType &itemType, pugi::xml_node attri } uint32_t fromDamage = 0; uint32_t toDamage = 0; - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -1133,7 +1133,7 @@ void ItemParse::createAndRegisterScript(ItemType &itemType, pugi::xml_node attri std::string token; while (std::getline(ss, token, ',')) { - token.erase(token.begin(), std::find_if(token.begin(), token.end(), [](unsigned char ch) { + token.erase(token.begin(), std::ranges::find_if(token, [](unsigned char ch) { return !std::isspace(ch); })); token.erase(std::find_if(token.rbegin(), token.rend(), [](unsigned char ch) { @@ -1232,14 +1232,14 @@ void ItemParse::createAndRegisterScript(ItemType &itemType, pugi::xml_node attri } if (weapon) { - if (auto weaponWand = dynamic_pointer_cast<WeaponWand>(weapon)) { + if (const auto &weaponWand = dynamic_pointer_cast<WeaponWand>(weapon)) { g_logger().trace("Added weapon damage from '{}', to '{}'", fromDamage, toDamage); weaponWand->setMinChange(fromDamage); weaponWand->setMaxChange(toDamage); weaponWand->configureWeapon(itemType); } - auto combat = weapon->getCombat(); + const auto &combat = weapon->getCombat(); if (combat) { combat->setupChain(weapon); } @@ -1263,13 +1263,13 @@ void ItemParse::createAndRegisterScript(ItemType &itemType, pugi::xml_node attri void ItemParse::parseUnscriptedItems(const std::string_view &tmpStrValue, pugi::xml_node attributeNode, pugi::xml_attribute valueAttribute, ItemType &itemType) { if (tmpStrValue == "script") { - std::string scriptName = valueAttribute.as_string(); - auto tokens = split(scriptName.data(), ';'); + const std::string scriptName = valueAttribute.as_string(); + const auto tokens = split(scriptName, ';'); for (const auto &token : tokens) { if (token == "moveevent") { g_logger().trace("Registering moveevent for item id '{}', name '{}'", itemType.id, itemType.name); MoveEvent_t eventType = MOVE_EVENT_NONE; - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; @@ -1297,9 +1297,9 @@ void ItemParse::parseUnscriptedItems(const std::string_view &tmpStrValue, pugi:: createAndRegisterScript(itemType, attributeNode, eventType); } } else if (token == "weapon") { - WeaponType_t weaponType; + WeaponType_t weaponType = {}; g_logger().trace("Registering weapon for item id '{}', name '{}'", itemType.id, itemType.name); - for (auto subAttributeNode : attributeNode.children()) { + for (const auto &subAttributeNode : attributeNode.children()) { pugi::xml_attribute subKeyAttribute = subAttributeNode.attribute("key"); if (!subKeyAttribute) { continue; diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 268ff42c968..5187051bd4d 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -26,7 +26,7 @@ WeaponShared_ptr Weapons::getWeapon(const std::shared_ptr<Item> &item) const { return nullptr; } - auto it = weapons.find(item->getID()); + const auto it = weapons.find(item->getID()); if (it == weapons.end()) { return nullptr; } @@ -134,7 +134,7 @@ int32_t Weapon::playerWeaponCheck(const std::shared_ptr<Player> &player, const s } bool Weapon::useWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Creature> &target) const { - int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); + const int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } @@ -145,20 +145,20 @@ bool Weapon::useWeapon(const std::shared_ptr<Player> &player, const std::shared_ CombatDamage Weapon::getCombatDamage(CombatDamage combat, const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, int32_t damageModifier) const { // Local variables - uint32_t level = player->getLevel(); - int16_t elementalAttack = getElementDamageValue(); - int32_t weaponAttack = std::max<int32_t>(0, item->getAttack()); - int32_t playerSkill = player->getWeaponSkill(item); - float attackFactor = player->getAttackFactor(); // full atk, balanced or full defense + const uint32_t level = player->getLevel(); + const int16_t elementalAttack = getElementDamageValue(); + const int32_t weaponAttack = std::max<int32_t>(0, item->getAttack()); + const int32_t playerSkill = player->getWeaponSkill(item); + const float attackFactor = player->getAttackFactor(); // full atk, balanced or full defense // Getting values factores - int32_t totalAttack = elementalAttack + weaponAttack; - double weaponAttackProportion = (double)weaponAttack / (double)totalAttack; + const int32_t totalAttack = elementalAttack + weaponAttack; + const double weaponAttackProportion = static_cast<double>(weaponAttack) / static_cast<double>(totalAttack); // Calculating damage - int32_t maxDamage = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, playerSkill, totalAttack, attackFactor, true) * player->getVocation()->meleeDamageMultiplier * damageModifier / 100); - int32_t minDamage = level / 5; - int32_t realDamage = normal_random(minDamage, maxDamage); + const int32_t maxDamage = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, playerSkill, totalAttack, attackFactor, true) * player->getVocation()->meleeDamageMultiplier * damageModifier / 100); + const int32_t minDamage = level / 5; + const int32_t realDamage = normal_random(minDamage, maxDamage); // Setting damage to combat combat.primary.value = realDamage * weaponAttackProportion; @@ -171,11 +171,11 @@ bool Weapon::useFist(const std::shared_ptr<Player> &player, const std::shared_pt return false; } - float attackFactor = player->getAttackFactor(); - int32_t attackSkill = player->getSkillLevel(SKILL_FIST); - int32_t attackValue = 7; + const float attackFactor = player->getAttackFactor(); + const int32_t attackSkill = player->getSkillLevel(SKILL_FIST); + constexpr int32_t attackValue = 7; - int32_t maxDamage = Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true); + const int32_t maxDamage = Weapons::getMaxWeaponDamage(player->getLevel(), attackSkill, attackValue, attackFactor, true); CombatParams params; params.combatType = COMBAT_PHYSICALDAMAGE; @@ -217,7 +217,7 @@ void Weapon::internalUseWeapon(const std::shared_ptr<Player> &player, const std: g_logger().debug("Weapon::internalUseWeapon - Lua callback executed."); } else { CombatDamage damage; - WeaponType_t weaponType = item->getWeaponType(); + const WeaponType_t weaponType = item->getWeaponType(); if (weaponType == WEAPON_AMMO || weaponType == WEAPON_DISTANCE || weaponType == WEAPON_MISSILE) { damage.origin = ORIGIN_RANGED; } else { @@ -271,7 +271,7 @@ void Weapon::internalUseWeapon(const std::shared_ptr<Player> &player, const std: g_game().addMagicEffect(tile->getPosition(), CONST_ME_POFF); g_game().sendSingleSoundEffect(tile->getPosition(), SoundEffect_t::PHYSICAL_RANGE_MISS, player); } - onUsedWeapon(player, std::move(item), tile); + onUsedWeapon(player, item, tile); } void Weapon::onUsedWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Tile> &destTile) const { @@ -283,7 +283,7 @@ void Weapon::onUsedWeapon(const std::shared_ptr<Player> &player, const std::shar } } - uint32_t manaCost = getManaCost(player); + const uint32_t manaCost = getManaCost(player); if (manaCost != 0) { player->addManaSpent(manaCost); player->changeMana(-static_cast<int32_t>(manaCost)); @@ -293,7 +293,7 @@ void Weapon::onUsedWeapon(const std::shared_ptr<Player> &player, const std::shar } } - uint32_t healthCost = getHealthCost(player); + const uint32_t healthCost = getHealthCost(player); if (healthCost != 0) { player->changeHealth(-static_cast<int32_t>(healthCost)); } @@ -302,7 +302,7 @@ void Weapon::onUsedWeapon(const std::shared_ptr<Player> &player, const std::shar player->changeSoul(-static_cast<int32_t>(soul)); } - bool skipRemoveBeginningWeaponAmmo = !g_configManager().getBoolean(REMOVE_BEGINNING_WEAPON_AMMO, __FUNCTION__) && (item->getName() == "arrow" || item->getName() == "bolt" || item->getName() == "spear"); + const bool skipRemoveBeginningWeaponAmmo = !g_configManager().getBoolean(REMOVE_BEGINNING_WEAPON_AMMO, __FUNCTION__) && (item->getName() == "arrow" || item->getName() == "bolt" || item->getName() == "spear"); if (!skipRemoveBeginningWeaponAmmo && breakChance != 0 && uniform_random(1, 100) <= breakChance) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); @@ -318,7 +318,7 @@ void Weapon::onUsedWeapon(const std::shared_ptr<Player> &player, const std::shar break; case WEAPONACTION_REMOVECHARGE: { - if (uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES, __FUNCTION__)) { + if (const uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES, __FUNCTION__)) { g_game().transformItem(item, item->getID(), charges - 1); } break; @@ -381,7 +381,7 @@ bool Weapon::executeUseWeapon(const std::shared_ptr<Player> &player, const LuaVa } void Weapon::decrementItemCount(const std::shared_ptr<Item> &item) { - uint16_t count = item->getItemCount(); + const uint16_t count = item->getItemCount(); if (count > 1) { g_game().transformItem(item, item->getID(), count - 1); } else { @@ -390,7 +390,7 @@ void Weapon::decrementItemCount(const std::shared_ptr<Item> &item) { } bool Weapon::calculateSkillFormula(const std::shared_ptr<Player> &player, int32_t &attackSkill, int32_t &attackValue, float &attackFactor, int16_t &elementAttack, CombatDamage &damage, bool useCharges /* = false*/) const { - std::shared_ptr<Item> tool = player->getWeapon(); + const auto &tool = player->getWeapon(); if (!tool) { return false; } @@ -404,7 +404,7 @@ bool Weapon::calculateSkillFormula(const std::shared_ptr<Player> &player, int32_ } } - CombatType_t elementType = getElementType(); + const CombatType_t elementType = getElementType(); damage.secondary.type = elementType; bool shouldCalculateSecondaryDamage = false; @@ -415,7 +415,7 @@ bool Weapon::calculateSkillFormula(const std::shared_ptr<Player> &player, int32_ } if (useCharges) { - auto charges = tool->getAttribute<uint16_t>(ItemAttribute_t::CHARGES); + const auto charges = tool->getAttribute<uint16_t>(ItemAttribute_t::CHARGES); if (charges != 0) { g_game().transformItem(tool, tool->getID(), charges - 1); } @@ -448,12 +448,12 @@ void WeaponMelee::configureWeapon(const ItemType &it) { } bool WeaponMelee::useWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Creature> &target) const { - int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); + const int32_t damageModifier = playerWeaponCheck(player, target, item->getShootRange()); if (damageModifier == 0) { return false; } - int32_t cleavePercent = player->getCleavePercent(true); + const int32_t cleavePercent = player->getCleavePercent(true); if (cleavePercent > 0) { const Position &targetPos = target->getPosition(); const Position &playerPos = player->getPosition(); @@ -479,12 +479,12 @@ bool WeaponMelee::useWeapon(const std::shared_ptr<Player> &player, const std::sh secondCleaveTargetPos.y++; } } - std::shared_ptr<Tile> firstTile = g_game().map.getTile(firstCleaveTargetPos.x, firstCleaveTargetPos.y, firstCleaveTargetPos.z); - std::shared_ptr<Tile> secondTile = g_game().map.getTile(secondCleaveTargetPos.x, secondCleaveTargetPos.y, secondCleaveTargetPos.z); + const auto &firstTile = g_game().map.getTile(firstCleaveTargetPos.x, firstCleaveTargetPos.y, firstCleaveTargetPos.z); + const auto &secondTile = g_game().map.getTile(secondCleaveTargetPos.x, secondCleaveTargetPos.y, secondCleaveTargetPos.z); if (firstTile) { - if (CreatureVector* tileCreatures = firstTile->getCreatures()) { - for (auto &tileCreature : *tileCreatures) { + if (const CreatureVector* tileCreatures = firstTile->getCreatures()) { + for (const auto &tileCreature : *tileCreatures) { if (tileCreature->getMonster() || (tileCreature->getPlayer() && !player->hasSecureMode())) { internalUseWeapon(player, item, tileCreature, damageModifier, cleavePercent); } @@ -492,8 +492,8 @@ bool WeaponMelee::useWeapon(const std::shared_ptr<Player> &player, const std::sh } } if (secondTile) { - if (CreatureVector* tileCreatures = secondTile->getCreatures()) { - for (auto &tileCreature : *tileCreatures) { + if (const CreatureVector* tileCreatures = secondTile->getCreatures()) { + for (const auto &tileCreature : *tileCreatures) { if (tileCreature->getMonster() || (tileCreature->getPlayer() && !player->hasSecureMode())) { internalUseWeapon(player, item, tileCreature, damageModifier, cleavePercent); } @@ -514,7 +514,7 @@ bool WeaponMelee::getSkillType(const std::shared_ptr<Player> &player, const std: skillpoint = 0; } - WeaponType_t weaponType = item->getWeaponType(); + const WeaponType_t weaponType = item->getWeaponType(); switch (weaponType) { case WEAPON_SWORD: { skill = SKILL_SWORD; @@ -537,18 +537,18 @@ bool WeaponMelee::getSkillType(const std::shared_ptr<Player> &player, const std: return false; } -int32_t WeaponMelee::getElementDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature>, std::shared_ptr<Item> item) const { +int32_t WeaponMelee::getElementDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &, const std::shared_ptr<Item> &item) const { if (elementType == COMBAT_NONE) { return 0; } - int32_t attackSkill = player->getWeaponSkill(item); - int32_t attackValue = elementDamage; - float attackFactor = player->getAttackFactor(); - uint32_t level = player->getLevel(); + const int32_t attackSkill = player->getWeaponSkill(item); + const int32_t attackValue = elementDamage; + const float attackFactor = player->getAttackFactor(); + const uint32_t level = player->getLevel(); - int32_t maxValue = Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true); - int32_t minValue = level / 5; + const int32_t maxValue = Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true); + const int32_t minValue = level / 5; return -normal_random(minValue, static_cast<int32_t>(maxValue * player->getVocation()->meleeDamageMultiplier)); } @@ -557,16 +557,16 @@ int16_t WeaponMelee::getElementDamageValue() const { return elementDamage; } -int32_t WeaponMelee::getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature>, std::shared_ptr<Item> item, bool maxDamage /*= false*/) const { +int32_t WeaponMelee::getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &, const std::shared_ptr<Item> &item, bool maxDamage /*= false*/) const { using namespace std; - int32_t attackSkill = player->getWeaponSkill(item); - int32_t attackValue = std::max<int32_t>(0, item->getAttack()); - float attackFactor = player->getAttackFactor(); - uint32_t level = player->getLevel(); + const int32_t attackSkill = player->getWeaponSkill(item); + const int32_t attackValue = std::max<int32_t>(0, item->getAttack()); + const float attackFactor = player->getAttackFactor(); + const uint32_t level = player->getLevel(); - int32_t maxValue = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); + const int32_t maxValue = static_cast<int32_t>(Weapons::getMaxWeaponDamage(level, attackSkill, attackValue, attackFactor, true) * player->getVocation()->meleeDamageMultiplier); - int32_t minValue = level / 5; + const int32_t minValue = level / 5; if (maxDamage) { return -maxValue; @@ -601,8 +601,8 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: int32_t damageModifier; const ItemType &it = Item::items[id]; if (it.weaponType == WEAPON_AMMO) { - std::shared_ptr<Item> mainWeaponItem = player->getWeapon(true); - const WeaponShared_ptr mainWeapon = g_weapons().getWeapon(mainWeaponItem); + const auto &mainWeaponItem = player->getWeapon(true); + const WeaponShared_ptr &mainWeapon = g_weapons().getWeapon(mainWeaponItem); if (mainWeapon) { damageModifier = mainWeapon->playerWeaponCheck(player, target, mainWeaponItem->getShootRange()); } else { @@ -619,13 +619,13 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: bool perfectShot = false; const Position &playerPos = player->getPosition(); const Position &targetPos = target->getPosition(); - int32_t distanceX = Position::getDistanceX(targetPos, playerPos); - int32_t distanceY = Position::getDistanceY(targetPos, playerPos); + const int32_t distanceX = Position::getDistanceX(targetPos, playerPos); + const int32_t distanceY = Position::getDistanceY(targetPos, playerPos); int32_t damageX = player->getPerfectShotDamage(distanceX); int32_t damageY = player->getPerfectShotDamage(distanceY); if (it.weaponType == WEAPON_DISTANCE) { - std::shared_ptr<Item> quiver = player->getInventoryItem(CONST_SLOT_RIGHT); + const auto &quiver = player->getInventoryItem(CONST_SLOT_RIGHT); if (quiver && quiver->getWeaponType()) { if (quiver->getPerfectShotRange() == distanceX) { damageX -= quiver->getPerfectShotDamage(); @@ -641,8 +641,8 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: perfectShot = true; } else if (it.hitChance == 0) { // hit chance is based on distance to target and distance skill - uint32_t skill = player->getSkillLevel(SKILL_DISTANCE); - uint32_t distance = std::max<uint32_t>(distanceX, distanceY); + const uint32_t skill = player->getSkillLevel(SKILL_DISTANCE); + const uint32_t distance = std::max<uint32_t>(distanceX, distanceY); uint32_t maxHitChance; if (it.maxHitChance != -1) { @@ -738,7 +738,7 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: } if (!perfectShot && item->getWeaponType() == WEAPON_AMMO) { - std::shared_ptr<Item> bow = player->getWeapon(true); + const auto &bow = player->getWeapon(true); if (bow && bow->getHitChance() != 0) { chance += bow->getHitChance(); } @@ -748,7 +748,7 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: Weapon::internalUseWeapon(player, item, target, damageModifier); } else { // miss target - std::shared_ptr<Tile> destTile = target->getTile(); + auto destTile = target->getTile(); if (!Position::areInRange<1, 1, 0>(player->getPosition(), target->getPosition())) { static std::vector<std::pair<int32_t, int32_t>> destList { @@ -756,11 +756,11 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: }; std::ranges::shuffle(destList.begin(), destList.end(), getRandomGenerator()); - Position destPos = target->getPosition(); + const Position destPos = target->getPosition(); for (const auto &dir : destList) { // Blocking tiles or tiles without ground ain't valid targets for spears - auto tmpTile = g_game().map.getTile(static_cast<uint16_t>(destPos.x + dir.first), static_cast<uint16_t>(destPos.y + dir.second), destPos.z); + const auto &tmpTile = g_game().map.getTile(static_cast<uint16_t>(destPos.x + dir.first), static_cast<uint16_t>(destPos.y + dir.second), destPos.z); if (tmpTile && !tmpTile->hasFlag(TILESTATE_IMMOVABLEBLOCKSOLID) && tmpTile->getGround() != nullptr) { destTile = tmpTile; break; @@ -773,25 +773,25 @@ bool WeaponDistance::useWeapon(const std::shared_ptr<Player> &player, const std: return true; } -int32_t WeaponDistance::getElementDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item) const { +int32_t WeaponDistance::getElementDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item) const { if (elementType == COMBAT_NONE) { return 0; } int32_t attackValue = elementDamage; if (item->getWeaponType() == WEAPON_AMMO) { - std::shared_ptr<Item> weapon = player->getWeapon(true); + const auto &weapon = player->getWeapon(true); if (weapon) { attackValue += item->getAttack(); attackValue += weapon->getAttack(); } } - int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); - float attackFactor = player->getAttackFactor(); + const int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); + const float attackFactor = player->getAttackFactor(); int32_t minValue = std::round(player->getLevel() / 5); - int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; + const int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue) / 2; if (target) { if (target->getPlayer()) { @@ -808,12 +808,12 @@ int16_t WeaponDistance::getElementDamageValue() const { return elementDamage; } -int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item, bool maxDamage /*= false*/) const { +int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage /*= false*/) const { int32_t attackValue = item->getAttack(); bool hasElement = false; if (item->getWeaponType() == WEAPON_AMMO) { - std::shared_ptr<Item> weapon = player->getWeapon(true); + const auto &weapon = player->getWeapon(true); if (weapon) { const ItemType &it = Item::items[item->getID()]; if (it.abilities && it.abilities->elementDamage != 0) { @@ -825,8 +825,8 @@ int32_t WeaponDistance::getWeaponDamage(const std::shared_ptr<Player> &player, s } } - int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); - float attackFactor = player->getAttackFactor(); + const int32_t attackSkill = player->getSkillLevel(SKILL_DISTANCE); + const float attackFactor = player->getAttackFactor(); int32_t minValue = player->getLevel() / 5; int32_t maxValue = std::round((0.09f * attackFactor) * attackSkill * attackValue + minValue); @@ -883,7 +883,7 @@ void WeaponWand::configureWeapon(const ItemType &it) { Weapon::configureWeapon(it); } -int32_t WeaponWand::getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature>, std::shared_ptr<Item>, bool maxDamage /* = false*/) const { +int32_t WeaponWand::getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &, const std::shared_ptr<Item> &, bool maxDamage /* = false*/) const { if (!g_configManager().getBoolean(TOGGLE_CHAIN_SYSTEM, __FUNCTION__)) { // Returns maximum damage or a random value between minChange and maxChange return maxDamage ? -maxChange : -normal_random(minChange, maxChange); @@ -897,19 +897,19 @@ int32_t WeaponWand::getWeaponDamage(const std::shared_ptr<Player> &player, std:: [[maybe_unused]] CombatDamage combatDamage; calculateSkillFormula(player, attackSkill, attackValue, attackFactor, elementAttack, combatDamage); - auto magLevel = player->getMagicLevel(); - auto level = player->getLevel(); + const auto magLevel = player->getMagicLevel(); + const auto level = player->getLevel(); // Check if level is greater than zero before performing division - auto levelDivision = level > 0 ? level / 5.0 : 0.0; + const auto levelDivision = level > 0 ? level / 5.0 : 0.0; - auto totalAttackValue = magLevel + attackValue; + const auto totalAttackValue = magLevel + attackValue; // Check if magLevel is greater than zero before performing division - auto magicLevelDivision = totalAttackValue > 0 ? totalAttackValue / 3.0 : 0.0; + const auto magicLevelDivision = totalAttackValue > 0 ? totalAttackValue / 3.0 : 0.0; - double min = levelDivision + magicLevelDivision; - double max = levelDivision + totalAttackValue; + const double min = levelDivision + magicLevelDivision; + const double max = levelDivision + totalAttackValue; // Returns the calculated maximum damage or a random value between the calculated minimum and maximum return maxDamage ? -max : -normal_random(min, max); diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 5eee699cacb..5e123a12a7c 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -66,8 +66,8 @@ class Weapon : public Script { static bool useFist(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target); virtual bool useWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Creature> &target) const; - virtual int32_t getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item, bool maxDamage = false) const = 0; - virtual int32_t getElementDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item) const = 0; + virtual int32_t getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage = false) const = 0; + virtual int32_t getElementDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item) const = 0; virtual CombatType_t getElementType() const = 0; virtual int16_t getElementDamageValue() const = 0; virtual CombatDamage getCombatDamage(CombatDamage combat, const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, int32_t damageModifier) const; @@ -163,7 +163,7 @@ class Weapon : public Script { } void addVocWeaponMap(const std::string &vocName) { - int32_t vocationId = g_vocations().getVocationId(vocName); + const int32_t vocationId = g_vocations().getVocationId(vocName); if (vocationId != -1) { vocWeaponMap[vocationId] = true; } @@ -286,8 +286,8 @@ class WeaponMelee final : public Weapon { bool useWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Creature> &target) const override; - int32_t getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item, bool maxDamage = false) const override; - int32_t getElementDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item) const override; + int32_t getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage = false) const override; + int32_t getElementDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item) const override; CombatType_t getElementType() const override { return elementType; } @@ -314,8 +314,8 @@ class WeaponDistance final : public Weapon { bool useWeapon(const std::shared_ptr<Player> &player, const std::shared_ptr<Item> &item, const std::shared_ptr<Creature> &target) const override; - int32_t getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item, bool maxDamage = false) const override; - int32_t getElementDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item) const override; + int32_t getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage = false) const override; + int32_t getElementDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item) const override; CombatType_t getElementType() const override { return elementType; } @@ -328,7 +328,7 @@ class WeaponDistance final : public Weapon { uint16_t elementDamage = 0; }; -class WeaponWand final : public Weapon { +class WeaponWand : public Weapon { public: using Weapon::Weapon; @@ -338,8 +338,8 @@ class WeaponWand final : public Weapon { void configureWeapon(const ItemType &it) override; - int32_t getWeaponDamage(const std::shared_ptr<Player> &player, std::shared_ptr<Creature> target, std::shared_ptr<Item> item, bool maxDamage = false) const override; - int32_t getElementDamage(const std::shared_ptr<Player> &, std::shared_ptr<Creature>, std::shared_ptr<Item>) const override { + int32_t getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage = false) const override; + int32_t getElementDamage(const std::shared_ptr<Player> &, const std::shared_ptr<Creature>&, const std::shared_ptr<Item>&) const override { return 0; } CombatType_t getElementType() const override { From fe4113d086707dfb0c5b214d9126f5ddb5b20678 Mon Sep 17 00:00:00 2001 From: GitHub Actions <github-actions[bot]@users.noreply.github.com> Date: Thu, 19 Sep 2024 00:06:02 +0000 Subject: [PATCH 34/34] Code format - (Clang-format) --- src/creatures/players/player.hpp | 2 +- src/items/containers/mailbox/mailbox.cpp | 2 +- src/items/cylinder.hpp | 2 +- src/items/items_classification.hpp | 2 +- src/items/weapons/weapons.hpp | 2 +- src/lua/creature/events.cpp | 2 +- src/lua/functions/core/game/global_functions.cpp | 2 +- src/server/network/message/networkmessage.cpp | 4 ++-- 8 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 1c15e32d449..a7df17c807c 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -2699,7 +2699,7 @@ class Player final : public Creature, public Cylinder, public Bankable { ReturnValue queryRemove(const std::shared_ptr<Thing> &thing, uint32_t count, uint32_t flags, const std::shared_ptr<Creature> &actor = nullptr) override; std::shared_ptr<Cylinder> queryDestination(int32_t &index, const std::shared_ptr<Thing> &thing, std::shared_ptr<Item> &destItem, uint32_t &flags) override; - void addThing(const std::shared_ptr<Thing>&) override { } + void addThing(const std::shared_ptr<Thing> &) override { } void addThing(int32_t index, const std::shared_ptr<Thing> &thing) override; void updateThing(const std::shared_ptr<Thing> &thing, uint16_t itemId, uint32_t count) override; diff --git a/src/items/containers/mailbox/mailbox.cpp b/src/items/containers/mailbox/mailbox.cpp index f6c42f45adf..5be97649f36 100644 --- a/src/items/containers/mailbox/mailbox.cpp +++ b/src/items/containers/mailbox/mailbox.cpp @@ -32,7 +32,7 @@ ReturnValue Mailbox::queryRemove(const std::shared_ptr<Thing> &, uint32_t, uint3 return RETURNVALUE_NOTPOSSIBLE; } -std::shared_ptr<Cylinder> Mailbox::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item>&, uint32_t &) { +std::shared_ptr<Cylinder> Mailbox::queryDestination(int32_t &, const std::shared_ptr<Thing> &, std::shared_ptr<Item> &, uint32_t &) { return getMailbox(); } diff --git a/src/items/cylinder.hpp b/src/items/cylinder.hpp index b4b606a3965..eb01abebeff 100644 --- a/src/items/cylinder.hpp +++ b/src/items/cylinder.hpp @@ -190,7 +190,7 @@ class VirtualCylinder final : public Cylinder { return nullptr; } - virtual void addThing(const std::shared_ptr<Thing>&) override { } + virtual void addThing(const std::shared_ptr<Thing> &) override { } virtual void addThing(int32_t, const std::shared_ptr<Thing> &) override { } virtual void updateThing(const std::shared_ptr<Thing> &, uint16_t, uint32_t) override { } virtual void replaceThing(uint32_t, const std::shared_ptr<Thing> &) override { } diff --git a/src/items/items_classification.hpp b/src/items/items_classification.hpp index 12a6e40e3d0..54521fd7675 100644 --- a/src/items/items_classification.hpp +++ b/src/items/items_classification.hpp @@ -33,5 +33,5 @@ class ItemClassification final { } uint8_t id {}; - std::map<uint8_t, TierInfo> tiers{}; + std::map<uint8_t, TierInfo> tiers {}; }; diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 5e123a12a7c..bbe15e12a7d 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -339,7 +339,7 @@ class WeaponWand : public Weapon { void configureWeapon(const ItemType &it) override; int32_t getWeaponDamage(const std::shared_ptr<Player> &player, const std::shared_ptr<Creature> &target, const std::shared_ptr<Item> &item, bool maxDamage = false) const override; - int32_t getElementDamage(const std::shared_ptr<Player> &, const std::shared_ptr<Creature>&, const std::shared_ptr<Item>&) const override { + int32_t getElementDamage(const std::shared_ptr<Player> &, const std::shared_ptr<Creature> &, const std::shared_ptr<Item> &) const override { return 0; } CombatType_t getElementType() const override { diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 4aa4d7fbfda..f8c743c628a 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -637,7 +637,7 @@ void Events::eventPlayerOnLookInBattleList(const std::shared_ptr<Player> &player scriptInterface.callVoidFunction(3); } -void Events::eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance) { +void Events::eventPlayerOnLookInTrade(const std::shared_ptr<Player> &player, const std::shared_ptr<Player> &partner, const std::shared_ptr<Item> &item, int32_t lookDistance) { // Player:onLookInTrade(partner, item, distance) or Player.onLookInTrade(self, partner, item, distance) if (info.playerOnLookInTrade == -1) { return; diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index df861531764..e5f428ee49f 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -586,7 +586,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { LuaData_t type = getNumber<LuaData_t>(L, -1); if (type != LuaData_t::Unknown && type <= LuaData_t::Npc) { - indexes.emplace_back( i, type ); + indexes.emplace_back(i, type); } lua_pop(globalState, 2); } diff --git a/src/server/network/message/networkmessage.cpp b/src/server/network/message/networkmessage.cpp index fa57693bcdf..8044cf80364 100644 --- a/src/server/network/message/networkmessage.cpp +++ b/src/server/network/message/networkmessage.cpp @@ -85,11 +85,11 @@ void NetworkMessage::addBytes(const char* bytes, size_t size) { } void NetworkMessage::addPaddingBytes(size_t n) { - #define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) +#define canAdd(size) ((size + info.position) < NETWORKMESSAGE_MAXSIZE) if (!canAdd(n)) { return; } - #undef canAdd +#undef canAdd memset(buffer + info.position, 0x33, n); info.length += n;