diff --git a/CMakeLists.txt b/CMakeLists.txt index e4093f4de2d..52c35a471f7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -86,10 +86,9 @@ endif() # === IPO === -option(OPTIONS_ENABLE_IPO "Check and Enable interprocedural optimization (IPO/LTO)" ON) if(OPTIONS_ENABLE_IPO) - log_option_enabled("IPO/LTO") if(MSVC) + log_option_enabled("IPO/LTO") set(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} /GL") set(CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_SHARED_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") set(CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_STATIC_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") @@ -97,6 +96,7 @@ if(OPTIONS_ENABLE_IPO) set(CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO "${CMAKE_EXE_LINKER_FLAGS_RELWITHDEBINFO} /LTCG") else() if(CMAKE_BUILD_TYPE STREQUAL "RelWithDebInfo" OR CMAKE_BUILD_TYPE STREQUAL "Release") + log_option_enabled("IPO/LTO") include(CheckIPOSupported) check_ipo_supported(RESULT result OUTPUT output) if(result) diff --git a/cmake/modules/BaseConfig.cmake b/cmake/modules/BaseConfig.cmake index 7e3f6404b3f..a1980d0f604 100644 --- a/cmake/modules/BaseConfig.cmake +++ b/cmake/modules/BaseConfig.cmake @@ -121,7 +121,9 @@ if (MSVC) endforeach(type) add_compile_options(/MP /FS /Zf /EHsc) -endif (MSVC) +else() + add_compile_options(-Wno-unused-parameter -Wno-sign-compare -Wno-switch -Wno-implicit-fallthrough -Wno-extra) +endif() ## Link compilation files to build/bin folder, else link to the main dir function(set_output_directory target_name) diff --git a/src/canary_server.cpp b/src/canary_server.cpp index bfabbf51ab8..17a36ff3d23 100644 --- a/src/canary_server.cpp +++ b/src/canary_server.cpp @@ -327,7 +327,7 @@ void CanaryServer::loadModules() { // 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__); - if (!useAnyDatapack && (datapackName != "data-canary" && datapackName != "data-otservbr-global" || datapackName != "data-otservbr-global" && datapackName != "data-canary")) { + if (!useAnyDatapack && datapackName != "data-canary" && datapackName != "data-otservbr-global") { throw FailedToInitializeCanary(fmt::format( "The datapack folder name '{}' is wrong, please select valid " "datapack name 'data-canary' or 'data-otservbr-global " diff --git a/src/canary_server.hpp b/src/canary_server.hpp index bb22232b8e4..57c931cd133 100644 --- a/src/canary_server.hpp +++ b/src/canary_server.hpp @@ -46,8 +46,8 @@ class CanaryServer { FAILED }; - RSA &rsa; Logger &logger; + RSA &rsa; ServiceManager &serviceManager; std::atomic loaderStatus = LoaderStatus::LOADING; diff --git a/src/config/configmanager.cpp b/src/config/configmanager.cpp index 0525c5a560a..37634abf514 100644 --- a/src/config/configmanager.cpp +++ b/src/config/configmanager.cpp @@ -11,7 +11,6 @@ #include "config/configmanager.hpp" #include "lib/di/container.hpp" -#include "declarations.hpp" #include "game/game.hpp" #include "server/network/webhook/webhook.hpp" diff --git a/src/creatures/appearance/mounts/mounts.cpp b/src/creatures/appearance/mounts/mounts.cpp index dff0f02a451..7051d04ddb8 100644 --- a/src/creatures/appearance/mounts/mounts.cpp +++ b/src/creatures/appearance/mounts/mounts.cpp @@ -35,7 +35,7 @@ bool Mounts::loadFromXml() { continue; } - mounts.emplace_back(std::make_shared( + mounts.emplace(std::make_shared( static_cast(pugi::cast(mountNode.attribute("id").value())), lookType, mountNode.attribute("name").as_string(), @@ -44,12 +44,11 @@ bool Mounts::loadFromXml() { mountNode.attribute("type").as_string() )); } - mounts.shrink_to_fit(); return true; } std::shared_ptr Mounts::getMountByID(uint8_t id) { - auto it = std::find_if(mounts.begin(), mounts.end(), [id](const std::shared_ptr mount) { + auto it = std::find_if(mounts.begin(), mounts.end(), [id](const std::shared_ptr &mount) { return mount->id == id; // Note the use of -> operator to access the members of the Mount object }); @@ -58,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) { + auto it = std::find_if(mounts.begin(), mounts.end(), [mountName](const std::shared_ptr &mount) { return strcasecmp(mountName, mount->name.c_str()) == 0; }); @@ -66,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) { + auto it = std::find_if(mounts.begin(), mounts.end(), [clientId](const std::shared_ptr &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 05bd330a66b..ca4f969842a 100644 --- a/src/creatures/appearance/mounts/mounts.hpp +++ b/src/creatures/appearance/mounts/mounts.hpp @@ -11,8 +11,8 @@ struct Mount { Mount(uint8_t initId, uint16_t initClientId, std::string initName, int32_t initSpeed, bool initPremium, std::string initType) : - name(initName), speed(initSpeed), clientId(initClientId), id(initId), premium(initPremium), - type(initType) { } + name(std::move(initName)), speed(initSpeed), clientId(initClientId), id(initId), premium(initPremium), + type(std::move(initType)) { } std::string name; int32_t speed; @@ -30,10 +30,10 @@ class Mounts { std::shared_ptr getMountByName(const std::string &name); std::shared_ptr getMountByClientID(uint16_t clientId); - [[nodiscard]] const std::vector> &getMounts() const { + [[nodiscard]] const phmap::parallel_flat_hash_set> &getMounts() const { return mounts; } private: - std::vector> mounts; + phmap::parallel_flat_hash_set> mounts; }; diff --git a/src/creatures/appearance/outfit/outfit.cpp b/src/creatures/appearance/outfit/outfit.cpp index 6f0490339de..9e96c60e756 100644 --- a/src/creatures/appearance/outfit/outfit.cpp +++ b/src/creatures/appearance/outfit/outfit.cpp @@ -14,6 +14,13 @@ #include "utils/tools.hpp" #include "game/game.hpp" +bool Outfits::reload() { + for (auto &outfitsVector : outfits) { + outfitsVector.clear(); + } + return loadFromXml(); +} + bool Outfits::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/outfits.xml"; @@ -68,10 +75,12 @@ bool Outfits::loadFromXml() { } std::shared_ptr Outfits::getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const { - for (const auto &outfit : outfits[sex]) { - if (outfit->lookType == lookType) { - return outfit; - } + auto it = std::ranges::find_if(outfits[sex], [&lookType](const auto &outfit) { + return outfit->lookType == lookType; + }); + + if (it != outfits[sex].end()) { + return *it; } return nullptr; } @@ -83,17 +92,7 @@ std::shared_ptr Outfits::getOutfitByLookType(PlayerSex_t sex, uint16_t l * @return const pointer to the outfit or nullptr if it could not be found. */ -std::shared_ptr Outfits::getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType) { +std::shared_ptr Outfits::getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const { PlayerSex_t searchSex = (sex == PLAYERSEX_MALE) ? PLAYERSEX_FEMALE : PLAYERSEX_MALE; - - for (uint16_t i = 0; i < outfits[sex].size(); i++) { - if (outfits[sex].at(i)->lookType == lookType) { - if (outfits[searchSex].size() > i) { - return outfits[searchSex].at(i); - } else { // looktype found but the oposite sex array doesn't have this index. - return nullptr; - } - } - } - return nullptr; + return getOutfitByLookType(searchSex, lookType); } diff --git a/src/creatures/appearance/outfit/outfit.hpp b/src/creatures/appearance/outfit/outfit.hpp index e1a5143c673..30b84d1aca2 100644 --- a/src/creatures/appearance/outfit/outfit.hpp +++ b/src/creatures/appearance/outfit/outfit.hpp @@ -12,9 +12,17 @@ #include "declarations.hpp" #include "lib/di/container.hpp" +struct OutfitEntry { + constexpr OutfitEntry(uint16_t initLookType, uint8_t initAddons) : + lookType(initLookType), addons(initAddons) { } + + uint16_t lookType; + uint8_t addons; +}; + struct Outfit { Outfit(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initFrom) : - name(initName), lookType(initLookType), premium(initPremium), unlocked(initUnlocked), from(initFrom) { } + name(std::move(initName)), lookType(initLookType), premium(initPremium), unlocked(initUnlocked), from(std::move(initFrom)) { } std::string name; uint16_t lookType; @@ -38,9 +46,10 @@ class Outfits { return inject(); } - std::shared_ptr getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType); + std::shared_ptr getOpositeSexOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const; bool loadFromXml(); + bool reload(); [[nodiscard]] std::shared_ptr getOutfitByLookType(PlayerSex_t sex, uint16_t lookType) const; [[nodiscard]] const std::vector> &getOutfits(PlayerSex_t sex) const { diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 06812095cbf..2aaadac4d61 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -287,7 +287,7 @@ bool Combat::isProtected(std::shared_ptr attacker, std::shared_ptrgetVocation()->canCombat() || !target->getVocation()->canCombat() && (attacker->getVocationId() == VOCATION_NONE || target->getVocationId() == VOCATION_NONE)) { + if ((!attacker->getVocation()->canCombat() || !target->getVocation()->canCombat()) && (attacker->getVocationId() == VOCATION_NONE || target->getVocationId() == VOCATION_NONE)) { return true; } @@ -707,7 +707,7 @@ bool Combat::checkFearConditionAffected(std::shared_ptr player) { auto affectedCount = (party->getMemberCount() + 5) / 5; g_logger().debug("[{}] Player is member of a party, {} members can be feared", __FUNCTION__, affectedCount); - for (const auto member : party->getMembers()) { + for (const auto &member : party->getMembers()) { if (member->hasCondition(CONDITION_FEARED)) { affectedCount -= 1; } @@ -759,7 +759,7 @@ void Combat::CombatConditionFunc(std::shared_ptr caster, std::shared_p } } - if (caster == target || target && !target->isImmune(condition->getType())) { + if (caster == target || (target && !target->isImmune(condition->getType()))) { auto conditionCopy = condition->clone(); if (caster) { conditionCopy->setParam(CONDITION_PARAM_OWNER, caster->getID()); @@ -1030,10 +1030,10 @@ bool Combat::doCombatChain(std::shared_ptr caster, std::shared_ptrgetChainValues(caster, maxTargets, chainDistance, backtracking); - auto targets = pickChainTargets(caster, params, chainDistance, maxTargets, backtracking, aggressive, target); + auto targets = pickChainTargets(caster, params, chainDistance, maxTargets, aggressive, backtracking, std::move(target)); g_logger().debug("[{}] Chain targets: {}", __FUNCTION__, targets.size()); - if (targets.empty() || targets.size() == 1 && targets.begin()->second.empty()) { + if (targets.empty() || (targets.size() == 1 && targets.begin()->second.empty())) { return false; } @@ -1122,7 +1122,7 @@ void Combat::CombatFunc(std::shared_ptr caster, const Position &origin uint32_t maxY = 0; // calculate the max viewable range - for (std::shared_ptr tile : tileList) { + for (const std::shared_ptr &tile : tileList) { const Position &tilePos = tile->getPosition(); uint32_t diff = Position::getDistanceX(tilePos, pos); @@ -1140,7 +1140,7 @@ void Combat::CombatFunc(std::shared_ptr caster, const Position &origin const int32_t rangeY = maxY + MAP_MAX_VIEW_PORT_Y; int affected = 0; - for (std::shared_ptr tile : tileList) { + for (const std::shared_ptr &tile : tileList) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } @@ -1195,7 +1195,7 @@ void Combat::CombatFunc(std::shared_ptr caster, const Position &origin uint8_t beamAffectedCurrent = 0; tmpDamage.affected = affected; - for (std::shared_ptr tile : tileList) { + for (const std::shared_ptr &tile : tileList) { if (canDoCombat(caster, tile, params.aggressive) != RETURNVALUE_NOERROR) { continue; } @@ -1241,7 +1241,7 @@ void Combat::CombatFunc(std::shared_ptr caster, const Position &origin } void Combat::doCombatHealth(std::shared_ptr caster, std::shared_ptr target, CombatDamage &damage, const CombatParams ¶ms) { - doCombatHealth(caster, target, caster ? caster->getPosition() : Position(), damage, params); + doCombatHealth(caster, std::move(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) { @@ -1382,7 +1382,7 @@ void Combat::doCombatDispel(std::shared_ptr caster, std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms) { +[[maybe_unused]] void Combat::doCombatDefault(std::shared_ptr caster, std::shared_ptr target, const CombatParams ¶ms) { doCombatDefault(caster, target, caster ? caster->getPosition() : Position(), params); } @@ -2076,7 +2076,7 @@ void AreaCombat::setupExtArea(const std::list &list, uint32_t rows) { void MagicField::onStepInField(const std::shared_ptr &creature) { // remove magic walls/wild growth - if (!isBlocking() && g_game().getWorldType() == WORLD_TYPE_NO_PVP && id == ITEM_MAGICWALL_SAFE || id == ITEM_WILDGROWTH_SAFE) { + if ((!isBlocking() && g_game().getWorldType() == WORLD_TYPE_NO_PVP && id == ITEM_MAGICWALL_SAFE) || id == ITEM_WILDGROWTH_SAFE) { if (!creature->isInGhostMode()) { g_game().internalRemoveItem(static_self_cast(), 1); } @@ -2091,7 +2091,7 @@ void MagicField::onStepInField(const std::shared_ptr &creature) { if (ownerId) { bool harmfulField = true; auto itemTile = getTile(); - if (g_game().getWorldType() == WORLD_TYPE_NO_PVP || itemTile && itemTile->hasFlag(TILESTATE_NOPVPZONE)) { + if (g_game().getWorldType() == WORLD_TYPE_NO_PVP || (itemTile && itemTile->hasFlag(TILESTATE_NOPVPZONE))) { auto ownerPlayer = g_game().getPlayerByGUID(ownerId); if (ownerPlayer) { harmfulField = false; diff --git a/src/creatures/combat/combat.hpp b/src/creatures/combat/combat.hpp index 6a79455c7c4..93b02502f25 100644 --- a/src/creatures/combat/combat.hpp +++ b/src/creatures/combat/combat.hpp @@ -72,8 +72,8 @@ class ChainCallback final : public CallBack { private: void onChainCombat(std::shared_ptr creature, uint8_t &chainTargets, uint8_t &chainDistance, bool &backtracking); - uint8_t m_chainTargets = 0; uint8_t m_chainDistance = 0; + uint8_t m_chainTargets = 0; bool m_backtracking = false; bool m_fromLua = false; }; @@ -125,7 +125,7 @@ class MatrixArea { data_[row] = new bool[cols]; for (uint32_t col = 0; col < cols; ++col) { - data_[row][col] = 0; + data_[row][col] = false; } } } @@ -324,7 +324,7 @@ class Combat { } 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(caster, origin, pos, params); + postCombatEffects(std::move(caster), origin, pos, params); } void setOrigin(CombatOrigin origin) { @@ -393,7 +393,7 @@ class Combat { * @param damage The combat damage. * @return The calculated level formula. */ - int32_t getLevelFormula(std::shared_ptr player, const std::shared_ptr wheelSpell, const CombatDamage &damage) const; + 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; // configureable diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 56c67700d13..7f477f1d859 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -1472,7 +1472,7 @@ bool ConditionDamage::unserializeProp(ConditionAttr_t attr, PropStream &propStre } else if (attr == CONDITIONATTR_OWNER) { return propStream.skip(4); } else if (attr == CONDITIONATTR_INTERVALDATA) { - IntervalInfo damageInfo; + IntervalInfo damageInfo {}; if (!propStream.read(damageInfo)) { return false; } @@ -1530,7 +1530,7 @@ bool ConditionDamage::addDamage(int32_t rounds, int32_t time, int32_t value) { // rounds, time, damage for (int32_t i = 0; i < rounds; ++i) { - IntervalInfo damageInfo; + IntervalInfo damageInfo {}; damageInfo.interval = time; damageInfo.timeLeft = time; damageInfo.value = value; @@ -1803,13 +1803,9 @@ void ConditionDamage::generateDamageList(int32_t amount, int32_t start, std::lis * ConditionFeared */ bool ConditionFeared::isStuck(std::shared_ptr creature, Position pos) const { - for (Direction dir : m_directionsVector) { - if (canWalkTo(creature, pos, dir)) { - return false; - } - } - - return true; + return std::ranges::all_of(m_directionsVector, [&](Direction dir) { + return !canWalkTo(creature, pos, dir); + }); } bool ConditionFeared::getRandomDirection(std::shared_ptr creature, Position pos) { @@ -1995,6 +1991,8 @@ bool ConditionFeared::getFleePath(std::shared_ptr creature, const Posi futurePos.y -= wsize; g_logger().debug("[{}] Trying to flee to NORTHWEST to {} [{}]", __FUNCTION__, futurePos.toString(), wsize); break; + case DIRECTION_NONE: + break; } found = creature->getPathTo(futurePos, dirList, 0, 30); diff --git a/src/creatures/combat/condition.hpp b/src/creatures/combat/condition.hpp index 539a8711723..07b31b42d15 100644 --- a/src/creatures/combat/condition.hpp +++ b/src/creatures/combat/condition.hpp @@ -27,7 +27,7 @@ class Condition : public SharedObject { virtual bool startCondition(std::shared_ptr creature); virtual bool executeCondition(std::shared_ptr creature, int32_t interval); virtual void endCondition(std::shared_ptr creature) = 0; - virtual void addCondition(std::shared_ptr creature, const std::shared_ptr condition) = 0; + virtual void addCondition(std::shared_ptr creature, std::shared_ptr condition) = 0; virtual uint32_t getIcons() const; ConditionId_t getId() const { return id; @@ -65,14 +65,14 @@ class Condition : public SharedObject { protected: uint8_t drainBodyStage = 0; - int64_t endTime; - uint32_t subId; - int32_t ticks; - ConditionType_t conditionType; - ConditionId_t id; - bool isBuff; + int64_t endTime {}; + uint32_t subId {}; + int32_t ticks {}; + ConditionType_t conditionType {}; + ConditionId_t id {}; + bool isBuff {}; - virtual bool updateCondition(const std::shared_ptr addCondition); + virtual bool updateCondition(std::shared_ptr addCondition); private: SoundEffect_t tickSound = SoundEffect_t::SILENCE; @@ -90,7 +90,7 @@ class ConditionGeneric : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; uint32_t getIcons() const override; std::shared_ptr clone() const override { @@ -106,7 +106,7 @@ class ConditionAttributes final : public ConditionGeneric { bool startCondition(std::shared_ptr creature) final; bool executeCondition(std::shared_ptr creature, int32_t interval) final; void endCondition(std::shared_ptr creature) final; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) final; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) final; bool setParam(ConditionParam_t param, int32_t value) final; @@ -172,7 +172,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, const std::shared_ptr addCondition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; @@ -205,7 +205,7 @@ class ConditionManaShield final : public Condition { bool startCondition(std::shared_ptr creature) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr addCondition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; uint32_t getIcons() const override; bool setParam(ConditionParam_t param, int32_t value) override; @@ -227,7 +227,7 @@ class ConditionSoul final : public ConditionGeneric { ConditionSoul(ConditionId_t initId, ConditionType_t initType, int32_t iniTicks, bool initBuff = false, uint32_t initSubId = 0) : ConditionGeneric(initId, initType, iniTicks, initBuff, initSubId) { } - void addCondition(std::shared_ptr creature, const std::shared_ptr addCondition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; bool setParam(ConditionParam_t param, int32_t value) override; @@ -270,7 +270,7 @@ class ConditionDamage final : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; uint32_t getIcons() const override; std::shared_ptr clone() const override { @@ -309,7 +309,7 @@ class ConditionDamage final : public Condition { bool getNextDamage(int32_t &damage); bool doDamage(std::shared_ptr creature, int32_t healthChange); - bool updateCondition(const std::shared_ptr addCondition) override; + bool updateCondition(std::shared_ptr addCondition) override; }; class ConditionFeared final : public Condition { @@ -321,7 +321,7 @@ class ConditionFeared final : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; uint32_t getIcons() const override; std::shared_ptr clone() const override { @@ -360,7 +360,7 @@ class ConditionSpeed final : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; uint32_t getIcons() const override; std::shared_ptr clone() const override { @@ -395,7 +395,7 @@ class ConditionOutfit final : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::shared_ptr clone() const override { return std::make_shared(*this); @@ -421,7 +421,7 @@ class ConditionLight final : public Condition { bool startCondition(std::shared_ptr creature) override; bool executeCondition(std::shared_ptr creature, int32_t interval) override; void endCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr addCondition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr addCondition) override; std::shared_ptr clone() const override { return std::make_shared(*this); @@ -445,7 +445,7 @@ class ConditionSpellCooldown final : public ConditionGeneric { ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::shared_ptr clone() const override { return std::make_shared(*this); @@ -458,7 +458,7 @@ class ConditionSpellGroupCooldown final : public ConditionGeneric { ConditionGeneric(initId, initType, initTicks, initBuff, initSubId) { } bool startCondition(std::shared_ptr creature) override; - void addCondition(std::shared_ptr creature, const std::shared_ptr condition) override; + void addCondition(std::shared_ptr creature, std::shared_ptr condition) override; std::shared_ptr clone() const override { return std::make_shared(*this); diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index 3aa445b34aa..dd4305de14e 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -766,7 +766,6 @@ uint32_t Spell::getManaCost(std::shared_ptr player) const { if (manaPercent != 0) { uint32_t maxMana = player->getMaxMana(); uint32_t manaCost = (maxMana * manaPercent) / 100; - WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); if (manaRedution > manaCost) { return 0; } @@ -789,7 +788,7 @@ bool InstantSpell::playerCastInstant(std::shared_ptr player, std::string var.type = VARIANT_NUMBER; var.number = player->getID(); } else if (needTarget || casterTargetOrDirection) { - std::shared_ptr target = nullptr; + std::shared_ptr target; bool useDirection = false; if (hasParam) { @@ -1085,7 +1084,7 @@ bool RuneSpell::castSpell(std::shared_ptr creature, std::shared_ptr creature, const LuaVariant &var, bool isHotkey) { bool result; if (isLoadedCallback()) { - result = executeCastSpell(creature, var, isHotkey); + result = executeCastSpell(std::move(creature), var, isHotkey); } else { result = false; } diff --git a/src/creatures/combat/spells.hpp b/src/creatures/combat/spells.hpp index dce7b3caba4..fc23bbf9030 100644 --- a/src/creatures/combat/spells.hpp +++ b/src/creatures/combat/spells.hpp @@ -63,8 +63,8 @@ class Spells final : public Scripts { } void clear(); - bool registerInstantLuaEvent(const std::shared_ptr instant); - bool registerRuneLuaEvent(const std::shared_ptr rune); + bool registerInstantLuaEvent(std::shared_ptr instant); + bool registerRuneLuaEvent(std::shared_ptr rune); private: std::map> runes; @@ -92,7 +92,7 @@ class BaseSpell { class CombatSpell final : public Script, public BaseSpell, public std::enable_shared_from_this { public: // Constructor - CombatSpell(const std::shared_ptr newCombat, bool newNeedTarget, bool newNeedDirection); + CombatSpell(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; diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index fd78e33ecf4..43e7ab89ccf 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -125,7 +125,7 @@ void Creature::onThink(uint32_t interval) { auto onThink = [self = getCreature(), interval] { // scripting event - onThink const auto &thinkEvents = self->getCreatureEvents(CREATURE_EVENT_THINK); - for (const auto creatureEventPtr : thinkEvents) { + for (const auto &creatureEventPtr : thinkEvents) { creatureEventPtr->executeOnThink(self->static_self_cast(), interval); } }; @@ -299,7 +299,7 @@ void Creature::updateTileCache(std::shared_ptr upTile, const Position &pos if (pos.z == myPos.z) { int32_t dx = Position::getOffsetX(pos, myPos); int32_t dy = Position::getOffsetY(pos, myPos); - updateTileCache(upTile, dx, dy); + updateTileCache(std::move(upTile), dx, dy); } } @@ -332,7 +332,7 @@ int32_t Creature::getWalkCache(const Position &pos) { void Creature::onAddTileItem(std::shared_ptr tileItem, const Position &pos) { if (isMapLoaded && pos.z == getPosition().z) { - updateTileCache(tileItem, pos); + updateTileCache(std::move(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(updateTile, pos); + updateTileCache(std::move(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(updateTile, pos); + updateTileCache(std::move(updateTile), pos); } } } @@ -439,7 +439,7 @@ void Creature::checkSummonMove(const Position &newPos, bool teleportSummon) { // 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); - if (monster && monster->isFamiliar() && checkSummonDist || teleportSummon && !protectionZoneCheck && checkSummonDist) { + if ((monster && monster->isFamiliar() && checkSummonDist) || (teleportSummon && !protectionZoneCheck && checkSummonDist)) { const auto &creatureMaster = summon->getMaster(); if (!creatureMaster) { continue; @@ -709,7 +709,7 @@ void Creature::onDeath() { } } - bool killedByPlayer = mostDamageCreature && mostDamageCreature->getPlayer() || mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer(); + bool killedByPlayer = (mostDamageCreature && mostDamageCreature->getPlayer()) || (mostDamageCreatureMaster && mostDamageCreatureMaster->getPlayer()); if (getPlayer()) { g_metrics().addCounter( "player_death", @@ -761,7 +761,7 @@ bool Creature::dropCorpse(std::shared_ptr lastHitCreature, std::shared if (getMaster()) { // Scripting event onDeath const CreatureEventList &deathEvents = getCreatureEvents(CREATURE_EVENT_DEATH); - for (const auto deathEventPtr : deathEvents) { + for (const auto &deathEventPtr : deathEvents) { deathEventPtr->executeOnDeath(static_self_cast(), nullptr, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } } @@ -834,7 +834,7 @@ bool Creature::dropCorpse(std::shared_ptr lastHitCreature, std::shared } // Scripting event onDeath - for (const auto deathEventPtr : getCreatureEvents(CREATURE_EVENT_DEATH)) { + for (const auto &deathEventPtr : getCreatureEvents(CREATURE_EVENT_DEATH)) { if (deathEventPtr) { deathEventPtr->executeOnDeath(static_self_cast(), corpse, lastHitCreature, mostDamageCreature, lastHitUnjustified, mostDamageUnjustified); } @@ -1169,7 +1169,7 @@ double Creature::getDamageRatio(std::shared_ptr attacker) const { } uint64_t Creature::getGainedExperience(std::shared_ptr attacker) const { - return std::floor(getDamageRatio(attacker) * getLostExperience()); + return std::floor(getDamageRatio(std::move(attacker)) * getLostExperience()); } void Creature::addDamagePoints(std::shared_ptr attacker, int32_t damagePoints) { @@ -1181,7 +1181,7 @@ void Creature::addDamagePoints(std::shared_ptr attacker, int32_t damag auto it = damageMap.find(attackerId); if (it == damageMap.end()) { - CountBlock_t cb; + CountBlock_t cb {}; cb.ticks = OTSYS_TIME(); cb.total = damagePoints; damageMap[attackerId] = cb; @@ -1247,7 +1247,7 @@ void Creature::onTickCondition(ConditionType_t type, bool &bRemove) { } void Creature::onCombatRemoveCondition(std::shared_ptr condition) { - removeCondition(condition); + removeCondition(std::move(condition)); } void Creature::onAttacked() { @@ -1275,7 +1275,7 @@ bool Creature::deprecatedOnKilledCreature(std::shared_ptr target, bool // scripting event - onKill const CreatureEventList &killEvents = getCreatureEvents(CREATURE_EVENT_KILL); - for (const auto killEventPtr : killEvents) { + for (const auto &killEventPtr : killEvents) { killEventPtr->executeOnKill(static_self_cast(), target, lastHit); } return false; @@ -1293,7 +1293,7 @@ void Creature::onGainExperience(uint64_t gainExp, std::shared_ptr targ gainExp /= 2; } - master->onGainExperience(gainExp, target); + master->onGainExperience(gainExp, std::move(target)); if (!m->isFamiliar()) { auto spectators = Spectators().find(position); @@ -1574,7 +1574,7 @@ void Creature::setSpeed(int32_t varSpeedDelta) { } void Creature::setCreatureLight(LightInfo lightInfo) { - internalLight = std::move(lightInfo); + internalLight = lightInfo; } void Creature::setNormalCreatureLight() { @@ -1589,7 +1589,7 @@ bool Creature::registerCreatureEvent(const std::string &name) { CreatureEventType_t type = event->getEventType(); if (hasEventRegistered(type)) { - for (const auto creatureEventPtr : eventsList) { + for (const auto &creatureEventPtr : eventsList) { if (creatureEventPtr == event) { return false; } @@ -1642,7 +1642,7 @@ CreatureEventList Creature::getCreatureEvents(CreatureEventType_t type) { return tmpEventList; } - for (const auto creatureEventPtr : eventsList) { + for (const auto &creatureEventPtr : eventsList) { if (creatureEventPtr->getEventType() == type) { tmpEventList.push_back(creatureEventPtr); } @@ -1727,7 +1727,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::find_if(conditions.begin(), conditions.end(), [](const std::shared_ptr &condition) { return condition->getType() == CONDITION_INVISIBLE; }) != conditions.end(); diff --git a/src/creatures/creature.hpp b/src/creatures/creature.hpp index 2c92032bd65..670d5f3d688 100644 --- a/src/creatures/creature.hpp +++ b/src/creatures/creature.hpp @@ -400,13 +400,13 @@ class Creature : virtual public Thing, public SharedObject { void executeConditions(uint32_t interval); bool hasCondition(ConditionType_t type, uint32_t subId = 0) const; - virtual bool isImmune(CombatType_t type) const { + virtual bool isImmune([[maybe_unused]] CombatType_t type) const { return false; } - virtual bool isImmune(ConditionType_t type) const { + virtual bool isImmune([[maybe_unused]] ConditionType_t type) const { return false; } - virtual bool isSuppress(ConditionType_t type, bool attackerPlayer) const { + virtual bool isSuppress([[maybe_unused]] ConditionType_t type, [[maybe_unused]] bool attackerPlayer) const { return false; }; @@ -424,7 +424,7 @@ class Creature : virtual public Thing, public SharedObject { virtual void drainHealth(std::shared_ptr attacker, int32_t damage); virtual void drainMana(std::shared_ptr attacker, int32_t manaLoss); - virtual bool challengeCreature(std::shared_ptr, int targetChangeCooldown) { + virtual bool challengeCreature(std::shared_ptr, [[maybe_unused]] int targetChangeCooldown) { return false; } @@ -448,10 +448,10 @@ class Creature : virtual public Thing, public SharedObject { * @deprecated -- This is here to trigger the deprecated onKill events in lua */ bool deprecatedOnKilledCreature(std::shared_ptr target, bool lastHit); - virtual bool onKilledPlayer(const std::shared_ptr &target, bool lastHit) { + virtual bool onKilledPlayer([[maybe_unused]] const std::shared_ptr &target, [[maybe_unused]] bool lastHit) { return false; }; - virtual bool onKilledMonster(const std::shared_ptr &target) { + virtual bool onKilledMonster([[maybe_unused]] const std::shared_ptr &target) { return false; }; virtual void onGainExperience(uint64_t gainExp, std::shared_ptr target); diff --git a/src/creatures/creatures_definitions.hpp b/src/creatures/creatures_definitions.hpp index 46fb5fe5979..136f587a64a 100644 --- a/src/creatures/creatures_definitions.hpp +++ b/src/creatures/creatures_definitions.hpp @@ -124,7 +124,7 @@ enum ConditionType_t : uint8_t { // constexpr definiting suppressible conditions constexpr bool IsConditionSuppressible(ConditionType_t condition) { - constexpr ConditionType_t suppressibleConditions[] = { + constexpr std::array suppressibleConditions = { CONDITION_POISON, CONDITION_FIRE, CONDITION_ENERGY, @@ -135,13 +135,9 @@ constexpr bool IsConditionSuppressible(ConditionType_t condition) { CONDITION_CURSED, }; - for (const auto &suppressibleCondition : suppressibleConditions) { - if (condition == suppressibleCondition) { - return true; - } - } - - return false; + return std::ranges::any_of(suppressibleConditions, [condition](const auto &suppressibleCondition) { + return condition == suppressibleCondition; + }); } enum ConditionParam_t { @@ -1415,20 +1411,6 @@ struct VIPEntry { bool notify; }; -struct OutfitEntry { - constexpr OutfitEntry(uint16_t initLookType, uint8_t initAddons) : - lookType(initLookType), addons(initAddons) { } - - uint16_t lookType; - uint8_t addons; -}; - -struct FamiliarEntry { - constexpr explicit FamiliarEntry(uint16_t initLookType) : - lookType(initLookType) { } - uint16_t lookType; -}; - struct Skill { uint64_t tries = 0; uint16_t level = 10; @@ -1539,19 +1521,6 @@ using ItemsTierCountList = std::map>; | ... */ -struct Familiar { - Familiar(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initType) : - name(initName), lookType(initLookType), - premium(initPremium), unlocked(initUnlocked), - type(initType) { } - - std::string name; - uint16_t lookType; - bool premium; - bool unlocked; - std::string type; -}; - struct ProtocolFamiliars { ProtocolFamiliars(const std::string &initName, uint16_t initLookType) : name(initName), lookType(initLookType) { } @@ -1654,18 +1623,11 @@ struct ShopBlock { int32_t itemStorageValue; std::vector childShop; - ShopBlock() { - itemId = 0; - itemName = ""; - itemSubType = 0; - itemBuyPrice = 0; - itemSellPrice = 0; - itemStorageKey = 0; - itemStorageValue = 0; - } + ShopBlock() : + itemId(0), itemName(""), itemSubType(0), itemBuyPrice(0), itemSellPrice(0), itemStorageKey(0), itemStorageValue(0) { } - explicit ShopBlock(uint16_t newItemId, int32_t newSubType = 0, uint32_t newBuyPrice = 0, uint32_t newSellPrice = 0, int32_t newStorageKey = 0, int32_t newStorageValue = 0, std::string newName = "") : - itemId(newItemId), itemSubType(newSubType), itemBuyPrice(newBuyPrice), itemSellPrice(newSellPrice), itemStorageKey(newStorageKey), itemStorageValue(newStorageValue), itemName(std::move(newName)) { } + 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) { } bool operator==(const ShopBlock &other) const { return itemId == other.itemId && itemName == other.itemName && itemSubType == other.itemSubType && itemBuyPrice == other.itemBuyPrice && itemSellPrice == other.itemSellPrice && itemStorageKey == other.itemStorageKey && itemStorageValue == other.itemStorageValue && childShop == other.childShop; diff --git a/src/creatures/interactions/chat.hpp b/src/creatures/interactions/chat.hpp index 022b3f540a1..3643086184c 100644 --- a/src/creatures/interactions/chat.hpp +++ b/src/creatures/interactions/chat.hpp @@ -71,7 +71,7 @@ class ChatChannel { int32_t onLeaveEvent = -1; int32_t onSpeakEvent = -1; - uint16_t id; + uint16_t id {}; bool publicChannel = false; friend class Chat; @@ -79,8 +79,8 @@ class ChatChannel { class PrivateChatChannel final : public ChatChannel { public: - PrivateChatChannel(uint16_t channelId, std::string channelName) : - ChatChannel(channelId, channelName) { } + PrivateChatChannel(uint16_t channelId, [[maybe_unused]] std::string channelName) : + ChatChannel(channelId, std::move(channelName)) { } uint32_t getOwner() const override { return owner; diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index f15616d6af5..fccc19b05e5 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -385,7 +385,7 @@ void Monster::onCreatureFound(std::shared_ptr creature, bool pushFront } void Monster::onCreatureEnter(std::shared_ptr creature) { - onCreatureFound(creature, true); + onCreatureFound(std::move(creature), true); } bool Monster::isFriend(const std::shared_ptr &creature) const { @@ -701,7 +701,7 @@ void Monster::updateIdleStatus() { isWalkingBack = true; } } else if (const auto &master = getMaster()) { - if ((!isSummon() && totalPlayersOnScreen == 0 || isSummon() && master->getMonster() && master->getMonster()->totalPlayersOnScreen == 0) && getFaction() != FACTION_DEFAULT) { + if (((!isSummon() && totalPlayersOnScreen == 0) || (isSummon() && master->getMonster() && master->getMonster()->totalPlayersOnScreen == 0)) && getFaction() != FACTION_DEFAULT) { idle = true; } } @@ -838,7 +838,7 @@ void Monster::doAttacking(uint32_t interval) { for (const spellBlock_t &spellBlock : mType->info.attackSpells) { bool inRange = false; - if (spellBlock.spell == nullptr || spellBlock.isMelee && isFleeing()) { + if (spellBlock.spell == nullptr || (spellBlock.isMelee && isFleeing())) { continue; } diff --git a/src/creatures/monsters/monster.hpp b/src/creatures/monsters/monster.hpp index edf3874161d..bf9a39e4133 100644 --- a/src/creatures/monsters/monster.hpp +++ b/src/creatures/monsters/monster.hpp @@ -15,7 +15,6 @@ class Creature; class Game; -class Spawn; class Monster final : public Creature { public: @@ -23,7 +22,7 @@ class Monster final : public Creature { static int32_t despawnRange; static int32_t despawnRadius; - explicit Monster(const std::shared_ptr mType); + explicit Monster(std::shared_ptr mType); // non-copyable Monster(const Monster &) = delete; @@ -160,7 +159,7 @@ class Monster final : public Creature { } std::vector getIcons() const override { - const auto creatureIcons = Creature::getIcons(); + auto creatureIcons = Creature::getIcons(); if (!creatureIcons.empty()) { return creatureIcons; } @@ -324,7 +323,7 @@ class Monster final : public Creature { return timeToChangeFiendish; } - const std::shared_ptr getMonsterType() const { + std::shared_ptr getMonsterType() const { return mType; } diff --git a/src/creatures/monsters/monsters.cpp b/src/creatures/monsters/monsters.cpp index 190c14c76e5..3d457aa4d47 100644 --- a/src/creatures/monsters/monsters.cpp +++ b/src/creatures/monsters/monsters.cpp @@ -20,7 +20,7 @@ void MonsterType::loadLoot(const std::shared_ptr monsterType, LootB if (lootBlock.childLoot.empty()) { bool isContainer = Item::items[lootBlock.id].isContainer(); if (isContainer) { - for (LootBlock child : lootBlock.childLoot) { + for (const LootBlock &child : lootBlock.childLoot) { lootBlock.childLoot.push_back(child); } } @@ -74,7 +74,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr spell, spell return true; } - std::shared_ptr combatSpell = nullptr; + std::shared_ptr combatSpell; auto combatPtr = std::make_shared(); @@ -156,7 +156,7 @@ bool Monsters::deserializeSpell(const std::shared_ptr spell, spell std::shared_ptr condition = Condition::createCondition(CONDITIONID_COMBAT, CONDITION_OUTFIT, duration, 0)->static_self_cast(); - if (spell->outfitMonster != "") { + if (!spell->outfitMonster.empty()) { condition->setLazyMonsterOutfit(spell->outfitMonster); } else if (spell->outfitItem > 0) { Outfit_t outfit; @@ -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 { - const auto bossType = g_ioBosstiary().getMonsterTypeByBossRaceId(raceId); + auto bossType = g_ioBosstiary().getMonsterTypeByBossRaceId(raceId); if (isBoss && bossType) { return bossType; } diff --git a/src/creatures/monsters/monsters.hpp b/src/creatures/monsters/monsters.hpp index 0fa2a3d88db..518befd8a70 100644 --- a/src/creatures/monsters/monsters.hpp +++ b/src/creatures/monsters/monsters.hpp @@ -30,7 +30,7 @@ struct spellBlock_t { ~spellBlock_t() = default; spellBlock_t(const spellBlock_t &other) = delete; spellBlock_t &operator=(const spellBlock_t &other) = delete; - spellBlock_t(spellBlock_t &&other) : + spellBlock_t(spellBlock_t &&other) noexcept : spell(other.spell), chance(other.chance), speed(other.speed), @@ -57,7 +57,7 @@ struct spellBlock_t { class MonsterType { struct MonsterInfo { - LuaScriptInterface* scriptInterface; + LuaScriptInterface* scriptInterface {}; std::map elementMap; std::map reflectMap; @@ -201,7 +201,7 @@ class MonsterType { return !info.bosstiaryClass.empty(); } - void loadLoot(const std::shared_ptr monsterType, LootBlock lootblock); + void loadLoot(std::shared_ptr monsterType, LootBlock lootblock); bool canSpawn(const Position &pos); }; @@ -271,8 +271,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, const std::shared_ptr mType); - bool deserializeSpell(const std::shared_ptr spell, spellBlock_t &sb, const std::string &description = ""); + bool tryAddMonsterType(const std::string &name, std::shared_ptr mType); + bool deserializeSpell(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 21eab1a7c0b..ef5912c8052 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -39,7 +39,6 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { this->filemonstername = filemonstername; loaded = true; - uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); std::string boostedNameGet = g_game().getBoostedMonsterName(); for (auto spawnMonsterNode : doc.child("monsters").children()) { @@ -89,12 +88,6 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { centerPos.z ); - int32_t boostedrate = 1; - - if (nameAttribute.value() == boostedNameGet) { - boostedrate = 2; - } - pugi::xml_attribute weightAttribute = childMonsterNode.attribute("weight"); uint32_t weight = 1; if (weightAttribute) { @@ -157,12 +150,9 @@ SpawnMonster::~SpawnMonster() { bool SpawnMonster::findPlayer(const Position &pos) { auto spectators = Spectators().find(pos); - for (const auto &spectator : spectators) { - if (!spectator->getPlayer()->hasFlag(PlayerFlags_t::IgnoredByMonsters)) { - return true; - } - } - return false; + return std::ranges::any_of(spectators, [](const auto &spectator) { + return !spectator->getPlayer()->hasFlag(PlayerFlags_t::IgnoredByMonsters); + }); } bool SpawnMonster::isInSpawnMonsterZone(const Position &pos) { @@ -299,7 +289,7 @@ void SpawnMonster::cleanup() { } bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Direction dir, uint32_t scheduleInterval, uint32_t weight /*= 1*/) { - std::string variant = ""; + std::string variant; for (const auto &zone : Zone::getZones(pos)) { if (!zone->getMonsterVariant().empty()) { variant = zone->getMonsterVariant() + "|"; @@ -343,7 +333,7 @@ bool SpawnMonster::addMonster(const std::string &name, const Position &pos, Dire g_logger().error("[SpawnMonster] Monster {} already exists in spawn block at {}", name, pos.toString()); return false; } - if (monsterType->isBoss() && sb->monsterTypes.size() > 0) { + if (monsterType->isBoss() && !sb->monsterTypes.empty()) { g_logger().error("[SpawnMonster] Boss monster {} has been added to spawn block with other monsters. This is not allowed.", name); return false; } @@ -436,10 +426,8 @@ std::shared_ptr spawnBlock_t::getMonsterType() const { } bool spawnBlock_t::hasBoss() const { - for (const auto &[monsterType, weight] : monsterTypes) { - if (monsterType->isBoss()) { - return true; - } - } - return false; + return std::ranges::any_of(monsterTypes, [](const auto &pair) { + const auto &[monsterType, weight] = pair; + return monsterType->isBoss(); + }); } diff --git a/src/creatures/monsters/spawns/spawn_monster.hpp b/src/creatures/monsters/spawns/spawn_monster.hpp index 800b36fda5a..35b856d23d4 100644 --- a/src/creatures/monsters/spawns/spawn_monster.hpp +++ b/src/creatures/monsters/spawns/spawn_monster.hpp @@ -29,7 +29,7 @@ struct spawnBlock_t { class SpawnMonster { public: SpawnMonster(Position initPos, int32_t initRadius) : - centerPos(std::move(initPos)), radius(initRadius) { } + centerPos(initPos), radius(initRadius) { } ~SpawnMonster(); // non-copyable @@ -71,9 +71,9 @@ class SpawnMonster { uint32_t checkSpawnMonsterEvent = 0; static bool findPlayer(const Position &pos); - bool spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr monsterType, bool startup = false); + bool spawnMonster(uint32_t spawnMonsterId, spawnBlock_t &sb, std::shared_ptr monsterType, bool startup = false); void checkSpawnMonster(); - void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, const std::shared_ptr monsterType, uint16_t interval, bool startup = false); + void scheduleSpawn(uint32_t spawnMonsterId, spawnBlock_t &sb, 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 d347ec6b66c..e445a58fcca 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -52,9 +52,6 @@ Npc::Npc(const std::shared_ptr &npcType) : } } -Npc::~Npc() { -} - void Npc::addList() { g_game().addNpc(static_self_cast()); } @@ -248,7 +245,7 @@ void Npc::onPlayerBuyItem(std::shared_ptr player, uint16_t itemId, uint8 uint32_t shoppingBagSlots = 20; const ItemType &itemType = Item::items[itemId]; if (std::shared_ptr tile = ignore ? player->getTile() : nullptr; tile) { - double slotsNedeed = 0; + double slotsNedeed; if (itemType.stackable) { slotsNedeed = inBackpacks ? std::ceil(std::ceil(static_cast(amount) / itemType.stackSize) / shoppingBagSlots) : std::ceil(static_cast(amount) / itemType.stackSize); } else { @@ -263,7 +260,7 @@ void Npc::onPlayerBuyItem(std::shared_ptr player, uint16_t itemId, uint8 uint32_t buyPrice = 0; const std::vector &shopVector = getShopItemVector(player->getGUID()); - for (ShopBlock shopBlock : shopVector) { + for (const ShopBlock &shopBlock : shopVector) { if (itemType.id == shopBlock.itemId && shopBlock.itemBuyPrice != 0) { buyPrice = shopBlock.itemBuyPrice; } @@ -308,7 +305,7 @@ 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) { uint64_t totalPrice = 0; - onPlayerSellItem(player, itemId, subType, amount, ignore, totalPrice); + onPlayerSellItem(std::move(player), itemId, subType, amount, ignore, totalPrice); } void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, uint64_t totalPrice) { @@ -324,7 +321,6 @@ void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, u bool hasMore = false; uint64_t toSellCount = 0; phmap::flat_hash_map toSell; - int64_t start = OTSYS_TIME(); for (ContainerIterator it = container->iterator(); it.hasNext(); it.advance()) { if (toSellCount >= 500) { hasMore = true; @@ -341,8 +337,8 @@ void Npc::onPlayerSellAllLoot(uint32_t playerId, uint16_t itemId, bool ignore, u toSellCount += item->getItemAmount(); } } - for (auto &[itemId, amount] : toSell) { - onPlayerSellItem(player, itemId, 0, amount, ignore, totalPrice, container); + for (auto &[m_itemId, amount] : toSell) { + onPlayerSellItem(player, m_itemId, 0, amount, ignore, totalPrice, container); } auto ss = std::stringstream(); if (totalPrice == 0) { @@ -377,7 +373,7 @@ void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint uint32_t sellPrice = 0; const ItemType &itemType = Item::items[itemId]; const std::vector &shopVector = getShopItemVector(player->getGUID()); - for (ShopBlock shopBlock : shopVector) { + for (const ShopBlock &shopBlock : shopVector) { if (itemType.id == shopBlock.itemId && shopBlock.itemSellPrice != 0) { sellPrice = shopBlock.itemSellPrice; } @@ -387,7 +383,7 @@ void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint } auto toRemove = amount; - for (auto item : player->getInventoryItemsFromId(itemId, ignore)) { + for (const auto &item : player->getInventoryItemsFromId(itemId, ignore)) { if (!item || item->getTier() > 0 || item->hasImbuements()) { continue; } @@ -452,7 +448,6 @@ void Npc::onPlayerCheckItem(std::shared_ptr player, uint16_t itemId, uin return; } - const ItemType &itemType = Item::items[itemId]; // onPlayerCheckItem(self, player, itemId, subType) CreatureCallback callback = CreatureCallback(npcType->info.scriptInterface, getNpc()); if (callback.startScriptInterface(npcType->info.playerLookEvent)) { @@ -515,7 +510,7 @@ void Npc::onThinkWalk(uint32_t interval) { } // If talking, no walking - if (playerInteractions.size() > 0) { + if (!playerInteractions.empty()) { walkTicks = 0; eventWalk = 0; return; diff --git a/src/creatures/npcs/npc.hpp b/src/creatures/npcs/npc.hpp index 2d4e87ac7b8..7e8be84c7f1 100644 --- a/src/creatures/npcs/npc.hpp +++ b/src/creatures/npcs/npc.hpp @@ -27,7 +27,6 @@ class Npc final : public Creature { explicit Npc(const std::shared_ptr &npcType); Npc() = default; - ~Npc(); // Singleton - ensures we don't accidentally copy it Npc(const Npc &) = delete; @@ -68,7 +67,7 @@ class Npc final : public Creature { } void setName(std::string newName) { - npcType->name = newName; + npcType->name = std::move(newName); } CreatureType_t getType() const override { @@ -190,13 +189,13 @@ class Npc final : public Creature { std::shared_ptr npcType; std::shared_ptr spawnNpc; - uint8_t speechBubble; + uint8_t speechBubble {}; uint32_t yellTicks = 0; uint32_t walkTicks = 0; uint32_t soundTicks = 0; - bool ignoreHeight; + bool ignoreHeight {}; phmap::flat_hash_set> playerSpectators; Position masterPos; diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index ecfd2750a94..6fe7f0b8320 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -84,16 +84,16 @@ void NpcType::loadShop(const std::shared_ptr &npcType, ShopBlock shopBl } // Check if the item already exists in the shop vector and ignore it - for (auto shopIterator = npcType->info.shopItemVector.begin(); shopIterator != npcType->info.shopItemVector.end(); ++shopIterator) { - if (*shopIterator == shopBlock) { - return; - } + if (std::any_of(npcType->info.shopItemVector.begin(), npcType->info.shopItemVector.end(), [&shopBlock](const auto &shopIterator) { + return shopIterator == shopBlock; + })) { + return; } if (shopBlock.childShop.empty()) { bool isContainer = iType.isContainer(); if (isContainer) { - for (ShopBlock child : shopBlock.childShop) { + for (const ShopBlock &child : shopBlock.childShop) { shopBlock.childShop.push_back(child); } } diff --git a/src/creatures/npcs/npcs.hpp b/src/creatures/npcs/npcs.hpp index 1a984abf2e8..ab5e700caea 100644 --- a/src/creatures/npcs/npcs.hpp +++ b/src/creatures/npcs/npcs.hpp @@ -25,7 +25,7 @@ class Shop { class NpcType : public SharedObject { struct NpcInfo { - LuaScriptInterface* scriptInterface; + LuaScriptInterface* scriptInterface {}; Outfit_t outfit = {}; RespawnType respawnType = {}; diff --git a/src/creatures/npcs/spawns/spawn_npc.cpp b/src/creatures/npcs/spawns/spawn_npc.cpp index 968deca5331..a8be411dc6c 100644 --- a/src/creatures/npcs/spawns/spawn_npc.cpp +++ b/src/creatures/npcs/spawns/spawn_npc.cpp @@ -146,12 +146,9 @@ SpawnNpc::~SpawnNpc() { bool SpawnNpc::findPlayer(const Position &pos) { auto spectators = Spectators().find(pos); - for (const auto &spectator : spectators) { - if (!spectator->getPlayer()->hasFlag(PlayerFlags_t::IgnoredByNpcs)) { - return true; - } - } - return false; + return std::ranges::any_of(spectators, [](const auto &spectator) { + return !spectator->getPlayer()->hasFlag(PlayerFlags_t::IgnoredByNpcs); + }); } bool SpawnNpc::isInSpawnNpcZone(const Position &pos) { diff --git a/src/creatures/npcs/spawns/spawn_npc.hpp b/src/creatures/npcs/spawns/spawn_npc.hpp index d02a83e80c5..49eb3bc6f2b 100644 --- a/src/creatures/npcs/spawns/spawn_npc.hpp +++ b/src/creatures/npcs/spawns/spawn_npc.hpp @@ -26,7 +26,7 @@ struct spawnBlockNpc_t { class SpawnNpc : public SharedObject { public: SpawnNpc(Position initPos, int32_t initRadius) : - centerPos(std::move(initPos)), radius(initRadius) { } + centerPos(initPos), radius(initRadius) { } ~SpawnNpc(); // non-copyable @@ -91,7 +91,7 @@ class SpawnsNpc { } std::string setFileName(std::string setName) { - return fileName = setName; + return fileName = std::move(setName); } std::forward_list> &getSpawnNpcList() { diff --git a/src/creatures/players/achievement/player_achievement.hpp b/src/creatures/players/achievement/player_achievement.hpp index 7d141c96a16..d1073a9bf1e 100644 --- a/src/creatures/players/achievement/player_achievement.hpp +++ b/src/creatures/players/achievement/player_achievement.hpp @@ -13,7 +13,7 @@ class Player; class KV; struct Achievement { - Achievement() { } + Achievement() = default; std::string name; std::string description; diff --git a/src/creatures/players/grouping/familiars.cpp b/src/creatures/players/grouping/familiars.cpp index 538519685c3..a922013f19b 100644 --- a/src/creatures/players/grouping/familiars.cpp +++ b/src/creatures/players/grouping/familiars.cpp @@ -14,6 +14,13 @@ #include "utils/pugicast.hpp" #include "utils/tools.hpp" +bool Familiars::reload() { + for (auto &familiarsVector : familiars) { + familiarsVector.clear(); + } + return loadFromXml(); +} + bool Familiars::loadFromXml() { pugi::xml_document doc; auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/familiars.xml"; @@ -47,13 +54,13 @@ bool Familiars::loadFromXml() { continue; } - familiars[vocation].emplace_back( + familiars[vocation].emplace_back(std::make_shared( familiarsNode.attribute("name").as_string(), pugi::cast(lookTypeAttribute.value()), familiarsNode.attribute("premium").as_bool(), familiarsNode.attribute("unlocked").as_bool(true), familiarsNode.attribute("type").as_string() - ); + )); } for (uint16_t vocation = VOCATION_NONE; vocation <= VOCATION_LAST; ++vocation) { familiars[vocation].shrink_to_fit(); @@ -61,11 +68,12 @@ bool Familiars::loadFromXml() { return true; } -const Familiar* Familiars::getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const { - for (const Familiar &familiar : familiars[vocation]) { - if (familiar.lookType == lookType) { - return &familiar; - } +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) { + return familiar_it->lookType == lookType; + }); + it != familiars[vocation].end()) { + return *it; } return nullptr; } diff --git a/src/creatures/players/grouping/familiars.hpp b/src/creatures/players/grouping/familiars.hpp index aae9b34e227..8f553af9fbe 100644 --- a/src/creatures/players/grouping/familiars.hpp +++ b/src/creatures/players/grouping/familiars.hpp @@ -9,20 +9,42 @@ #pragma once -#include "declarations.hpp" #include "lib/di/container.hpp" +struct FamiliarEntry { + constexpr explicit FamiliarEntry(uint16_t initLookType) : + lookType(initLookType) { } + uint16_t lookType; +}; + +struct Familiar { + Familiar(std::string initName, uint16_t initLookType, bool initPremium, bool initUnlocked, std::string initType) : + name(std::move(initName)), lookType(initLookType), + premium(initPremium), unlocked(initUnlocked), + type(std::move(initType)) { } + + std::string name; + uint16_t lookType; + bool premium; + bool unlocked; + std::string type; +}; + class Familiars { public: static Familiars &getInstance() { return inject(); } + bool loadFromXml(); - const std::vector &getFamiliars(uint16_t vocation) const { + bool reload(); + + std::vector> &getFamiliars(uint16_t vocation) { return familiars[vocation]; } - const Familiar* getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const; + + [[nodiscard]] std::shared_ptr getFamiliarByLookType(uint16_t vocation, uint16_t lookType) const; private: - std::vector familiars[VOCATION_LAST + 1]; + std::vector> familiars[VOCATION_LAST + 1]; }; diff --git a/src/creatures/players/grouping/groups.cpp b/src/creatures/players/grouping/groups.cpp index 40dd13bc385..27ae68d9fd4 100644 --- a/src/creatures/players/grouping/groups.cpp +++ b/src/creatures/players/grouping/groups.cpp @@ -93,17 +93,18 @@ bool Groups::load() { // Parsing group flags parseGroupFlags(group, groupNode); - groups_vector.push_back(group); + groups_vector.emplace_back(std::make_shared(group)); } groups_vector.shrink_to_fit(); return true; } -Group* Groups::getGroup(uint16_t id) { - for (Group &group : groups_vector) { - if (group.id == id) { - return &group; - } +std::shared_ptr Groups::getGroup(uint16_t id) { + if (auto it = std::find_if(groups_vector.begin(), groups_vector.end(), [id](auto group_it) { + return group_it->id == id; + }); + it != groups_vector.end()) { + return *it; } return nullptr; } diff --git a/src/creatures/players/grouping/groups.hpp b/src/creatures/players/grouping/groups.hpp index 3d74564173d..d76914e2632 100644 --- a/src/creatures/players/grouping/groups.hpp +++ b/src/creatures/players/grouping/groups.hpp @@ -26,11 +26,11 @@ class Groups { static PlayerFlags_t getFlagFromNumber(uint8_t value); bool reload() const; bool load(); - Group* getGroup(uint16_t id); - std::vector &getGroups() { + std::shared_ptr getGroup(uint16_t id); + std::vector> &getGroups() { return groups_vector; } private: - std::vector groups_vector; + std::vector> groups_vector; }; diff --git a/src/creatures/players/grouping/guild.cpp b/src/creatures/players/grouping/guild.cpp index aca512f28e3..bbd662d1a1d 100644 --- a/src/creatures/players/grouping/guild.cpp +++ b/src/creatures/players/grouping/guild.cpp @@ -14,7 +14,7 @@ void Guild::addMember(const std::shared_ptr &player) { membersOnline.push_back(player); - for (auto member : getMembersOnline()) { + for (const auto &member : getMembersOnline()) { g_game().updatePlayerHelpers(member); } } diff --git a/src/creatures/players/grouping/guild.hpp b/src/creatures/players/grouping/guild.hpp index 834eb03252c..82b0a7367ea 100644 --- a/src/creatures/players/grouping/guild.hpp +++ b/src/creatures/players/grouping/guild.hpp @@ -32,9 +32,10 @@ class Guild : public Bankable { void addMember(const std::shared_ptr &player); void removeMember(const std::shared_ptr &player); - bool isGuild() { + bool isGuild() override { return true; } + void setOnline(bool value) override { online = value; } diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index c7d6fd48363..76f1d955f10 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -7,6 +7,8 @@ * Website: https://docs.opentibiabr.com/ */ +#include + #include "pch.hpp" #include "creatures/players/grouping/party.hpp" @@ -47,23 +49,23 @@ void Party::disband() { currentLeader->sendCreatureSkull(currentLeader); currentLeader->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, "Your party has been disbanded."); - for (auto invitee : getInvitees()) { + for (const auto &invitee : getInvitees()) { invitee->removePartyInvitation(getParty()); currentLeader->sendCreatureShield(invitee); } inviteList.clear(); auto members = getMembers(); - for (auto member : members) { + for (const auto &member : members) { member->setParty(nullptr); member->sendClosePrivate(CHANNEL_PARTY); member->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, "Your party has been disbanded."); } - for (auto member : members) { + for (const auto &member : members) { g_game().updatePlayerShield(member); - for (auto otherMember : members) { + for (const auto &otherMember : members) { otherMember->sendCreatureSkull(member); } @@ -132,7 +134,7 @@ bool Party::leaveParty(std::shared_ptr player) { g_game().updatePlayerShield(player); g_game().updatePlayerHelpers(player); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->sendCreatureSkull(player); player->sendPlayerPartyIcons(member); member->sendPartyCreatureUpdate(player); @@ -185,12 +187,12 @@ bool Party::passPartyLeadership(std::shared_ptr player) { updateSharedExperience(); updateTrackerAnalyzer(); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->sendPartyCreatureShield(oldLeader); member->sendPartyCreatureShield(player); } - for (auto invitee : getInvitees()) { + for (const auto &invitee : getInvitees()) { invitee->sendCreatureShield(oldLeader); invitee->sendCreatureShield(player); } @@ -231,7 +233,7 @@ bool Party::joinParty(const std::shared_ptr &player) { g_game().updatePlayerShield(player); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->sendCreatureSkull(player); member->sendPlayerPartyIcons(player); player->sendPlayerPartyIcons(member); @@ -282,7 +284,7 @@ bool Party::removeInvite(const std::shared_ptr &player, bool removeFromP if (empty()) { disband(); } else { - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { g_game().updatePlayerHelpers(member); } @@ -332,7 +334,7 @@ bool Party::invitePlayer(const std::shared_ptr &player) { inviteList.push_back(player); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { g_game().updatePlayerHelpers(member); } @@ -359,8 +361,8 @@ void Party::updateAllPartyIcons() { return; } auto members = getMembers(); - for (auto member : members) { - for (auto otherMember : members) { + for (const auto &member : members) { + for (const auto &otherMember : members) { member->sendPartyCreatureShield(otherMember); } @@ -376,14 +378,14 @@ void Party::broadcastPartyMessage(MessageClasses msgClass, const std::string &ms if (!leader) { return; } - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->sendTextMessage(msgClass, msg); } leader->sendTextMessage(msgClass, msg); if (sendToInvitations) { - for (auto invitee : getInvitees()) { + for (const auto &invitee : getInvitees()) { invitee->sendTextMessage(msgClass, msg); } } @@ -454,14 +456,14 @@ void Party::shareExperience(uint64_t experience, std::shared_ptr targe g_events().eventPartyOnShareExperience(getParty(), shareExperience); g_callbacks().executeCallback(EventCallback_t::partyOnShareExperience, &EventCallback::partyOnShareExperience, getParty(), shareExperience); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->onGainSharedExperience(shareExperience, target); } leader->onGainSharedExperience(shareExperience, target); } bool Party::canUseSharedExperience(std::shared_ptr player) { - return getMemberSharedExperienceStatus(player) == SHAREDEXP_OK; + return getMemberSharedExperienceStatus(std::move(player)) == SHAREDEXP_OK; } SharedExpStatus_t Party::getMemberSharedExperienceStatus(std::shared_ptr player) { @@ -473,7 +475,6 @@ SharedExpStatus_t Party::getMemberSharedExperienceStatus(std::shared_ptr return SHAREDEXP_EMPTYPARTY; } - uint32_t highestLevel = getHighestLevel(); uint32_t minLevel = getMinLevel(); if (player->getLevel() < minLevel) { return SHAREDEXP_LEVELDIFFTOOLARGE; @@ -502,7 +503,7 @@ uint32_t Party::getHighestLevel() { } uint32_t highestLevel = leader->getLevel(); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { if (member->getLevel() > highestLevel) { highestLevel = member->getLevel(); } @@ -520,7 +521,7 @@ uint32_t Party::getLowestLevel() { return 0; } uint32_t lowestLevel = leader->getLevel(); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { if (member->getLevel() < lowestLevel) { lowestLevel = member->getLevel(); } @@ -551,7 +552,7 @@ SharedExpStatus_t Party::getSharedExperienceStatus() { return leaderStatus; } - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { SharedExpStatus_t memberStatus = getMemberSharedExperienceStatus(member); if (memberStatus != SHAREDEXP_OK) { return memberStatus; @@ -620,7 +621,7 @@ void Party::updatePlayerStatus(std::shared_ptr player) { } int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { showPlayerStatus(player, member, true); @@ -644,7 +645,7 @@ void Party::updatePlayerStatus(std::shared_ptr player, const Position &o int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); if (maxDistance != 0) { - for (auto member : getMembers()) { + 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); if (condition1 && !condition2) { @@ -673,7 +674,7 @@ void Party::updatePlayerHealth(std::shared_ptr player, std::shared_ptrgetPosition(); auto leaderPosition = leader->getPosition(); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { auto memberPosition = member->getPosition(); bool condition = (maxDistance == 0 || (Position::getDistanceX(playerPosition, memberPosition) <= maxDistance && Position::getDistanceY(playerPosition, memberPosition) <= maxDistance)); if (condition) { @@ -693,7 +694,7 @@ void Party::updatePlayerMana(std::shared_ptr player, uint8_t manaPercent } int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { member->sendPartyPlayerMana(player, manaPercent); @@ -712,7 +713,7 @@ void Party::updatePlayerVocation(std::shared_ptr player) { } int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { member->sendPartyPlayerVocation(player); @@ -730,7 +731,7 @@ void Party::updateTrackerAnalyzer() { return; } - for (auto member : getMembers()) { + for (const auto &member : getMembers()) { member->updatePartyTrackerAnalyzer(); } diff --git a/src/creatures/players/grouping/party.hpp b/src/creatures/players/grouping/party.hpp index 5da0f4e0647..10663a278bf 100644 --- a/src/creatures/players/grouping/party.hpp +++ b/src/creatures/players/grouping/party.hpp @@ -105,7 +105,7 @@ class Party : public SharedObject { void reloadPrices(); std::shared_ptr getPlayerPartyAnalyzerStruct(uint32_t playerId) const { - if (auto it = std::find_if(membersData.begin(), membersData.end(), [playerId](const std::shared_ptr preyIt) { + if (auto it = std::find_if(membersData.begin(), membersData.end(), [playerId](const std::shared_ptr &preyIt) { return preyIt->id == playerId; }); it != membersData.end()) { diff --git a/src/creatures/players/grouping/team_finder.hpp b/src/creatures/players/grouping/team_finder.hpp index 123ce7c07d8..9fafbd03227 100644 --- a/src/creatures/players/grouping/team_finder.hpp +++ b/src/creatures/players/grouping/team_finder.hpp @@ -1,3 +1,5 @@ +#include + /** * Canary - A free and open-source MMORPG server emulator * Copyright (©) 2019-2024 OpenTibiaBR @@ -31,7 +33,7 @@ class TeamFinder { hunt_area(initHunt_area), questID(initQuestID), leaderGuid(initLeaderGuid), - membersMap(initMembersMap) { } + membersMap(std::move(initMembersMap)) { } virtual ~TeamFinder() = default; uint16_t minLevel = 0; diff --git a/src/creatures/players/highscore_category.hpp b/src/creatures/players/highscore_category.hpp index b387199f315..71da6b76ec6 100644 --- a/src/creatures/players/highscore_category.hpp +++ b/src/creatures/players/highscore_category.hpp @@ -10,8 +10,8 @@ #pragma once struct HighscoreCategory { - HighscoreCategory(const std::string &name, uint8_t id) : - m_name(name), + HighscoreCategory(std::string name, uint8_t id) : + m_name(std::move(name)), m_id(id) { } std::string m_name; diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index 78478953ade..3182607ecba 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -56,7 +56,7 @@ Player::Player(ProtocolGame_ptr p) : } Player::~Player() { - for (std::shared_ptr item : inventory) { + for (const std::shared_ptr &item : inventory) { if (item) { item->resetParent(); item->stopDecaying(); @@ -1335,7 +1335,7 @@ void Player::getRewardList(std::vector &rewards) const { std::vector> Player::getRewardsFromContainer(std::shared_ptr container) const { std::vector> rewardItemsVector; if (container) { - for (auto item : container->getItems(false)) { + for (const auto &item : container->getItems(false)) { if (item->getID() == ITEM_REWARD_CONTAINER) { auto items = getRewardsFromContainer(item->getContainer()); rewardItemsVector.insert(rewardItemsVector.end(), items.begin(), items.end()); @@ -1754,7 +1754,7 @@ void Player::onCreatureAppear(std::shared_ptr creature, bool isLogin) offlineTime = 0; } - for (std::shared_ptr condition : getMuteConditions()) { + for (const std::shared_ptr &condition : getMuteConditions()) { condition->setTicks(condition->getTicks() - (offlineTime * 1000)); if (condition->getTicks() <= 0) { removeCondition(condition); @@ -2232,7 +2232,7 @@ uint32_t Player::isMuted() const { } int32_t muteTicks = 0; - for (std::shared_ptr condition : conditions) { + for (const std::shared_ptr &condition : conditions) { if (condition->getType() == CONDITION_MUTED && condition->getTicks() > muteTicks) { muteTicks = condition->getTicks(); } @@ -2401,7 +2401,7 @@ void Player::addExperience(std::shared_ptr target, uint64_t exp, bool if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " gained " + expString; - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { spectator->getPlayer()->sendTextMessage(message); } } @@ -2494,7 +2494,7 @@ void Player::removeExperience(uint64_t exp, bool sendText /* = false*/) { if (!spectators.empty()) { message.type = MESSAGE_EXPERIENCE_OTHERS; message.text = getName() + " lost " + expString; - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { spectator->getPlayer()->sendTextMessage(message); } } @@ -3553,7 +3553,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh n--; } - for (std::shared_ptr tmpContainerItem : tmpContainer->getItemList()) { + for (const std::shared_ptr &tmpContainerItem : tmpContainer->getItemList()) { if (std::shared_ptr subContainer = tmpContainerItem->getContainer()) { containers.push_back(subContainer); } @@ -3564,7 +3564,7 @@ std::shared_ptr Player::queryDestination(int32_t &index, const std::sh uint32_t n = 0; - for (std::shared_ptr tmpItem : tmpContainer->getItemList()) { + for (const std::shared_ptr &tmpItem : tmpContainer->getItemList()) { if (tmpItem == tradeItem) { continue; } @@ -3772,7 +3772,7 @@ uint32_t Player::getItemTypeCount(uint16_t itemId, int32_t subType /*= -1*/) con void Player::stashContainer(StashContainerList itemDict) { StashItemList stashItemDict; // ItemID - Count - for (auto it_dict : itemDict) { + for (const auto &it_dict : itemDict) { stashItemDict[(it_dict.first)->getID()] = it_dict.second; } @@ -3792,7 +3792,7 @@ void Player::stashContainer(StashContainerList itemDict) { uint32_t totalStowed = 0; std::ostringstream retString; uint16_t refreshDepotSearchOnItem = 0; - for (auto stashIterator : itemDict) { + 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); @@ -3878,7 +3878,7 @@ bool Player::removeItemOfType(uint16_t itemId, uint32_t amount, int32_t subType, bool Player::hasItemCountById(uint16_t itemId, uint32_t itemAmount, bool checkStash) const { uint32_t newCount = 0; // Check items from inventory - for (const auto item : getAllInventoryItems()) { + for (const auto &item : getAllInventoryItems()) { if (!item || item->getID() != itemId) { continue; } @@ -3909,7 +3909,7 @@ bool Player::removeItemCountById(uint16_t itemId, uint32_t itemAmount, bool remo uint32_t amountToRemove = itemAmount; // Check items from inventory - for (auto item : getAllInventoryItems()) { + for (const auto &item : getAllInventoryItems()) { if (!item || item->getID() != itemId) { continue; } @@ -4171,14 +4171,14 @@ std::vector> Player::getEquippedItems() const { } std::map &Player::getAllItemTypeCount(std::map &countMap) const { - for (const auto item : getAllInventoryItems()) { + for (const auto &item : getAllInventoryItems()) { countMap[static_cast(item->getID())] += Item::countByType(item, -1); } return countMap; } std::map &Player::getAllSaleItemIdAndCount(std::map &countMap) const { - for (const auto item : getAllInventoryItems(false, true)) { + for (const auto &item : getAllInventoryItems(false, true)) { countMap[item->getID()] += item->getItemCount(); } @@ -4186,7 +4186,7 @@ std::map &Player::getAllSaleItemIdAndCount(std::map &countMap) const { - for (const auto item : getAllInventoryItems()) { + for (const auto &item : getAllInventoryItems()) { uint16_t itemId = item->getID(); if (Item::items[itemId].isFluidContainer()) { countMap[static_cast(itemId) | (item->getAttribute(ItemAttribute_t::FLUIDTYPE)) << 16] += item->getItemCount(); @@ -4263,7 +4263,7 @@ void Player::postAddNotification(std::shared_ptr thing, std::shared_ptr container : containers) { + for (const std::shared_ptr &container : containers) { autoCloseContainers(container); } } @@ -4570,7 +4570,7 @@ void Player::updateItemsLight(bool internal /*=false*/) { LightInfo curLight = item->getLightInfo(); if (curLight.level > maxLight.level) { - maxLight = std::move(curLight); + maxLight = curLight; } } } @@ -5101,7 +5101,7 @@ bool Player::canFamiliar(uint16_t lookType) const { return true; } - const Familiar* familiar = Familiars::getInstance().getFamiliarByLookType(getVocationId(), lookType); + const auto &familiar = Familiars::getInstance().getFamiliarByLookType(getVocationId(), lookType); if (!familiar) { return false; } @@ -5142,24 +5142,24 @@ bool Player::removeFamiliar(uint16_t lookType) { return false; } -bool Player::getFamiliar(const Familiar &familiar) const { +bool Player::getFamiliar(const std::shared_ptr &familiar) const { if (group->access) { return true; } - if (familiar.premium && !isPremium()) { + if (familiar->premium && !isPremium()) { return false; } for (const FamiliarEntry &familiarEntry : familiars) { - if (familiarEntry.lookType != familiar.lookType) { + if (familiarEntry.lookType != familiar->lookType) { continue; } return true; } - if (!familiar.unlocked) { + if (!familiar->unlocked) { return false; } @@ -5514,7 +5514,7 @@ void Player::setTibiaCoins(int32_t v) { int32_t Player::getCleavePercent(bool useCharges) const { int32_t result = cleavePercent; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &it = Item::items[item->getID()]; if (!it.abilities) { continue; @@ -5540,7 +5540,7 @@ int32_t Player::getPerfectShotDamage(uint8_t range, bool useCharges) const { result = it->second; } - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5564,7 +5564,7 @@ int32_t Player::getPerfectShotDamage(uint8_t range, bool useCharges) const { int32_t Player::getSpecializedMagicLevel(CombatType_t combat, bool useCharges) const { int32_t result = specializedMagicLevel[combatTypeToIndex(combat)]; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5585,7 +5585,7 @@ int32_t Player::getSpecializedMagicLevel(CombatType_t combat, bool useCharges) c int32_t Player::getMagicShieldCapacityFlat(bool useCharges) const { int32_t result = magicShieldCapacityFlat; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5606,7 +5606,7 @@ int32_t Player::getMagicShieldCapacityFlat(bool useCharges) const { int32_t Player::getMagicShieldCapacityPercent(bool useCharges) const { int32_t result = magicShieldCapacityPercent; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5627,7 +5627,7 @@ int32_t Player::getMagicShieldCapacityPercent(bool useCharges) const { int32_t Player::getReflectPercent(CombatType_t combat, bool useCharges) const { int32_t result = reflectPercent[combatTypeToIndex(combat)]; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5648,7 +5648,7 @@ int32_t Player::getReflectPercent(CombatType_t combat, bool useCharges) const { int32_t Player::getReflectFlat(CombatType_t combat, bool useCharges) const { int32_t result = reflectFlat[combatTypeToIndex(combat)]; - for (const auto item : getEquippedItems()) { + for (const auto &item : getEquippedItems()) { const ItemType &itemType = Item::items[item->getID()]; if (!itemType.abilities) { continue; @@ -5855,7 +5855,7 @@ void Player::setCurrentMount(uint8_t mount) { bool Player::hasAnyMount() const { const auto mounts = g_game().mounts.getMounts(); - for (const auto mount : mounts) { + for (const auto &mount : mounts) { if (hasMount(mount)) { return true; } @@ -5866,7 +5866,7 @@ bool Player::hasAnyMount() const { uint8_t Player::getRandomMountId() const { std::vector playerMounts; const auto mounts = g_game().mounts.getMounts(); - for (const auto mount : mounts) { + for (const auto &mount : mounts) { if (hasMount(mount)) { playerMounts.push_back(mount->id); } @@ -6253,7 +6253,7 @@ uint64_t Player::getMoney() const { size_t i = 0; while (i < containers.size()) { std::shared_ptr container = containers[i++]; - for (std::shared_ptr item : container->getItemList()) { + for (const std::shared_ptr &item : container->getItemList()) { std::shared_ptr tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); @@ -6270,7 +6270,7 @@ std::pair Player::getForgeSliversAndCores() const { uint64_t coreCount = 0; // Check items from inventory - for (const auto item : getAllInventoryItems()) { + for (const auto &item : getAllInventoryItems()) { if (!item) { continue; } @@ -6313,7 +6313,7 @@ size_t Player::getMaxDepotItems() const { std::forward_list> Player::getMuteConditions() const { std::forward_list> muteConditions; - for (std::shared_ptr condition : conditions) { + for (const std::shared_ptr &condition : conditions) { if (condition->getTicks() <= 0) { continue; } @@ -6519,7 +6519,7 @@ void sendStowItems(const std::shared_ptr &item, const std::shared_ptrgetContainer()) { - for (auto stowable_it : container->getStowableItems()) { + for (const auto &stowable_it : container->getStowableItems()) { if ((stowable_it.first)->getID() == item->getID()) { itemDict.push_back(stowable_it); } @@ -6597,14 +6597,14 @@ void Player::openPlayerContainers() { if (itemContainer) { auto cid = item->getAttribute(ItemAttribute_t::OPENCONTAINER); if (cid > 0) { - openContainersList.emplace_back(std::make_pair(cid, itemContainer)); + 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); if (subcid > 0) { - openContainersList.emplace_back(std::make_pair(subcid, subContainer)); + openContainersList.emplace_back(subcid, subContainer); } } } @@ -6822,7 +6822,7 @@ void Player::requestDepotItems() { return; } - for (std::shared_ptr locker : depotLocker->getItemList()) { + for (const std::shared_ptr &locker : depotLocker->getItemList()) { std::shared_ptr c = locker->getContainer(); if (!c || c->empty()) { continue; @@ -6888,7 +6888,7 @@ void Player::requestDepotSearchItem(uint16_t itemId, uint8_t tier) { return; } - for (std::shared_ptr locker : depotLocker->getItemList()) { + for (const std::shared_ptr &locker : depotLocker->getItemList()) { std::shared_ptr c = locker->getContainer(); if (!c || c->empty()) { continue; @@ -6925,7 +6925,7 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool } std::vector> itemsVector; - for (std::shared_ptr locker : depotLocker->getItemList()) { + for (const std::shared_ptr &locker : depotLocker->getItemList()) { std::shared_ptr c = locker->getContainer(); if (!c || c->empty() || // Retrieve from inbox. @@ -6948,7 +6948,7 @@ void Player::retrieveAllItemsFromDepotSearch(uint16_t itemId, uint8_t tier, bool } ReturnValue ret = RETURNVALUE_NOERROR; - for (std::shared_ptr item : itemsVector) { + for (const std::shared_ptr &item : itemsVector) { // First lets try to retrieve the item to the stash retrieve container. if (g_game().tryRetrieveStashItems(static_self_cast(), item)) { continue; @@ -6994,7 +6994,7 @@ std::shared_ptr Player::getItemFromDepotSearch(uint16_t itemId, const Posi } uint8_t index = 0; - for (std::shared_ptr locker : depotLocker->getItemList()) { + for (const std::shared_ptr &locker : depotLocker->getItemList()) { std::shared_ptr c = locker->getContainer(); if (!c || c->empty() || (c->isInbox() && pos.y != 0x21) || // From inbox. (!c->isInbox() && pos.y != 0x20)) { // From depot. @@ -7071,7 +7071,7 @@ std::pair>, uint16_t> Player::getLockerItemsAn std::vector> lockerItems; auto [itemVector, itemMap] = requestLockerItems(depotLocker, false, tier); uint16_t totalCount = 0; - for (auto item : itemVector) { + for (const auto &item : itemVector) { if (!item || item->getID() != itemId) { continue; } @@ -7117,7 +7117,7 @@ bool Player::saySpell( int32_t valueEmote = 0; // Send to client - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { if (std::shared_ptr tmpPlayer = spectator->getPlayer()) { if (g_configManager().getBoolean(EMOTE_SPELLS, __FUNCTION__)) { valueEmote = tmpPlayer->getStorageValue(STORAGEVALUE_EMOTE); @@ -7133,7 +7133,7 @@ bool Player::saySpell( } // Execute lua event method - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { auto tmpPlayer = spectator->getPlayer(); if (!tmpPlayer) { continue; @@ -7777,7 +7777,7 @@ void Player::closeAllExternalContainers() { } } - for (std::shared_ptr container : containerToClose) { + for (const std::shared_ptr &container : containerToClose) { autoCloseContainers(container); } } @@ -7898,7 +7898,7 @@ bool Player::setAccount(uint32_t accountId) { } uint8_t Player::getAccountType() const { - return account ? account->getAccountType() : AccountType::ACCOUNT_TYPE_NORMAL; + return static_cast(account ? account->getAccountType() : static_cast(AccountType::ACCOUNT_TYPE_NORMAL)); } uint32_t Player::getAccountId() const { @@ -7941,7 +7941,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptrgetMembers()) { + for (const auto &partyMember : m_party->getMembers()) { if (partyMember && partyMember->getHazardSystemPoints() < points) { points = partyMember->getHazardSystemPoints(); } @@ -8000,7 +8000,7 @@ void Player::parseAttackDealtHazardSystem(CombatDamage &damage, std::shared_ptr< auto points = getHazardSystemPoints(); if (m_party) { - for (const auto partyMember : m_party->getMembers()) { + for (const auto &partyMember : m_party->getMembers()) { if (partyMember && partyMember->getHazardSystemPoints() < points) { points = partyMember->getHazardSystemPoints(); } @@ -8089,7 +8089,7 @@ void Player::sendLootMessage(const std::string &message) const { if (auto partyLeader = party->getLeader()) { partyLeader->sendTextMessage(MESSAGE_LOOT, message); } - for (const auto partyMember : party->getMembers()) { + for (const auto &partyMember : party->getMembers()) { if (partyMember) { partyMember->sendTextMessage(MESSAGE_LOOT, message); } diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index b3bdd875b20..f61e33a37ef 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -517,10 +517,10 @@ class Player final : public Creature, public Cylinder, public Bankable { void genReservedStorageRange(); - void setGroup(Group* newGroup) { + void setGroup(std::shared_ptr newGroup) { group = newGroup; } - Group* getGroup() const { + std::shared_ptr getGroup() const { return group; } @@ -1041,7 +1041,7 @@ class Player final : public Creature, public Cylinder, public Bankable { bool canFamiliar(uint16_t lookType) const; void addFamiliar(uint16_t lookType); bool removeFamiliar(uint16_t lookType); - bool getFamiliar(const Familiar &familiar) const; + bool getFamiliar(const std::shared_ptr &familiar) const; void setFamiliarLooktype(uint16_t familiarLooktype) { this->defaultOutfit.lookFamiliarsType = familiarLooktype; } @@ -2800,7 +2800,7 @@ class Player final : public Creature, public Cylinder, public Bankable { std::shared_ptr bedItem = nullptr; std::shared_ptr guild = nullptr; GuildRank_ptr guildRank; - Group* group = nullptr; + std::shared_ptr group = nullptr; std::shared_ptr inbox; std::shared_ptr imbuingItem = nullptr; std::shared_ptr tradeItem = nullptr; diff --git a/src/creatures/players/wheel/player_wheel.cpp b/src/creatures/players/wheel/player_wheel.cpp index 8101f51ae42..c4fdbf5e169 100644 --- a/src/creatures/players/wheel/player_wheel.cpp +++ b/src/creatures/players/wheel/player_wheel.cpp @@ -283,7 +283,7 @@ bool PlayerWheel::canPlayerSelectPointOnSlot(WheelSlots_t slot, bool recursive) return true; } } else if (slot == WheelSlots_t::SLOT_GREEN_50) { - return recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot)) || true; + return (recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot))) || true; } // Red quadrant @@ -410,7 +410,7 @@ bool PlayerWheel::canPlayerSelectPointOnSlot(WheelSlots_t slot, bool recursive) return true; } } else if (slot == WheelSlots_t::SLOT_RED_50) { - return recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot)) || true; + return (recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot))) || true; } // Purple quadrant @@ -537,7 +537,7 @@ bool PlayerWheel::canPlayerSelectPointOnSlot(WheelSlots_t slot, bool recursive) return true; } } else if (slot == WheelSlots_t::SLOT_PURPLE_50) { - return recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot)) || true; + return (recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot))) || true; } // Blue quadrant @@ -664,7 +664,7 @@ bool PlayerWheel::canPlayerSelectPointOnSlot(WheelSlots_t slot, bool recursive) return true; } } else if (slot == WheelSlots_t::SLOT_BLUE_50) { - return recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot)) || true; + return (recursive && (getPointsBySlotType(slot) == getMaxPointsPerSlot(slot))) || true; } return false; @@ -1603,7 +1603,7 @@ void PlayerWheel::registerPlayerBonusData() { setSpellInstant("Avatar of Storm", false); } - for (const auto spell : m_playerBonusData.spells) { + for (const auto &spell : m_playerBonusData.spells) { upgradeSpell(spell); } @@ -1759,7 +1759,7 @@ void PlayerWheel::printPlayerWheelMethodsBonusData(const PlayerWheelMethodsBonus auto &spellsVector = bonusData.spells; if (!spellsVector.empty()) { g_logger().debug("Spells:"); - for (const auto spell : bonusData.spells) { + for (const auto &spell : bonusData.spells) { g_logger().debug(" {}", spell); } } @@ -2523,7 +2523,7 @@ void PlayerWheel::reduceAllSpellsCooldownTimer(int32_t value) { } void PlayerWheel::resetUpgradedSpells() { - for (const auto spell : m_learnedSpellsSelected) { + for (const auto &spell : m_learnedSpellsSelected) { if (m_player.hasLearnedInstantSpell(spell)) { m_player.forgetInstantSpell(spell); } diff --git a/src/creatures/players/wheel/wheel_gems.hpp b/src/creatures/players/wheel/wheel_gems.hpp index 762684cb383..668d8fe05db 100644 --- a/src/creatures/players/wheel/wheel_gems.hpp +++ b/src/creatures/players/wheel/wheel_gems.hpp @@ -174,7 +174,7 @@ class GemModifierStrategy { public: explicit GemModifierStrategy(PlayerWheel &wheel) : m_wheel(wheel) { } - virtual ~GemModifierStrategy() { } + virtual ~GemModifierStrategy() = default; virtual void execute() = 0; protected: @@ -211,7 +211,7 @@ class GemModifierStatStrategy : public GemModifierStrategy { class GemModifierRevelationStrategy : public GemModifierStrategy { public: - explicit GemModifierRevelationStrategy(PlayerWheel &wheel, WheelGemAffinity_t affinity, uint16_t value) : + explicit GemModifierRevelationStrategy(PlayerWheel &wheel, WheelGemAffinity_t affinity, [[maybe_unused]] uint16_t value) : GemModifierStrategy(wheel), m_affinity(affinity) { } @@ -224,9 +224,9 @@ class GemModifierRevelationStrategy : public GemModifierStrategy { class GemModifierSpellBonusStrategy : public GemModifierStrategy { public: - explicit GemModifierSpellBonusStrategy(PlayerWheel &wheel, const std::string &spellName, WheelSpells::Bonus bonus) : + explicit GemModifierSpellBonusStrategy(PlayerWheel &wheel, std::string spellName, WheelSpells::Bonus bonus) : GemModifierStrategy(wheel), - m_spellName(spellName), + m_spellName(std::move(spellName)), m_bonus(bonus) { } void execute() override; @@ -256,7 +256,7 @@ class WheelModifierContext { Vocation_t m_vocation; }; -static int32_t getHealthValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { +[[maybe_unused]] static int32_t getHealthValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { static const std::unordered_map> stats = { { WheelGemBasicModifier_t::Vocation_Health, @@ -333,7 +333,7 @@ static int32_t getHealthValue(Vocation_t vocation, WheelGemBasicModifier_t modif return 0; } -static int32_t getManaValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { +[[maybe_unused]] static int32_t getManaValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { static const std::unordered_map> stats = { { WheelGemBasicModifier_t::Vocation_Mana_FireResistance, @@ -409,7 +409,7 @@ static int32_t getManaValue(Vocation_t vocation, WheelGemBasicModifier_t modifie return 0; } -static int32_t getCapacityValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { +[[maybe_unused]] static int32_t getCapacityValue(Vocation_t vocation, WheelGemBasicModifier_t modifier) { static const std::unordered_map> stats = { { WheelGemBasicModifier_t::Vocation_Capacity_FireResistance, diff --git a/src/game/functions/game_reload.cpp b/src/game/functions/game_reload.cpp index 9a7246a86ec..0fc74bcee71 100644 --- a/src/game/functions/game_reload.cpp +++ b/src/game/functions/game_reload.cpp @@ -116,7 +116,6 @@ bool GameReload::reloadCore() const { const bool coreLoaded = g_luaEnvironment().loadFile(coreFolder + "/core.lua", "core.lua") == 0; if (coreLoaded) { - const auto &datapackFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); const bool scriptsLoaded = g_scripts().loadScripts(coreFolder + "/scripts/lib", true, false); if (scriptsLoaded) { return true; diff --git a/src/game/game.cpp b/src/game/game.cpp index d731bd766b6..1743edb2f32 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -94,7 +94,7 @@ namespace InternalGame { } if (blockType != BLOCK_NONE) { - g_game().sendSingleSoundEffect(targetPos, SoundEffect_t::NO_DAMAGE, source); + g_game().sendSingleSoundEffect(targetPos, SoundEffect_t::NO_DAMAGE, std::move(source)); } } @@ -405,15 +405,15 @@ void Game::loadBoostedCreature() { MonsterRace selectedMonster; if (!monsterlist.empty()) { - std::vector monsters; + std::vector m_monsters; for (const auto &[raceId, _name] : BestiaryList) { if (raceId != oldRace) { - monsters.emplace_back(raceId, _name); + m_monsters.emplace_back(raceId, _name); } } - if (!monsters.empty()) { - selectedMonster = monsters[normal_random(0, monsters.size() - 1)]; + if (!m_monsters.empty()) { + selectedMonster = m_monsters[normal_random(0, m_monsters.size() - 1)]; } } @@ -626,7 +626,7 @@ void Game::loadCustomMaps(const std::filesystem::path &customMapPath) { int customMapIndex = 0; for (const auto &entry : fs::directory_iterator(customMapPath)) { - const auto realPath = entry.path(); + const auto &realPath = entry.path(); if (realPath.extension() != ".otbm") { continue; @@ -1133,7 +1133,7 @@ bool Game::removeCreature(std::shared_ptr creature, bool isLogout /* = } // event method - for (auto spectator : spectators) { + for (const auto &spectator : spectators) { spectator->onRemoveCreature(creature, isLogout); } } @@ -1150,7 +1150,7 @@ bool Game::removeCreature(std::shared_ptr creature, bool isLogout /* = removeCreatureCheck(creature); - for (auto summon : creature->getSummons()) { + for (const auto &summon : creature->getSummons()) { summon->setSkillLoss(false); removeCreature(summon); } @@ -1772,12 +1772,10 @@ void Game::playerMoveItem(std::shared_ptr player, const Position &fromPo player->stowItem(item, count, false); return; } - if (!item->isPushable() || item->hasAttribute(ItemAttribute_t::UNIQUEID)) { player->sendCancelMessage(RETURNVALUE_NOTMOVABLE); return; } - ReturnValue ret = internalMoveItem(fromCylinder, toCylinder, toIndex, item, count, nullptr, 0, player); if (ret != RETURNVALUE_NOERROR) { player->sendCancelMessage(ret); @@ -1868,7 +1866,7 @@ ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::s } if (item->getContainer() && !item->isStoreItem()) { - for (std::shared_ptr containerItem : item->getContainer()->getItems(true)) { + for (const std::shared_ptr &containerItem : item->getContainer()->getItems(true)) { if (containerItem->isStoreItem() && ((containerID != ITEM_GOLD_POUCH && containerID != ITEM_DEPOT && containerID != ITEM_STORE_INBOX) || (topParentContainer->getParent() && topParentContainer->getParent()->getContainer() && (!topParentContainer->getParent()->getContainer()->isDepotChest() || topParentContainer->getParent()->getContainer()->getID() != ITEM_STORE_INBOX)))) { return RETURNVALUE_NOTPOSSIBLE; } @@ -1884,7 +1882,7 @@ ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::s } } if (item->getContainer() && !item->isStoreItem()) { - for (std::shared_ptr containerItem : item->getContainer()->getItems(true)) { + for (const std::shared_ptr &containerItem : item->getContainer()->getItems(true)) { if (containerItem->isStoreItem()) { return RETURNVALUE_NOTPOSSIBLE; } @@ -2155,7 +2153,7 @@ ReturnValue Game::internalMoveItem(std::shared_ptr fromCylinder, std:: ReturnValue Game::internalAddItem(std::shared_ptr toCylinder, std::shared_ptr item, int32_t index /*= INDEX_WHEREEVER*/, uint32_t flags /* = 0*/, bool test /* = false*/) { uint32_t remainderCount = 0; - return internalAddItem(toCylinder, item, index, flags, test, remainderCount); + return internalAddItem(std::move(toCylinder), std::move(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) { @@ -2553,7 +2551,7 @@ bool Game::removeMoney(std::shared_ptr cylinder, uint64_t money, uint3 size_t i = 0; while (i < containers.size()) { std::shared_ptr container = containers[i++]; - for (std::shared_ptr item : container->getItemList()) { + for (const std::shared_ptr &item : container->getItemList()) { std::shared_ptr tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); @@ -2848,7 +2846,7 @@ void Game::playerQuickLootCorpse(std::shared_ptr player, std::shared_ptr uint32_t totalLootedGold = 0; uint32_t totalLootedItems = 0; - for (std::shared_ptr item : itemList) { + for (const std::shared_ptr &item : itemList) { uint32_t worth = item->getWorth(); uint16_t baseCount = item->getItemCount(); ObjectCategory_t category = getObjectCategory(item); @@ -3099,7 +3097,7 @@ ReturnValue Game::collectRewardChestItems(std::shared_ptr player, uint32 auto rewardCount = rewardItemsVector.size(); uint32_t movedRewardItems = 0; std::string lootedItemsMessage; - for (auto item : rewardItemsVector) { + for (const auto &item : rewardItemsVector) { // Stop if player not have free capacity if (item && player->getCapacity() < item->getWeight()) { player->sendCancelMessage(RETURNVALUE_NOTENOUGHCAPACITY); @@ -4471,7 +4469,7 @@ void Game::playerWriteItem(uint32_t playerId, uint32_t windowTextId, const std:: return; } - for (auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_TEXTEDIT)) { + for (const auto &creatureEvent : player->getCreatureEvents(CREATURE_EVENT_TEXTEDIT)) { if (!creatureEvent->executeTextEdit(player, writeItem, text)) { player->setWriteItem(nullptr); return; @@ -4836,7 +4834,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t st } if (tradeItemContainer) { - for (std::shared_ptr containerItem : tradeItemContainer->getItems(true)) { + for (const std::shared_ptr &containerItem : tradeItemContainer->getItems(true)) { if (containerItem->isStoreItem()) { player->sendTextMessage(MESSAGE_TRADE, "This item cannot be trade."); return; @@ -5067,7 +5065,7 @@ void Game::playerLookInTrade(uint32_t playerId, bool lookAtCounterOffer, uint8_t size_t i = 0; while (i < containers.size()) { std::shared_ptr container = containers[i++]; - for (std::shared_ptr item : container->getItemList()) { + for (const std::shared_ptr &item : container->getItemList()) { std::shared_ptr tmpContainer = item->getContainer(); if (tmpContainer) { containers.push_back(tmpContainer); @@ -5519,7 +5517,7 @@ void Game::playerSetManagedContainer(uint32_t playerId, ObjectCategory_t categor std::shared_ptr container = thing->getContainer(); auto allowConfig = g_configManager().getBoolean(TOGGLE_GOLD_POUCH_ALLOW_ANYTHING, __FUNCTION__) || g_configManager().getBoolean(TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY, __FUNCTION__); - if (!container || (container->getID() == ITEM_GOLD_POUCH && category != OBJECTCATEGORY_GOLD) && !allowConfig) { + if (!container || ((container->getID() == ITEM_GOLD_POUCH && category != OBJECTCATEGORY_GOLD) && !allowConfig)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -5849,7 +5847,6 @@ void Game::playerCloseImbuementWindow(uint32_t playerid) { } player->setImbuingItem(nullptr); - return; } void Game::playerTurn(uint32_t playerId, Direction dir) { @@ -6157,7 +6154,7 @@ void Game::playerSpeakToNpc(std::shared_ptr player, const std::string &t } std::shared_ptr Game::createPlayerTask(uint32_t delay, std::function f, std::string context) const { - return Player::createPlayerTask(delay, f, context); + return Player::createPlayerTask(delay, std::move(f), std::move(context)); } //-- @@ -6742,7 +6739,7 @@ void Game::handleHazardSystemAttack(CombatDamage &damage, std::shared_ptr attackerPlayer, std::shared_ptr targetMonster) { if (!spectators.empty()) { - for (auto spectator : spectators) { + for (const auto &spectator : spectators) { if (!spectator) { continue; } @@ -6912,7 +6909,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt if (damage.origin != ORIGIN_NONE) { const auto events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); if (!events.empty()) { - for (const auto creatureEvent : events) { + for (const auto &creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -7131,7 +7128,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt if (damage.origin != ORIGIN_NONE) { const auto events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { - for (const auto creatureEvent : events) { + for (const auto &creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } healthChange = damage.primary.value + damage.secondary.value; @@ -7235,7 +7232,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt if (damage.origin != ORIGIN_NONE) { const auto events = target->getCreatureEvents(CREATURE_EVENT_HEALTHCHANGE); if (!events.empty()) { - for (const auto creatureEvent : events) { + for (const auto &creatureEvent : events) { creatureEvent->executeHealthChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -7260,7 +7257,7 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt if (realDamage == 0) { return true; } else if (realDamage >= targetHealth) { - for (const auto creatureEvent : target->getCreatureEvents(CREATURE_EVENT_PREPAREDEATH)) { + for (const auto &creatureEvent : target->getCreatureEvents(CREATURE_EVENT_PREPAREDEATH)) { if (!creatureEvent->executeOnPrepareDeath(target, attacker)) { return false; } @@ -7336,7 +7333,7 @@ void Game::sendDamageMessageAndEffects( sendEffects(target, damage, targetPos, message, spectators); if (shouldSendMessage(message)) { - sendMessages(attacker, target, damage, targetPos, attackerPlayer, targetPlayer, message, spectators, realDamage); + sendMessages(std::move(attacker), target, damage, targetPos, std::move(attackerPlayer), std::move(targetPlayer), message, spectators, realDamage); } } @@ -7375,7 +7372,7 @@ void Game::sendMessages( std::string spectatorMessage; - for (std::shared_ptr spectator : spectators) { + for (const std::shared_ptr &spectator : spectators) { std::shared_ptr tmpPlayer = spectator->getPlayer(); if (!tmpPlayer || tmpPlayer->getPosition().z != targetPos.z) { continue; @@ -7496,7 +7493,7 @@ 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, target, realDamage); + g_iobestiary().parseCharmCombat(charm, attackerPlayer, std::move(target), realDamage); } } } @@ -7589,7 +7586,7 @@ bool Game::combatChangeMana(std::shared_ptr attacker, std::shared_ptr< if (damage.origin != ORIGIN_NONE) { const auto events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { - for (const auto creatureEvent : events) { + for (const auto &creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -7683,7 +7680,7 @@ bool Game::combatChangeMana(std::shared_ptr attacker, std::shared_ptr< if (damage.origin != ORIGIN_NONE) { const auto events = target->getCreatureEvents(CREATURE_EVENT_MANACHANGE); if (!events.empty()) { - for (const auto creatureEvent : events) { + for (const auto &creatureEvent : events) { creatureEvent->executeManaChange(target, attacker, damage); } damage.origin = ORIGIN_NONE; @@ -7991,7 +7988,7 @@ void Game::broadcastMessage(const std::string &text, MessageClasses type) const void Game::updateCreatureWalkthrough(std::shared_ptr creature) { // Send to clients - for (const auto spectator : Spectators().find(creature->getPosition(), true)) { + for (const auto &spectator : Spectators().find(creature->getPosition(), true)) { const auto &tmpPlayer = spectator->getPlayer(); tmpPlayer->sendCreatureWalkthrough(creature, tmpPlayer->canWalkthroughEx(creature)); } @@ -8224,7 +8221,7 @@ void Game::playerLeaveParty(uint32_t playerId) { } std::shared_ptr party = player->getParty(); - if (!party || player->hasCondition(CONDITION_INFIGHT) && !player->getZoneType() == ZONE_PROTECTION) { + if (!party || (player->hasCondition(CONDITION_INFIGHT) && !player->getZoneType() == ZONE_PROTECTION)) { player->sendTextMessage(TextMessage(MESSAGE_FAILURE, "You cannot leave party, contact the administrator.")); return; } @@ -8302,7 +8299,7 @@ void Game::playerCyclopediaCharacterInfo(std::shared_ptr player, uint32_ query << "SELECT `time`, `level`, `killed_by`, `mostdamage_by`, (select count(*) FROM `player_deaths` WHERE `player_id` = " << playerGUID << ") as `entries` FROM `player_deaths` WHERE `player_id` = " << playerGUID << " ORDER BY `time` DESC LIMIT " << offset << ", " << entriesPerPage; uint32_t playerID = player->getID(); - std::function callback = [playerID, page, entriesPerPage](DBResult_ptr result, bool) { + std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { std::shared_ptr player = g_game().getPlayerByID(playerID); if (!player) { return; @@ -8367,7 +8364,7 @@ void Game::playerCyclopediaCharacterInfo(std::shared_ptr player, uint32_ query << "SELECT `d`.`time`, `d`.`killed_by`, `d`.`mostdamage_by`, `d`.`unjustified`, `d`.`mostdamage_unjustified`, `p`.`name`, (select count(*) FROM `player_deaths` WHERE ((`killed_by` = " << escapedName << " AND `is_player` = 1) OR (`mostdamage_by` = " << escapedName << " 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` = " << escapedName << " AND `d`.`is_player` = 1) OR (`d`.`mostdamage_by` = " << escapedName << " AND `d`.`mostdamage_is_player` = 1)) ORDER BY `time` DESC LIMIT " << offset << ", " << entriesPerPage; uint32_t playerID = player->getID(); - std::function callback = [playerID, page, entriesPerPage](DBResult_ptr result, bool) { + std::function callback = [playerID, page, entriesPerPage](const DBResult_ptr &result, bool) { std::shared_ptr player = g_game().getPlayerByID(playerID); if (!player) { return; @@ -8812,13 +8809,13 @@ namespace { auto [itemVector, totalCount] = player->getLockerItemsAndCountById(depotLocker, tier, itemType.id); if (removeAmount > 0) { - if (totalCount == 0 || itemVector.size() == 0) { + if (totalCount == 0 || itemVector.empty()) { offerStatus << "Player " << player->getName() << " not have item for create offer"; return false; } uint32_t count = 0; - for (auto item : itemVector) { + for (const auto &item : itemVector) { if (!item) { continue; } @@ -8904,7 +8901,7 @@ bool checkCanInitCreateMarketOffer(std::shared_ptr player, uint8_t type, return false; } - if (amount == 0 || !it.stackable && amount > 2000 || it.stackable && amount > 64000) { + if (amount == 0 || (!it.stackable && amount > 2000) || (it.stackable && amount > 64000)) { offerStatus << "Failed to load amount " << amount << " for player " << player->getName(); return false; } @@ -9123,7 +9120,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 return; } - if (amount == 0 || !it.stackable && amount > 2000 || it.stackable && amount > 64000 || amount > offer.amount) { + if (amount == 0 || (!it.stackable && amount > 2000) || (it.stackable && amount > 64000) || amount > offer.amount) { offerStatus << "Invalid offer amount " << amount << " for player " << player->getName(); return; } @@ -9372,7 +9369,7 @@ void Game::parsePlayerExtendedOpcode(uint32_t playerId, uint8_t opcode, const st return; } - for (const auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_EXTENDED_OPCODE)) { + for (const auto &creatureEvent : player->getCreatureEvents(CREATURE_EVENT_EXTENDED_OPCODE)) { creatureEvent->executeExtendedOpcode(player, opcode, buffer); } } @@ -9424,7 +9421,7 @@ void Game::playerAnswerModalWindow(uint32_t playerId, uint32_t modalWindowId, ui player->setBedItem(nullptr); } else { - for (const auto creatureEvent : player->getCreatureEvents(CREATURE_EVENT_MODALWINDOW)) { + for (const auto &creatureEvent : player->getCreatureEvents(CREATURE_EVENT_MODALWINDOW)) { creatureEvent->executeModalWindow(player, modalWindowId, button, choice); } } @@ -9694,7 +9691,7 @@ void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t st bool isPodiumOfRenown = itemId == ITEM_PODIUM_OF_RENOWN1 || itemId == ITEM_PODIUM_OF_RENOWN2; if (!isPodiumOfRenown) { auto lookTypeExAttribute = item->getCustomAttribute("LookTypeEx"); - if (!isMonsterVisible || podiumRaceId == 0 || lookTypeExAttribute && lookTypeExAttribute->getInteger() == 39003) { + if (!isMonsterVisible || podiumRaceId == 0 || (lookTypeExAttribute && lookTypeExAttribute->getInteger() == 39003)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -9910,7 +9907,7 @@ void Game::removeGuild(uint32_t guildId) { void Game::internalRemoveItems(const std::vector> &itemVector, uint32_t amount, bool stackable) { if (stackable) { - for (std::shared_ptr item : itemVector) { + for (const std::shared_ptr &item : itemVector) { if (item->getItemCount() > amount) { internalRemoveItem(item, amount); break; @@ -9920,7 +9917,7 @@ void Game::internalRemoveItems(const std::vector> &itemVec } } } else { - for (std::shared_ptr item : itemVector) { + for (const std::shared_ptr &item : itemVector) { internalRemoveItem(item); } } @@ -9935,7 +9932,7 @@ std::shared_ptr Game::getBedBySleeper(uint32_t guid) const { } void Game::setBedSleeper(std::shared_ptr bed, uint32_t guid) { - bedSleepersMap[guid] = bed; + bedSleepersMap[guid] = std::move(bed); } void Game::removeBedSleeper(uint32_t guid) { @@ -10489,7 +10486,7 @@ void Game::playerRewardChestCollect(uint32_t playerId, const Position &pos, uint bool Game::tryRetrieveStashItems(std::shared_ptr player, std::shared_ptr item) { ObjectCategory_t category = getObjectCategory(item); - return internalCollectManagedItems(player, item, category, false) == RETURNVALUE_NOERROR; + return internalCollectManagedItems(std::move(player), item, category, false) == RETURNVALUE_NOERROR; } std::unique_ptr &Game::getIOWheel() { @@ -10621,7 +10618,7 @@ void Game::registerAchievement(uint16_t id, std::string name, std::string descri m_achievements[id] = Achievement(); m_achievements[id].id = id; m_achievements[id].name = name; - m_achievements[id].description = description; + m_achievements[id].description = std::move(description); m_achievements[id].secret = secret; m_achievements[id].grade = grade; m_achievements[id].points = points; diff --git a/src/game/scheduling/events_scheduler.cpp b/src/game/scheduling/events_scheduler.cpp index c57f84b667c..a86254fa35c 100644 --- a/src/game/scheduling/events_scheduler.cpp +++ b/src/game/scheduling/events_scheduler.cpp @@ -27,7 +27,6 @@ bool EventsScheduler::loadScheduleEventFromXml() { int daysMath = ((timePtr->tm_year + 1900) * 365) + ((timePtr->tm_mon + 1) * 30) + (timePtr->tm_mday); // Keep track of loaded scripts to check for duplicates - int count = 0; phmap::flat_hash_set loadedScripts; std::map eventsOnSameDay; for (const auto &eventNode : doc.child("events").children()) { diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index 0498b40e29f..bcbfc531468 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -66,7 +66,7 @@ bool IOLoginDataLoad::preLoadPlayer(std::shared_ptr player, const std::s } player->setGUID(result->getNumber("id")); - Group* group = g_game().groups.getGroup(result->getNumber("group_id")); + std::shared_ptr group = g_game().groups.getGroup(result->getNumber("group_id")); if (!group) { g_logger().error("Player {} has group id {} which doesn't exist", player->name, result->getNumber("group_id")); return false; @@ -118,7 +118,7 @@ bool IOLoginDataLoad::loadPlayerFirst(std::shared_ptr player, DBResult_p player->setAccount(result->getNumber("account_id")); } - Group* group = g_game().groups.getGroup(result->getNumber("group_id")); + std::shared_ptr group = g_game().groups.getGroup(result->getNumber("group_id")); if (!group) { g_logger().error("Player {} has group id {} which doesn't exist", player->name, result->getNumber("group_id")); return false; diff --git a/src/io/functions/iologindata_save_player.cpp b/src/io/functions/iologindata_save_player.cpp index 82ba286d622..eccb88c8229 100644 --- a/src/io/functions/iologindata_save_player.cpp +++ b/src/io/functions/iologindata_save_player.cpp @@ -436,7 +436,7 @@ bool IOLoginDataSave::savePlayerBestiarySystem(std::shared_ptr player) { query << "`UnlockedRunesBit` = " << player->UnlockedRunesBit << ","; PropWriteStream propBestiaryStream; - for (const auto trackedType : player->getCyclopediaMonsterTrackerSet(false)) { + for (const auto &trackedType : player->getCyclopediaMonsterTrackerSet(false)) { propBestiaryStream.write(trackedType->info.raceid); } size_t trackerSize; @@ -737,7 +737,7 @@ bool IOLoginDataSave::savePlayerBosstiary(std::shared_ptr player) { // Bosstiary tracker PropWriteStream stream; - for (const auto monsterType : player->getCyclopediaMonsterTrackerSet(true)) { + for (const auto &monsterType : player->getCyclopediaMonsterTrackerSet(true)) { if (!monsterType) { continue; } diff --git a/src/io/iobestiary.cpp b/src/io/iobestiary.cpp index f7305d8503c..c544021367e 100644 --- a/src/io/iobestiary.cpp +++ b/src/io/iobestiary.cpp @@ -97,7 +97,7 @@ bool IOBestiary::parseCharmCombat(const std::shared_ptr charm, std::share std::shared_ptr IOBestiary::getBestiaryCharm(charmRune_t activeCharm, bool force /*= false*/) const { const auto charmInternal = g_game().getCharmList(); - for (const auto tmpCharm : charmInternal) { + for (const auto &tmpCharm : charmInternal) { if (tmpCharm->id == activeCharm) { return tmpCharm; } @@ -169,7 +169,7 @@ void IOBestiary::setCharmRuneCreature(std::shared_ptr player, const std: std::list IOBestiary::getCharmUsedRuneBitAll(std::shared_ptr player) { int32_t input = player->getUsedRunesBit(); - ; + int8_t i = 0; std::list rtn; while (input != 0) { @@ -191,7 +191,7 @@ uint16_t IOBestiary::getBestiaryRaceUnlocked(std::shared_ptr player, Bes uint16_t count = 0; std::map besty_l = g_game().getBestiaryList(); - for (auto it : besty_l) { + for (const auto &it : besty_l) { const auto mtype = g_monsters().getMonsterType(it.second); if (mtype && mtype->info.bestiaryRace == race && player->getBestiaryKillCount(mtype->info.raceid) > 0) { count++; @@ -271,7 +271,7 @@ int32_t IOBestiary::bitToggle(int32_t input, const std::shared_ptr charm, return CHARM_NONE; } - int32_t returnToggle = 0; + int32_t returnToggle; int32_t binary = charm->binary; if (on) { returnToggle = input | binary; @@ -307,7 +307,7 @@ void IOBestiary::sendBuyCharmRune(std::shared_ptr player, charmRune_t ru player->setUnlockedRunesBit(value); } else if (action == 1) { std::list usedRunes = getCharmUsedRuneBitAll(player); - uint16_t limitRunes = 0; + uint16_t limitRunes; if (player->isPremium()) { if (player->hasCharmExpansion()) { @@ -343,7 +343,6 @@ void IOBestiary::sendBuyCharmRune(std::shared_ptr player, charmRune_t ru player->sendFYIBox("You don't have enough gold."); } player->BestiarysendCharms(); - return; } std::map IOBestiary::getMonsterElements(const std::shared_ptr mtype) const { diff --git a/src/io/iobestiary.hpp b/src/io/iobestiary.hpp index 9cb2ef2fe55..a521ce68852 100644 --- a/src/io/iobestiary.hpp +++ b/src/io/iobestiary.hpp @@ -20,16 +20,18 @@ class Charm { public: Charm() = default; Charm(std::string initname, charmRune_t initcharmRune_t, std::string initdescription, charm_t inittype, uint16_t initpoints, int32_t initbinary) : - name(initname), id(initcharmRune_t), description(initdescription), type(inittype), points(initpoints), binary(initbinary) { } + name(std::move(initname)), id(initcharmRune_t), description(std::move(initdescription)), type(inittype), points(initpoints), binary(initbinary) { } virtual ~Charm() = default; std::string name; + charmRune_t id = CHARM_NONE; + std::string description; + charm_t type; + uint16_t points = 0; + int32_t binary = 0; std::string cancelMsg; std::string logMsg; - std::string description; - charm_t type; - charmRune_t id = CHARM_NONE; CombatType_t dmgtype = COMBAT_NONE; uint16_t effect = CONST_ME_NONE; @@ -38,8 +40,6 @@ class Charm { uint16_t percent = 0; int8_t chance = 0; - uint16_t points = 0; - int32_t binary = 0; }; class IOBestiary { diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index 4c6b95dc32e..46426451ddc 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -72,7 +72,7 @@ uint8_t IOLoginData::getAccountType(uint32_t accountId) { void IOLoginData::updateOnlineStatus(uint32_t guid, bool login) { static phmap::flat_hash_map updateOnline; - if (login && updateOnline.find(guid) != updateOnline.end() || guid <= 0) { + if ((login && updateOnline.find(guid) != updateOnline.end()) || guid <= 0) { return; } diff --git a/src/io/iomap.cpp b/src/io/iomap.cpp index 4edfefa66d1..d50d9b2804f 100644 --- a/src/io/iomap.cpp +++ b/src/io/iomap.cpp @@ -122,8 +122,6 @@ void IOMap::parseTileArea(FileStream &stream, Map &map, const Position &pos) { const uint16_t base_y = stream.getU16(); const uint8_t base_z = stream.getU8(); - bool tileIsStatic = false; - while (stream.startNode()) { const uint8_t tileType = stream.getU8(); if (tileType != OTBM_HOUSETILE && tileType != OTBM_TILE) { @@ -166,9 +164,6 @@ void IOMap::parseTileArea(FileStream &stream, Map &map, const Position &pos) { const auto &iType = Item::items[id]; if (!tile->isHouse() || (!iType.isBed() && !iType.isTrashHolder())) { - if (iType.blockSolid) { - tileIsStatic = true; - } const auto item = std::make_shared(); item->id = id; @@ -194,10 +189,6 @@ void IOMap::parseTileArea(FileStream &stream, Map &map, const Position &pos) { const auto &iType = Item::items[id]; - if (iType.blockSolid) { - tileIsStatic = true; - } - const auto item = std::make_shared(); item->id = id; diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index 5d2ffd98769..63ce657741a 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -383,7 +383,7 @@ bool Container::isInsideContainerWithId(const uint16_t id) { } bool Container::isAnyKindOfRewardChest() { - return getID() == ITEM_REWARD_CHEST || getID() == ITEM_REWARD_CONTAINER && getParent() && getParent()->getContainer() && getParent()->getContainer()->getID() == ITEM_REWARD_CHEST || isBrowseFieldAndHoldsRewardChest(); + return getID() == ITEM_REWARD_CHEST || (getID() == ITEM_REWARD_CONTAINER && getParent() && getParent()->getContainer() && getParent()->getContainer()->getID() == ITEM_REWARD_CHEST) || isBrowseFieldAndHoldsRewardChest(); } bool Container::isAnyKindOfRewardContainer() { diff --git a/src/items/item.cpp b/src/items/item.cpp index 104efc7f925..823eb13b393 100644 --- a/src/items/item.cpp +++ b/src/items/item.cpp @@ -3237,7 +3237,7 @@ std::shared_ptr Item::transform(uint16_t itemId, uint16_t itemCount /*= -1 } std::shared_ptr newItem; - if (itemCount == -1) { + if (itemCount == 0) { newItem = Item::CreateItem(itemId, 1); } else { newItem = Item::CreateItem(itemId, itemCount); diff --git a/src/items/tile.cpp b/src/items/tile.cpp index ca354700f22..11e3fafd6fd 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -791,7 +791,7 @@ ReturnValue Tile::queryAdd(int32_t, const std::shared_ptr &thing, uint32_ if (ground) { const ItemType &iiType = Item::items[ground->getID()]; if (iiType.blockSolid) { - if (!iiType.pickupable && iiType.type != ITEM_TYPE_TRASHHOLDER || item->isMagicField() || item->isBlocking()) { + if ((!iiType.pickupable && iiType.type != ITEM_TYPE_TRASHHOLDER) || item->isMagicField() || item->isBlocking()) { if (!item->isPickupable() && !item->isCarpet()) { return RETURNVALUE_NOTENOUGHROOM; } @@ -1575,7 +1575,7 @@ void Tile::internalAddThing(uint32_t, std::shared_ptr thing) { if (!thing) { return; } - for (const auto zone : getZones()) { + for (const auto &zone : getZones()) { zone->thingAdded(thing); } diff --git a/src/items/weapons/weapons.hpp b/src/items/weapons/weapons.hpp index 5b2b260e2ee..59cc23636e2 100644 --- a/src/items/weapons/weapons.hpp +++ b/src/items/weapons/weapons.hpp @@ -200,11 +200,11 @@ class Weapon : public Script { return m_isDisabledChain; } - const WeaponType_t getWeaponType() const { + WeaponType_t getWeaponType() const { return weaponType; } - const std::shared_ptr getCombat() const { + std::shared_ptr getCombat() const { if (!m_combat) { g_logger().error("Weapon::getCombat() - m_combat is nullptr"); return nullptr; diff --git a/src/lib/metrics/metrics.cpp b/src/lib/metrics/metrics.cpp index cf11060125a..f005c79c966 100644 --- a/src/lib/metrics/metrics.cpp +++ b/src/lib/metrics/metrics.cpp @@ -87,7 +87,7 @@ void Metrics::shutdown() { metrics_api::Provider::SetMeterProvider(none); } -ScopedLatency::ScopedLatency(std::string_view name, const std::string &histogramName, const std::string &scopeKey) : +ScopedLatency::ScopedLatency(const std::string_view &name, const std::string &histogramName, const std::string &scopeKey) : ScopedLatency(name, g_metrics().latencyHistograms[histogramName], { { scopeKey, std::string(name) } }, g_metrics().defaultContext) { if (histogram == nullptr) { stopped = true; diff --git a/src/lib/metrics/metrics.hpp b/src/lib/metrics/metrics.hpp index 279ea5f91c5..1e3dbe31086 100644 --- a/src/lib/metrics/metrics.hpp +++ b/src/lib/metrics/metrics.hpp @@ -54,9 +54,9 @@ namespace metrics { class ScopedLatency { public: - explicit ScopedLatency(std::string_view name, const std::string &histogramName, const std::string &scopeKey); - explicit ScopedLatency(std::string_view name, Histogram &histogram, std::map attrs = {}, opentelemetry::context::Context context = opentelemetry::context::Context()) : - begin(std::chrono::steady_clock::now()), histogram(histogram), attrs(attrs), context(context) { + explicit ScopedLatency(const std::string_view &name, const std::string &histogramName, const std::string &scopeKey); + explicit ScopedLatency([[maybe_unused]] const std::string_view &name, Histogram &histogram, std::map attrs = {}, opentelemetry::context::Context context = opentelemetry::context::Context()) : + begin(std::chrono::steady_clock::now()), histogram(histogram), attrs(std::move(attrs)), context(std::move(context)) { } void stop(); @@ -64,10 +64,10 @@ namespace metrics { ~ScopedLatency(); private: - opentelemetry::context::Context context; - Histogram &histogram; std::chrono::steady_clock::time_point begin; + Histogram &histogram; std::map attrs; + opentelemetry::context::Context context; bool stopped { false }; }; @@ -94,7 +94,7 @@ namespace metrics { class Metrics final { public: - Metrics() { } + Metrics() = default; ~Metrics() = default; void init(Options opts); diff --git a/src/lua/creature/movement.cpp b/src/lua/creature/movement.cpp index 0af09476ed8..b302877b3d3 100644 --- a/src/lua/creature/movement.cpp +++ b/src/lua/creature/movement.cpp @@ -24,8 +24,6 @@ void MoveEvents::clear(bool isFromXML /*= false*/) { for (int moveEventType = 0; moveEventType < MOVE_EVENT_LAST; ++moveEventType) { auto &eventList = moveEventList.moveEvent[moveEventType]; - int originalSize = eventList.size(); - eventList.remove_if([&](const std::shared_ptr &moveEvent) { bool removed = moveEvent && moveEvent->isFromXML(); if (removed) { diff --git a/src/lua/creature/movement.hpp b/src/lua/creature/movement.hpp index 485454a0564..4ce4297b0f5 100644 --- a/src/lua/creature/movement.hpp +++ b/src/lua/creature/movement.hpp @@ -180,7 +180,7 @@ class MoveEvent final : public Script, public SharedObject { } void addVocEquipMap(std::string vocName) { uint16_t vocationId = g_vocations().getVocationId(vocName); - if (vocationId != -1) { + if (vocationId != 65535) { vocEquipMap[vocationId] = true; } } diff --git a/src/lua/functions/core/game/config_functions.cpp b/src/lua/functions/core/game/config_functions.cpp index a84c500b985..d0e77a69352 100644 --- a/src/lua/functions/core/game/config_functions.cpp +++ b/src/lua/functions/core/game/config_functions.cpp @@ -22,7 +22,6 @@ void ConfigFunctions::init(lua_State* L) { #define registerMagicEnumIn(L, tableName, enumValue) \ do { \ - auto number = magic_enum::enum_integer(enumValue); \ auto name = magic_enum::enum_name(enumValue).data(); \ registerVariable(L, tableName, name, value); \ } while (0) diff --git a/src/lua/functions/core/game/game_functions.cpp b/src/lua/functions/core/game/game_functions.cpp index a91889e43bc..0fdbc96f4d6 100644 --- a/src/lua/functions/core/game/game_functions.cpp +++ b/src/lua/functions/core/game/game_functions.cpp @@ -214,7 +214,7 @@ int GameFunctions::luaGameGetMonsterTypes(lua_State* L) { const auto type = g_monsters().monsters; lua_createtable(L, type.size(), 0); - for (const auto [typeName, mType] : type) { + for (const auto &[typeName, mType] : type) { pushUserdata(L, mType); setMetatable(L, -1, "MonsterType"); lua_setfield(L, -2, typeName.c_str()); @@ -517,7 +517,7 @@ int GameFunctions::luaGameGetBestiaryCharm(lua_State* L) { lua_createtable(L, c_list.size(), 0); int index = 0; - for (const auto charmPtr : c_list) { + for (const auto &charmPtr : c_list) { pushUserdata(L, charmPtr); setMetatable(L, -1, "Charm"); lua_rawseti(L, -2, ++index); @@ -699,7 +699,7 @@ int GameFunctions::luaGameGetInfluencedMonsters(lua_State* L) { int GameFunctions::luaGameGetLadderIds(lua_State* L) { // Game.getLadderIds() - const auto ladders = Item::items.getLadders(); + const auto &ladders = Item::items.getLadders(); lua_createtable(L, static_cast(ladders.size()), 0); int index = 0; for (const auto ladderId : ladders) { @@ -721,7 +721,7 @@ int GameFunctions::luaGameGetDummies(lua_State* L) { local rate = dummies[1] -- Retrieve dummy rate */ - const auto dummies = Item::items.getDummys(); + const auto &dummies = Item::items.getDummys(); lua_createtable(L, dummies.size(), 0); for (const auto &[dummyId, rate] : dummies) { lua_pushnumber(L, static_cast(rate)); diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index a633afe9749..7a40cc426f1 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -54,7 +54,7 @@ int CreatureFunctions::luaCreatureGetEvents(lua_State* L) { lua_createtable(L, static_cast(eventList.size()), 0); int index = 0; - for (const auto eventPtr : eventList) { + for (const auto &eventPtr : eventList) { pushString(L, eventPtr->getName()); lua_rawseti(L, -2, ++index); } diff --git a/src/lua/functions/creatures/monster/charm_functions.cpp b/src/lua/functions/creatures/monster/charm_functions.cpp index 48f7ff5aec9..d456f1c96a8 100644 --- a/src/lua/functions/creatures/monster/charm_functions.cpp +++ b/src/lua/functions/creatures/monster/charm_functions.cpp @@ -18,7 +18,7 @@ int CharmFunctions::luaCharmCreate(lua_State* L) { if (isNumber(L, 2)) { charmRune_t charmid = getNumber(L, 2); const auto charmList = g_game().getCharmList(); - for (const auto charm : charmList) { + for (const auto &charm : charmList) { if (charm->id == charmid) { pushUserdata(L, charm); setMetatable(L, -1, "Charm"); diff --git a/src/lua/functions/creatures/monster/monster_spell_functions.cpp b/src/lua/functions/creatures/monster/monster_spell_functions.cpp index ee00fd43af7..a20d57008d2 100644 --- a/src/lua/functions/creatures/monster/monster_spell_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_spell_functions.cpp @@ -170,7 +170,7 @@ int MonsterSpellFunctions::luaMonsterSpellSetConditionType(lua_State* L) { const auto spell = getUserdataShared(L, 1); if (spell) { auto conditionType = getNumber(L, 2); - if (conditionType == -1) { + if (conditionType == 254) { g_logger().error("[{}] trying to register condition type none for monster: {}", __FUNCTION__, spell->name); reportErrorFunc(fmt::format("trying to register condition type none for monster: {}", spell->name)); pushBoolean(L, false); diff --git a/src/lua/functions/creatures/npc/npc_functions.cpp b/src/lua/functions/creatures/npc/npc_functions.cpp index 43c2950a802..8c19a4ede0a 100644 --- a/src/lua/functions/creatures/npc/npc_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_functions.cpp @@ -400,7 +400,7 @@ int NpcFunctions::luaNpcOpenShopWindowTable(lua_State* L) { if (itemName.empty()) { itemName = Item::items[itemId].name; } - items.emplace_back(itemId, subType, buyPrice, sellPrice, storageKey, storageValue, itemName); + items.emplace_back(itemId, itemName, subType, buyPrice, sellPrice, storageKey, storageValue); lua_pop(L, 8); } lua_pop(L, 3); diff --git a/src/lua/functions/creatures/player/group_functions.cpp b/src/lua/functions/creatures/player/group_functions.cpp index 0ea195fe745..5acc16d72a9 100644 --- a/src/lua/functions/creatures/player/group_functions.cpp +++ b/src/lua/functions/creatures/player/group_functions.cpp @@ -17,7 +17,7 @@ int GroupFunctions::luaGroupCreate(lua_State* L) { // Group(id) uint32_t id = getNumber(L, 2); - Group* group = g_game().groups.getGroup(id); + std::shared_ptr group = g_game().groups.getGroup(id); if (group) { pushUserdata(L, group); setMetatable(L, -1, "Group"); @@ -29,7 +29,7 @@ int GroupFunctions::luaGroupCreate(lua_State* L) { int GroupFunctions::luaGroupGetId(lua_State* L) { // group:getId() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { lua_pushnumber(L, group->id); } else { @@ -40,7 +40,7 @@ int GroupFunctions::luaGroupGetId(lua_State* L) { int GroupFunctions::luaGroupGetName(lua_State* L) { // group:getName() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { pushString(L, group->name); } else { @@ -51,7 +51,7 @@ int GroupFunctions::luaGroupGetName(lua_State* L) { int GroupFunctions::luaGroupGetFlags(lua_State* L) { // group:getFlags() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { std::bitset flags; for (uint8_t i = 0; i < magic_enum::enum_integer(PlayerFlags_t::FlagLast); ++i) { @@ -68,7 +68,7 @@ int GroupFunctions::luaGroupGetFlags(lua_State* L) { int GroupFunctions::luaGroupGetAccess(lua_State* L) { // group:getAccess() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { pushBoolean(L, group->access); } else { @@ -79,7 +79,7 @@ int GroupFunctions::luaGroupGetAccess(lua_State* L) { int GroupFunctions::luaGroupGetMaxDepotItems(lua_State* L) { // group:getMaxDepotItems() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { lua_pushnumber(L, group->maxDepotItems); } else { @@ -90,7 +90,7 @@ int GroupFunctions::luaGroupGetMaxDepotItems(lua_State* L) { int GroupFunctions::luaGroupGetMaxVipEntries(lua_State* L) { // group:getMaxVipEntries() - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { lua_pushnumber(L, group->maxVipEntries); } else { @@ -101,7 +101,7 @@ int GroupFunctions::luaGroupGetMaxVipEntries(lua_State* L) { int GroupFunctions::luaGroupHasFlag(lua_State* L) { // group:hasFlag(flag) - Group* group = getUserdata(L, 1); + std::shared_ptr group = getUserdataShared(L, 1); if (group) { auto flag = static_cast(getNumber(L, 2)); pushBoolean(L, group->flags[Groups::getFlagNumber(flag)]); diff --git a/src/lua/functions/creatures/player/group_functions.hpp b/src/lua/functions/creatures/player/group_functions.hpp index ecc3ac07280..4a33d1b988e 100644 --- a/src/lua/functions/creatures/player/group_functions.hpp +++ b/src/lua/functions/creatures/player/group_functions.hpp @@ -14,7 +14,7 @@ class GroupFunctions final : LuaScriptInterface { public: static void init(lua_State* L) { - registerClass(L, "Group", "", GroupFunctions::luaGroupCreate); + registerSharedClass(L, "Group", "", GroupFunctions::luaGroupCreate); registerMetaMethod(L, "Group", "__eq", GroupFunctions::luaUserdataCompare); registerMethod(L, "Group", "getId", GroupFunctions::luaGroupGetId); diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 51dd79638ab..7f4d96f3773 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -1604,7 +1604,7 @@ int PlayerFunctions::luaPlayerGetGroup(lua_State* L) { int PlayerFunctions::luaPlayerSetGroup(lua_State* L) { // player:setGroup(group) - Group* group = getUserdata(L, 2); + std::shared_ptr group = getUserdataShared(L, 2); if (!group) { pushBoolean(L, false); return 1; diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index 7967e21c3cc..842622b2af5 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -45,7 +45,7 @@ void House::setNewOwnerGuid(int32_t newOwnerGuid, bool serverStartup) { void House::clearHouseInfo(bool preventOwnerDeletion) { // Remove players from beds - for (auto bed : bedsList) { + for (const auto &bed : bedsList) { if (bed->getSleeper() != 0) { bed->wakeUp(nullptr); } @@ -60,7 +60,7 @@ void House::clearHouseInfo(bool preventOwnerDeletion) { setAccessList(SUBOWNER_LIST, ""); setAccessList(GUEST_LIST, ""); - for (auto door : doorList) { + for (const auto &door : doorList) { door->setAccessList(""); } } @@ -73,7 +73,7 @@ bool House::tryTransferOwnership(std::shared_ptr player, bool serverStar transferSuccess = transferToDepot(); } - for (auto tile : houseTiles) { + for (const auto &tile : houseTiles) { if (const CreatureVector* creatures = tile->getCreatures()) { for (int32_t i = creatures->size(); --i >= 0;) { const auto creature = (*creatures)[i]; @@ -103,7 +103,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, std::shared isLoaded = true; if (owner != 0) { - tryTransferOwnership(player, false); + tryTransferOwnership(std::move(player), false); } else { std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); time_t currentTime = time(nullptr); @@ -237,7 +237,7 @@ void House::setAccessList(uint32_t listId, const std::string &textlist) { } // kick uninvited players - for (std::shared_ptr tile : houseTiles) { + 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(); @@ -272,7 +272,7 @@ bool House::transferToDepot(std::shared_ptr player) const { if (townId == 0 || !player) { return false; } - for (std::shared_ptr tile : houseTiles) { + for (const std::shared_ptr &tile : houseTiles) { if (!transferToDepot(player, tile)) { return false; } @@ -304,7 +304,7 @@ bool House::transferToDepot(std::shared_ptr player, std::shared_ptr> playersToSave = { player }; - for (std::shared_ptr item : moveItemList) { + for (const std::shared_ptr &item : moveItemList) { g_logger().debug("[{}] moving item '{}' to depot", __FUNCTION__, item->getName()); auto targetPlayer = player; if (item->hasOwner() && !item->isOwner(targetPlayer)) { @@ -317,7 +317,7 @@ bool House::transferToDepot(std::shared_ptr player, std::shared_ptrgetParent(), targetPlayer->getInbox(), INDEX_WHEREEVER, item, item->getItemCount(), nullptr, FLAG_NOLIMIT); } - for (auto playerToSave : playersToSave) { + for (const auto &playerToSave : playersToSave) { g_saveManager().savePlayer(playerToSave); } return true; @@ -379,7 +379,7 @@ void House::handleWrapableItem(ItemList &moveItemList, std::shared_ptr ite void House::handleContainer(ItemList &moveItemList, std::shared_ptr item) const { if (const auto container = item->getContainer()) { - for (std::shared_ptr containerItem : container->getItemList()) { + for (const std::shared_ptr &containerItem : container->getItemList()) { moveItemList.push_back(containerItem); } } @@ -554,32 +554,32 @@ void AccessList::parseList(const std::string &list) { } auto lines = explodeString(validList, "\n", 100); - for (auto &line : lines) { - trimString(line); - trim_left(line, '\t'); - trim_right(line, '\t'); - trimString(line); + for (auto &m_line : lines) { + trimString(m_line); + trim_left(m_line, '\t'); + trim_right(m_line, '\t'); + trimString(m_line); - if (line.empty() || line.front() == '#' || line.length() > 100) { + if (m_line.empty() || m_line.front() == '#' || m_line.length() > 100) { continue; } - toLowerCaseString(line); + toLowerCaseString(m_line); - std::string::size_type at_pos = line.find("@"); + std::string::size_type at_pos = m_line.find('@'); if (at_pos != std::string::npos) { if (at_pos == 0) { - addGuild(line.substr(1)); + addGuild(m_line.substr(1)); } else { - addGuildRank(line.substr(0, at_pos - 1), line.substr(at_pos + 1)); + addGuildRank(m_line.substr(0, at_pos - 1), m_line.substr(at_pos + 1)); } - } else if (line == "*") { + } else if (m_line == "*") { allowEveryone = true; - } else if (line.find_first_of("!*?") != std::string::npos) { + } else if (m_line.find_first_of("!*?") != std::string::npos) { // Remove regular expressions since they don't make much sense in houses continue; - } else if (line.length() <= NETWORKMESSAGE_PLAYERNAME_MAXLENGTH) { - addPlayer(line); + } else if (m_line.length() <= NETWORKMESSAGE_PLAYERNAME_MAXLENGTH) { + addPlayer(m_line); } } } @@ -603,7 +603,7 @@ namespace { return nullptr; } - const auto guild = g_game().getGuild(guildId); + 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); if (guild) { - for (const auto rank : guild->getRanks()) { + for (const auto &rank : guild->getRanks()) { guildRankList.insert(rank->id); } } @@ -669,7 +669,7 @@ void Door::setHouse(std::shared_ptr newHouse) { return; } - this->house = newHouse; + this->house = std::move(newHouse); if (!accessList) { accessList = std::make_unique(); diff --git a/src/map/map.cpp b/src/map/map.cpp index 395e6d7d2be..fcf14262c30 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -611,7 +611,7 @@ bool Map::getPathMatching(const std::shared_ptr &creature, const Posit const bool withoutCreature = creature == nullptr; const auto &tile = neighborNode || withoutCreature ? getTile(pos.x, pos.y, pos.z) : canWalkTo(creature, pos); - if (!tile || !neighborNode && withoutCreature && tile->hasFlag(TILESTATE_BLOCKSOLID)) { + if (!tile || (!neighborNode && withoutCreature && tile->hasFlag(TILESTATE_BLOCKSOLID))) { continue; } diff --git a/src/map/spectators.cpp b/src/map/spectators.cpp index 18ce13871fe..7c0e80a0412 100644 --- a/src/map/spectators.cpp +++ b/src/map/spectators.cpp @@ -79,7 +79,7 @@ bool Spectators::checkCache(const SpectatorsCache::FloorData &specData, bool onl if (checkDistance) { SpectatorList spectators; spectators.reserve(creatures.size()); - for (const auto creature : *list) { + for (const auto &creature : *list) { const auto &specPos = creature->getPosition(); if (centerPos.x - specPos.x >= minRangeX && centerPos.y - specPos.y >= minRangeY @@ -184,7 +184,7 @@ Spectators Spectators::find(const Position ¢erPos, bool multifloor, bool onl for (uint_fast16_t nx = startx1; nx <= endx2; nx += FLOOR_SIZE) { if (leafE) { const auto &node_list = (onlyPlayers ? leafE->player_list : leafE->creature_list); - for (const auto creature : node_list) { + for (const auto &creature : node_list) { const auto &cpos = creature->getPosition(); if (minRangeZ > cpos.z || maxRangeZ < cpos.z) { continue; @@ -211,7 +211,7 @@ Spectators Spectators::find(const Position ¢erPos, bool multifloor, bool onl } // It is necessary to create the cache even if no spectators is found, so that there is no future query. - auto &cache = cacheFound ? it->second : spectatorsCache.emplace(centerPos, SpectatorsCache { .minRangeX = minRangeX, .maxRangeX = maxRangeX, .minRangeY = minRangeY, .maxRangeY = maxRangeY }).first->second; + auto &cache = cacheFound ? it->second : spectatorsCache.emplace(centerPos, SpectatorsCache { .minRangeX = minRangeX, .maxRangeX = maxRangeX, .minRangeY = minRangeY, .maxRangeY = maxRangeY, .creatures = {}, .players = {} }).first->second; auto &creaturesCache = onlyPlayers ? cache.players : cache.creatures; auto &creatureList = (multifloor ? creaturesCache.multiFloor : creaturesCache.floor); if (creatureList) { diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index ab111fd3c8f..ada1340a7c6 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -2247,7 +2247,7 @@ void ProtocolGame::parseBestiarysendRaces() { for (uint8_t i = BESTY_RACE_FIRST; i <= BESTY_RACE_LAST; i++) { std::string BestClass = ""; uint16_t count = 0; - for (auto rit : mtype_list) { + for (const auto &rit : mtype_list) { const auto mtype = g_monsters().getMonsterType(rit.second); if (!mtype) { return; @@ -2323,7 +2323,7 @@ void ProtocolGame::parseBestiarysendMonsterData(NetworkMessage &msg) { std::vector lootList = mtype->info.lootItems; newmsg.addByte(lootList.size()); - for (LootBlock loot : lootList) { + for (const LootBlock &loot : lootList) { int8_t difficult = g_iobestiary().calculateDifficult(loot.chance); bool shouldAddItem = false; @@ -2635,7 +2635,7 @@ void ProtocolGame::createLeaderTeamFinder(NetworkMessage &msg) { auto party = player->getParty(); if (teamAssemble->partyBool && party) { - for (std::shared_ptr member : party->getMembers()) { + for (const std::shared_ptr &member : party->getMembers()) { if (member && member->getGUID() != player->getGUID()) { teamAssemble->membersMap.insert({ member->getGUID(), 3 }); } @@ -2907,7 +2907,7 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) { std::string raceName = msg.getString(); race = g_iobestiary().findRaceByName(raceName); - if (race.size() == 0) { + if (race.empty()) { g_logger().warn("[ProtocolGame::parseBestiarysendCreature] - " "Race was not found: {}, search: {}", raceName, search); @@ -2921,7 +2921,7 @@ void ProtocolGame::parseBestiarysendCreatures(NetworkMessage &msg) { newmsg.add(race.size()); std::map creaturesKilled = g_iobestiary().getBestiaryKillCountByMonsterIDs(player, race); - for (auto it_ : race) { + for (const auto &it_ : race) { uint16_t raceid_ = it_.first; newmsg.add(raceid_); @@ -3889,14 +3889,14 @@ void ProtocolGame::sendCyclopediaCharacterOutfitsMounts() { auto startFamiliars = msg.getBufferPosition(); msg.skipBytes(2); const auto familiars = Familiars::getInstance().getFamiliars(player->getVocationId()); - for (const Familiar &familiar : familiars) { - const std::string type = familiar.type; + for (const auto &familiar : familiars) { + const std::string type = familiar->type; if (!player->getFamiliar(familiar)) { continue; } ++familiarsSize; - msg.add(familiar.lookType); - msg.addString(familiar.name, "ProtocolGame::sendCyclopediaCharacterOutfitsMounts - familiar.name"); + msg.add(familiar->lookType); + msg.addString(familiar->name, "ProtocolGame::sendCyclopediaCharacterOutfitsMounts - familiar.name"); if (type == "quest") { msg.addByte(CYCLOPEDIA_CHARACTERINFO_OUTFITTYPE_QUEST); } else { @@ -4151,7 +4151,7 @@ void ProtocolGame::sendBasicData() { // Send total size of spells msg.add(validSpells.size()); // Send each spell valid ids - for (auto spell : validSpells) { + for (const auto &spell : validSpells) { if (!spell) { continue; } @@ -4488,7 +4488,7 @@ void ProtocolGame::sendContainer(uint8_t cid, std::shared_ptr contain msg.addByte(0x00); } else if (container->getID() == ITEM_STORE_INBOX && !itemsStoreInboxToSend.empty()) { msg.addByte(std::min(maxItemsToSend, containerSize)); - for (const auto item : itemsStoreInboxToSend) { + for (const auto &item : itemsStoreInboxToSend) { AddItem(msg, item); } } else { @@ -4616,7 +4616,7 @@ void ProtocolGame::sendShop(std::shared_ptr npc) { msg.add(itemsToSend); uint16_t i = 0; - for (ShopBlock shopBlock : shoplist) { + for (const ShopBlock &shopBlock : shoplist) { if (++i > itemsToSend) { break; } @@ -4699,7 +4699,7 @@ void ProtocolGame::sendSaleItemList(const std::vector &shopVector, co msg.addByte(0xEE); msg.addByte(0x00); msg.add(player->getBankBalance()); - uint16_t currency = player->getShopOwner() ? player->getShopOwner()->getCurrency() : ITEM_GOLD_COIN; + uint16_t currency = player->getShopOwner() ? player->getShopOwner()->getCurrency() : static_cast(ITEM_GOLD_COIN); msg.addByte(0xEE); if (currency == ITEM_GOLD_COIN) { msg.addByte(0x01); @@ -4724,7 +4724,7 @@ void ProtocolGame::sendSaleItemList(const std::vector &shopVector, co auto msgPosition = msg.getBufferPosition(); msg.skipBytes(1); - for (ShopBlock shopBlock : shopVector) { + for (const ShopBlock &shopBlock : shopVector) { if (shopBlock.itemSellPrice == 0) { continue; } @@ -5859,7 +5859,7 @@ void ProtocolGame::sendTradeItemRequest(const std::string &traderName, std::shar std::shared_ptr container = listContainer.front(); listContainer.pop_front(); - for (std::shared_ptr containerItem : container->getItemList()) { + for (const std::shared_ptr &containerItem : container->getItemList()) { std::shared_ptr tmpContainer = containerItem->getContainer(); if (tmpContainer) { listContainer.push_back(tmpContainer); @@ -5869,7 +5869,7 @@ void ProtocolGame::sendTradeItemRequest(const std::string &traderName, std::shar } msg.addByte(itemList.size()); - for (std::shared_ptr listItem : itemList) { + for (const std::shared_ptr &listItem : itemList) { AddItem(msg, listItem); } } else { @@ -6810,14 +6810,14 @@ void ProtocolGame::sendOutfitWindow() { } std::vector> mounts; - for (const auto mount : g_game().mounts.getMounts()) { + for (const auto &mount : g_game().mounts.getMounts()) { if (player->hasMount(mount)) { mounts.push_back(mount); } } msg.addByte(mounts.size()); - for (const auto mount : mounts) { + for (const auto &mount : mounts) { msg.add(mount->clientId); msg.addString(mount->name, "ProtocolGame::sendOutfitWindow - mount->name"); } @@ -6919,7 +6919,7 @@ void ProtocolGame::sendOutfitWindow() { msg.skipBytes(2); const auto mounts = g_game().mounts.getMounts(); - for (const auto mount : mounts) { + for (const auto &mount : mounts) { if (player->hasMount(mount)) { msg.add(mount->clientId); msg.addString(mount->name, "ProtocolGame::sendOutfitWindow - mount->name"); @@ -6950,13 +6950,13 @@ void ProtocolGame::sendOutfitWindow() { const auto familiars = Familiars::getInstance().getFamiliars(player->getVocationId()); - for (const Familiar &familiar : familiars) { + for (const auto &familiar : familiars) { if (!player->getFamiliar(familiar)) { continue; } - msg.add(familiar.lookType); - msg.addString(familiar.name, "ProtocolGame::sendOutfitWindow - familiar.name"); + msg.add(familiar->lookType); + msg.addString(familiar->name, "ProtocolGame::sendOutfitWindow - familiar.name"); msg.addByte(0x00); if (++familiarSize == limitFamiliars) { break; @@ -7039,7 +7039,7 @@ void ProtocolGame::sendPodiumWindow(std::shared_ptr podium, const Position msg.skipBytes(2); const auto mounts = g_game().mounts.getMounts(); - for (const auto mount : mounts) { + for (const auto &mount : mounts) { if (player->hasMount(mount)) { msg.add(mount->clientId); msg.addString(mount->name, "ProtocolGame::sendPodiumWindow - mount->name"); @@ -7432,7 +7432,7 @@ void ProtocolGame::AddCreature(NetworkMessage &msg, std::shared_ptr cr } auto bubble = creature->getSpeechBubble(); - msg.addByte(oldProtocol && bubble == SPEECHBUBBLE_HIRELING ? SPEECHBUBBLE_NONE : bubble); + msg.addByte(oldProtocol && bubble == SPEECHBUBBLE_HIRELING ? static_cast(SPEECHBUBBLE_NONE) : bubble); msg.addByte(0xFF); // MARK_UNMARKED if (!oldProtocol) { msg.addByte(0x00); // inspection type @@ -7715,7 +7715,7 @@ void ProtocolGame::updatePartyTrackerAnalyzer(const std::shared_ptr party msg.addByte(static_cast(party->priceType)); msg.addByte(static_cast(party->membersData.size())); - for (const std::shared_ptr analyzer : party->membersData) { + for (const std::shared_ptr &analyzer : party->membersData) { msg.add(analyzer->id); if (std::shared_ptr member = g_game().getPlayerByID(analyzer->id); !member || !member->getParty() || member->getParty() != party) { @@ -7734,7 +7734,7 @@ void ProtocolGame::updatePartyTrackerAnalyzer(const std::shared_ptr party msg.addByte(showNames ? 0x01 : 0x00); if (showNames) { msg.addByte(static_cast(party->membersData.size())); - for (const std::shared_ptr analyzer : party->membersData) { + for (const std::shared_ptr &analyzer : party->membersData) { msg.add(analyzer->id); msg.addString(analyzer->name, "ProtocolGame::updatePartyTrackerAnalyzer - analyzer->name"); } @@ -8573,7 +8573,7 @@ void ProtocolGame::parseSendBosstiarySlots() { std::string boostedBossName = g_ioBosstiary().getBoostedBossName(); const auto mTypeBoosted = g_monsters().getMonsterType(boostedBossName); auto boostedBossRace = mTypeBoosted ? mTypeBoosted->info.bosstiaryRace : BosstiaryRarity_t::BOSS_INVALID; - auto isValidBoostedBoss = boostedBossId == 0 || boostedBossRace >= BosstiaryRarity_t::RARITY_BANE && boostedBossRace <= BosstiaryRarity_t::RARITY_NEMESIS; + auto isValidBoostedBoss = boostedBossId == 0 || (boostedBossRace >= BosstiaryRarity_t::RARITY_BANE && boostedBossRace <= BosstiaryRarity_t::RARITY_NEMESIS); if (!isValidBoostedBoss) { g_logger().error("[{}] The boosted boss '{}' has an invalid race", __FUNCTION__, boostedBossName); return; @@ -8581,7 +8581,7 @@ void ProtocolGame::parseSendBosstiarySlots() { const auto mTypeSlotOne = g_ioBosstiary().getMonsterTypeByBossRaceId((uint16_t)bossIdSlotOne); auto bossRaceSlotOne = mTypeSlotOne ? mTypeSlotOne->info.bosstiaryRace : BosstiaryRarity_t::BOSS_INVALID; - auto isValidBossSlotOne = bossIdSlotOne == 0 || bossRaceSlotOne >= BosstiaryRarity_t::RARITY_BANE && bossRaceSlotOne <= BosstiaryRarity_t::RARITY_NEMESIS; + auto isValidBossSlotOne = bossIdSlotOne == 0 || (bossRaceSlotOne >= BosstiaryRarity_t::RARITY_BANE && bossRaceSlotOne <= BosstiaryRarity_t::RARITY_NEMESIS); if (!isValidBossSlotOne) { g_logger().error("[{}] boss slot1 with race id '{}' has an invalid race", __FUNCTION__, bossIdSlotOne); return; @@ -8589,7 +8589,7 @@ void ProtocolGame::parseSendBosstiarySlots() { const auto mTypeSlotTwo = g_ioBosstiary().getMonsterTypeByBossRaceId((uint16_t)bossIdSlotTwo); auto bossRaceSlotTwo = mTypeSlotTwo ? mTypeSlotTwo->info.bosstiaryRace : BosstiaryRarity_t::BOSS_INVALID; - auto isValidBossSlotTwo = bossIdSlotTwo == 0 || bossRaceSlotTwo >= BosstiaryRarity_t::RARITY_BANE && bossRaceSlotTwo <= BosstiaryRarity_t::RARITY_NEMESIS; + auto isValidBossSlotTwo = bossIdSlotTwo == 0 || (bossRaceSlotTwo >= BosstiaryRarity_t::RARITY_BANE && bossRaceSlotTwo <= BosstiaryRarity_t::RARITY_NEMESIS); if (!isValidBossSlotTwo) { g_logger().error("[{}] boss slot1 with race id '{}' has an invalid race", __FUNCTION__, bossIdSlotTwo); return;