From 356c995857fc18d394aadff45ec3d26a1b2decde Mon Sep 17 00:00:00 2001 From: Matt Gomez Date: Sun, 3 Dec 2023 18:04:06 -0600 Subject: [PATCH] update : https://github.com/opentibiabr/canary/commit/cda6813cfde90bdc55e959330c819e4112caca31 --- src/canary_server.cpp | 34 +- src/config/config_definitions.hpp | 29 +- src/config/configmanager.cpp | 743 +++++++++--------- src/config/configmanager.hpp | 27 +- src/creatures/appearance/mounts/mounts.cpp | 6 +- src/creatures/appearance/outfit/outfit.cpp | 4 +- src/creatures/combat/combat.cpp | 16 +- src/creatures/combat/condition.cpp | 8 +- src/creatures/combat/spells.cpp | 4 +- src/creatures/creature.cpp | 8 +- src/creatures/interactions/chat.cpp | 2 +- src/creatures/monsters/monster.cpp | 10 +- src/creatures/monsters/monsters.hpp | 6 +- .../monsters/spawns/spawn_monster.cpp | 4 +- src/creatures/npcs/npc.cpp | 22 +- src/creatures/npcs/npc.hpp | 13 +- src/creatures/npcs/npcs.cpp | 4 +- src/creatures/players/grouping/familiars.cpp | 2 +- src/creatures/players/grouping/groups.cpp | 2 +- src/creatures/players/grouping/party.cpp | 20 +- .../players/imbuements/imbuements.cpp | 4 +- src/creatures/players/management/waitlist.cpp | 2 +- src/creatures/players/player.cpp | 137 ++-- src/creatures/players/player.hpp | 28 +- src/creatures/players/storages/storages.cpp | 2 +- src/creatures/players/vocations/vocation.cpp | 2 +- src/creatures/players/vocations/vocation.hpp | 12 +- src/creatures/players/wheel/player_wheel.cpp | 3 +- src/database/database.cpp | 2 +- src/database/databasemanager.cpp | 8 +- src/game/functions/game_reload.cpp | 10 +- src/game/game.cpp | 139 ++-- src/game/scheduling/dispatcher.cpp | 16 +- src/game/scheduling/dispatcher.hpp | 9 +- src/game/scheduling/events_scheduler.cpp | 2 +- src/game/scheduling/task.cpp | 2 - src/game/scheduling/task.hpp | 16 +- src/io/functions/iologindata_load_player.cpp | 18 +- src/io/functions/iologindata_save_player.cpp | 4 +- src/io/iologindata.cpp | 2 +- src/io/iomap.hpp | 8 +- src/io/iomapserialize.cpp | 2 +- src/io/iomarket.cpp | 12 +- src/io/ioprey.cpp | 44 +- src/items/bed.cpp | 4 +- src/items/containers/container.cpp | 4 +- src/items/item.hpp | 4 +- src/items/items.cpp | 4 +- src/items/items.hpp | 8 +- src/items/tile.cpp | 4 +- src/items/weapons/weapons.cpp | 4 +- src/lua/creature/actions.cpp | 12 +- src/lua/creature/events.cpp | 4 +- src/lua/creature/raids.cpp | 6 +- .../functions/core/game/bank_functions.cpp | 34 +- .../functions/core/game/config_functions.cpp | 289 ++----- .../functions/core/game/global_functions.cpp | 14 +- src/lua/functions/core/game/lua_enums.cpp | 36 +- .../core/game/modal_window_functions.cpp | 4 +- .../network/network_message_functions.cpp | 10 +- .../creatures/creature_functions.cpp | 2 +- .../creatures/monster/monster_functions.cpp | 8 +- .../monster/monster_type_functions.cpp | 2 +- .../functions/creatures/npc/npc_functions.cpp | 79 +- .../functions/creatures/npc/npc_functions.hpp | 2 + .../creatures/npc/npc_type_functions.cpp | 2 +- .../creatures/player/party_functions.cpp | 37 +- .../creatures/player/player_functions.cpp | 21 +- src/lua/functions/lua_functions_loader.cpp | 35 +- src/lua/functions/lua_functions_loader.hpp | 14 +- src/lua/functions/map/house_functions.cpp | 31 +- src/lua/functions/map/position_functions.cpp | 30 +- src/lua/global/baseevents.cpp | 2 +- src/lua/scripts/luascript.cpp | 14 +- src/lua/scripts/scripts.cpp | 8 +- src/map/house/house.cpp | 24 +- src/map/house/housetile.cpp | 4 +- src/map/map.cpp | 12 +- src/pch.hpp | 13 +- src/security/argon.cpp | 6 +- src/server/network/connection/connection.cpp | 4 +- src/server/network/protocol/protocol.hpp | 2 +- src/server/network/protocol/protocolgame.cpp | 102 +-- src/server/network/protocol/protocollogin.cpp | 10 +- .../network/protocol/protocolstatus.cpp | 60 +- src/server/network/webhook/webhook.cpp | 6 +- src/server/server.cpp | 4 +- src/server/signals.cpp | 2 +- src/utils/tools.cpp | 7 +- src/utils/tools.hpp | 1 + 90 files changed, 1202 insertions(+), 1231 deletions(-) diff --git a/src/canary_server.cpp b/src/canary_server.cpp index da5251605..e1efbca62 100644 --- a/src/canary_server.cpp +++ b/src/canary_server.cpp @@ -60,7 +60,7 @@ int CanaryServer::run() { try { loadConfigLua(); - logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL) ? " and 10x allowed!" : ""); + logger.info("Server protocol: {}.{}{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER, g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) ? " and 10x allowed!" : ""); rsa.start(); initializeDatabase(); @@ -89,7 +89,7 @@ int CanaryServer::run() { g_game().start(&serviceManager); g_game().setGameState(GAME_STATE_NORMAL); - if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE)) { + if (g_configManager().getBoolean(TOGGLE_MAINTAIN_MODE, __FUNCTION__)) { g_game().setGameState(GAME_STATE_CLOSED); g_logger().warn("Initialized in maintain mode!"); g_webhook().sendMessage("Server is now online", "The server is now online. Access is currently restricted to administrators only.", WEBHOOK_COLOR_ONLINE); @@ -123,7 +123,7 @@ int CanaryServer::run() { return EXIT_FAILURE; } - logger.info("{} {}", g_configManager().getString(SERVER_NAME), "server online!"); + logger.info("{} {}", g_configManager().getString(SERVER_NAME, __FUNCTION__), "server online!"); serviceManager.run(); @@ -132,7 +132,7 @@ int CanaryServer::run() { } void CanaryServer::setWorldType() { - std::string worldType = asLowerCaseString(g_configManager().getString(WORLD_TYPE)); + const std::string worldType = asLowerCaseString(g_configManager().getString(WORLD_TYPE, __FUNCTION__)); if (worldType == "pvp") { g_game().setWorldType(WORLD_TYPE_PVP); } else if (worldType == "no-pvp") { @@ -143,7 +143,7 @@ void CanaryServer::setWorldType() { throw FailedToInitializeCanary( fmt::format( "Unknown world type: {}, valid world types are: pvp, no-pvp and pvp-enforced", - g_configManager().getString(WORLD_TYPE) + g_configManager().getString(WORLD_TYPE, __FUNCTION__) ) ); } @@ -153,11 +153,11 @@ void CanaryServer::setWorldType() { void CanaryServer::loadMaps() const { try { - g_game().loadMainMap(g_configManager().getString(MAP_NAME)); + g_game().loadMainMap(g_configManager().getString(MAP_NAME, __FUNCTION__)); // If "mapCustomEnabled" is true on config.lua, then load the custom map - if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM)) { - g_game().loadCustomMaps(g_configManager().getString(DATA_DIRECTORY) + "/world/custom/"); + if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM, __FUNCTION__)) { + g_game().loadCustomMaps(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/world/custom/"); } Zone::refreshAll(); } catch (const std::exception &err) { @@ -167,7 +167,7 @@ void CanaryServer::loadMaps() const { void CanaryServer::setupHousesRent() { RentPeriod_t rentPeriod; - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD)); + std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); if (strRentPeriod == "yearly") { rentPeriod = RENTPERIOD_YEARLY; @@ -215,8 +215,8 @@ void CanaryServer::logInfos() { */ void CanaryServer::toggleForceCloseButton() { #ifdef OS_WINDOWS - HWND hwnd = GetConsoleWindow(); - HMENU hmenu = GetSystemMenu(hwnd, FALSE); + const HWND hwnd = GetConsoleWindow(); + const HMENU hmenu = GetSystemMenu(hwnd, FALSE); EnableMenuItem(hmenu, SC_CLOSE, MF_GRAYED); #endif } @@ -281,7 +281,7 @@ void CanaryServer::loadConfigLua() { modulesLoadHelper(g_configManager().load(), g_configManager().getConfigFileLua()); #ifdef _WIN32 - const std::string &defaultPriority = g_configManager().getString(DEFAULT_PRIORITY); + const std::string &defaultPriority = g_configManager().getString(DEFAULT_PRIORITY, __FUNCTION__); if (strcasecmp(defaultPriority.c_str(), "high") == 0) { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); } else if (strcasecmp(defaultPriority.c_str(), "above-normal") == 0) { @@ -307,7 +307,7 @@ void CanaryServer::initializeDatabase() { DatabaseManager::updateDatabase(); - if (g_configManager().getBoolean(OPTIMIZE_DATABASE) + if (g_configManager().getBoolean(OPTIMIZE_DATABASE, __FUNCTION__) && !DatabaseManager::optimizeTables()) { logger.debug("No tables were optimized"); } @@ -315,8 +315,8 @@ void CanaryServer::initializeDatabase() { void CanaryServer::loadModules() { // If "USE_ANY_DATAPACK_FOLDER" is set to true then you can choose any datapack folder for your server - auto useAnyDatapack = g_configManager().getBoolean(USE_ANY_DATAPACK_FOLDER); - auto datapackName = g_configManager().getString(DATA_DIRECTORY); + 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")) { throw FailedToInitializeCanary(fmt::format( "The datapack folder name '{}' is wrong, please select valid " @@ -331,12 +331,12 @@ void CanaryServer::loadModules() { g_luaEnvironment().initState(); } - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); // Load items dependencies modulesLoadHelper((g_game().loadAppearanceProtobuf(coreFolder + "/items/appearances.dat") == ERROR_NONE), "appearances.dat"); modulesLoadHelper(Item::items.loadFromXml(), "items.xml"); - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); + const auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); logger.debug("Loading core scripts on folder: {}/", coreFolder); // Load first core Lua libs modulesLoadHelper((g_luaEnvironment().loadFile(coreFolder + "/core.lua", "core.lua") == 0), "core.lua"); diff --git a/src/config/config_definitions.hpp b/src/config/config_definitions.hpp index bf86266f3..dc7f1caac 100644 --- a/src/config/config_definitions.hpp +++ b/src/config/config_definitions.hpp @@ -10,7 +10,7 @@ #pragma once // Enum -enum booleanConfig_t { +enum ConfigKey_t : uint16_t { ALLOW_CHANGEOUTFIT, ONE_PLAYER_ON_ACCOUNT, AIMBOT_HOTKEY_ENABLED, @@ -91,11 +91,6 @@ enum booleanConfig_t { TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, TOGGLE_RECEIVE_REWARD, TOGGLE_MAINTAIN_MODE, - - LAST_BOOLEAN_CONFIG -}; - -enum stringConfig_t { MAP_NAME, MAP_DOWNLOAD_URL, MAP_AUTHOR, @@ -128,11 +123,6 @@ enum stringConfig_t { TIBIADROME_CONCOCTION_TICK_TYPE, M_CONST, MAINTAIN_MODE_MESSAGE, - - LAST_STRING_CONFIG -}; - -enum integerConfig_t { SQL_PORT, MAX_PLAYERS, PZ_LOCKED, @@ -251,53 +241,38 @@ enum integerConfig_t { PARALLELISM, BOSS_DEFAULT_TIME_TO_FIGHT_AGAIN, BOSS_DEFAULT_TIME_TO_DEFEAT, - VIP_BONUS_EXP, VIP_BONUS_LOOT, VIP_BONUS_SKILL, VIP_FAMILIAR_TIME_COOLDOWN_REDUCTION, - REWARD_CHEST_MAX_COLLECT_ITEMS, DISCORD_WEBHOOK_DELAY_MS, - PVP_MAX_LEVEL_DIFFERENCE, - - LAST_INTEGER_CONFIG -}; - -enum floatingConfig_t { BESTIARY_RATE_CHARM_SHOP_PRICE, - RATE_HEALTH_REGEN, RATE_HEALTH_REGEN_SPEED, RATE_MANA_REGEN, RATE_MANA_REGEN_SPEED, RATE_SOUL_REGEN, RATE_SOUL_REGEN_SPEED, - RATE_SPELL_COOLDOWN, RATE_ATTACK_SPEED, RATE_OFFLINE_TRAINING_SPEED, RATE_EXERCISE_TRAINING_SPEED, - RATE_MONSTER_HEALTH, RATE_MONSTER_ATTACK, RATE_MONSTER_DEFENSE, RATE_BOSS_HEALTH, RATE_BOSS_ATTACK, RATE_BOSS_DEFENSE, - RATE_NPC_HEALTH, RATE_NPC_ATTACK, RATE_NPC_DEFENSE, LOYALTY_BONUS_PERCENTAGE_MULTIPLIER, PARTY_SHARE_LOOT_BOOSTS_DIMINISHING_FACTOR, - PVP_RATE_DAMAGE_TAKEN_PER_LEVEL, PVP_RATE_DAMAGE_REDUCTION_PER_LEVEL, - HOUSE_PRICE_RENT_MULTIPLIER, HOUSE_RENT_RATE, - - LAST_FLOATING_CONFIG + LOGLEVEL, }; diff --git a/src/config/configmanager.cpp b/src/config/configmanager.cpp index 5d52ca11b..293146427 100644 --- a/src/config/configmanager.cpp +++ b/src/config/configmanager.cpp @@ -19,62 +19,6 @@ #define lua_strlen lua_rawlen #endif -namespace { - - std::string getGlobalString(lua_State* L, const char* identifier, const char* defaultValue) { - lua_getglobal(L, identifier); - if (!lua_isstring(L, -1)) { - return defaultValue; - } - - size_t len = lua_strlen(L, -1); - std::string ret(lua_tostring(L, -1), len); - lua_pop(L, 1); - return ret; - } - - int32_t getGlobalNumber(lua_State* L, const char* identifier, const int32_t defaultValue = 0) { - lua_getglobal(L, identifier); - if (!lua_isnumber(L, -1)) { - return defaultValue; - } - - int32_t val = lua_tonumber(L, -1); - lua_pop(L, 1); - return val; - } - - bool getGlobalBoolean(lua_State* L, const char* identifier, const bool defaultValue) { - lua_getglobal(L, identifier); - if (!lua_isboolean(L, -1)) { - if (!lua_isstring(L, -1)) { - return defaultValue; - } - - size_t len = lua_strlen(L, -1); - std::string ret(lua_tostring(L, -1), len); - lua_pop(L, 1); - return booleanString(ret); - } - - int val = lua_toboolean(L, -1); - lua_pop(L, 1); - return val != 0; - } - - float getGlobalFloat(lua_State* L, const char* identifier, const float defaultValue = 0.0) { - lua_getglobal(L, identifier); - if (!lua_isnumber(L, -1)) { - return defaultValue; - } - - float val = lua_tonumber(L, -1); - lua_pop(L, 1); - return val; - } - -} - bool ConfigManager::load() { lua_State* L = luaL_newstate(); if (!L) { @@ -90,318 +34,318 @@ bool ConfigManager::load() { } #ifndef DEBUG_LOG - g_logger().setLevel(getGlobalString(L, "logLevel", "info")); + g_logger().setLevel(loadStringConfig(L, LOGLEVEL, "logLevel", "info")); #endif // Parse config // Info that must be loaded one time (unless we reset the modules involved) if (!loaded) { - boolean[BIND_ONLY_GLOBAL_ADDRESS] = getGlobalBoolean(L, "bindOnlyGlobalAddress", false); - boolean[OPTIMIZE_DATABASE] = getGlobalBoolean(L, "startupDatabaseOptimization", true); - boolean[TOGGLE_MAP_CUSTOM] = getGlobalBoolean(L, "toggleMapCustom", true); - boolean[TOGGLE_MAINTAIN_MODE] = getGlobalBoolean(L, "toggleMaintainMode", false); - string[MAINTAIN_MODE_MESSAGE] = getGlobalString(L, "maintainModeMessage", ""); - - string[IP] = getGlobalString(L, "ip", "127.0.0.1"); - string[MAP_NAME] = getGlobalString(L, "mapName", "canary"); - string[MAP_DOWNLOAD_URL] = getGlobalString(L, "mapDownloadUrl", ""); - string[MAP_AUTHOR] = getGlobalString(L, "mapAuthor", "Eduardo Dantas"); - - string[MAP_CUSTOM_NAME] = getGlobalString(L, "mapCustomName", ""); - string[MAP_CUSTOM_AUTHOR] = getGlobalString(L, "mapCustomAuthor", "OTServBR"); - - string[HOUSE_RENT_PERIOD] = getGlobalString(L, "houseRentPeriod", "never"); - floating[HOUSE_PRICE_RENT_MULTIPLIER] = getGlobalFloat(L, "housePriceRentMultiplier", 1.0); - floating[HOUSE_RENT_RATE] = getGlobalFloat(L, "houseRentRate", 1.0); - string[MYSQL_HOST] = getGlobalString(L, "mysqlHost", "127.0.0.1"); - string[MYSQL_USER] = getGlobalString(L, "mysqlUser", "root"); - string[MYSQL_PASS] = getGlobalString(L, "mysqlPass", ""); - string[MYSQL_DB] = getGlobalString(L, "mysqlDatabase", "canary"); - string[MYSQL_SOCK] = getGlobalString(L, "mysqlSock", ""); - - string[AUTH_TYPE] = getGlobalString(L, "authType", "password"); - boolean[RESET_SESSIONS_ON_STARTUP] = getGlobalBoolean(L, "resetSessionsOnStartup", false); - - integer[SQL_PORT] = getGlobalNumber(L, "mysqlPort", 3306); - integer[GAME_PORT] = getGlobalNumber(L, "gameProtocolPort", 7172); - integer[LOGIN_PORT] = getGlobalNumber(L, "loginProtocolPort", 7171); - integer[STATUS_PORT] = getGlobalNumber(L, "statusProtocolPort", 7171); - - integer[MARKET_OFFER_DURATION] = getGlobalNumber(L, "marketOfferDuration", 30 * 24 * 60 * 60); - - integer[FREE_DEPOT_LIMIT] = getGlobalNumber(L, "freeDepotLimit", 2000); - integer[PREMIUM_DEPOT_LIMIT] = getGlobalNumber(L, "premiumDepotLimit", 8000); - integer[DEPOT_BOXES] = getGlobalNumber(L, "depotBoxes", 20); - integer[STASH_ITEMS] = getGlobalNumber(L, "stashItemCount", 5000); - - boolean[OLD_PROTOCOL] = getGlobalBoolean(L, "allowOldProtocol", true); + loadBoolConfig(L, BIND_ONLY_GLOBAL_ADDRESS, "bindOnlyGlobalAddress", false); + loadBoolConfig(L, OPTIMIZE_DATABASE, "startupDatabaseOptimization", true); + loadBoolConfig(L, TOGGLE_MAP_CUSTOM, "toggleMapCustom", true); + loadBoolConfig(L, TOGGLE_MAINTAIN_MODE, "toggleMaintainMode", false); + loadStringConfig(L, MAINTAIN_MODE_MESSAGE, "maintainModeMessage", ""); + + loadStringConfig(L, IP, "ip", "127.0.0.1"); + loadStringConfig(L, MAP_NAME, "mapName", "canary"); + loadStringConfig(L, MAP_DOWNLOAD_URL, "mapDownloadUrl", ""); + loadStringConfig(L, MAP_AUTHOR, "mapAuthor", "Eduardo Dantas"); + + loadStringConfig(L, MAP_CUSTOM_NAME, "mapCustomName", ""); + loadStringConfig(L, MAP_CUSTOM_AUTHOR, "mapCustomAuthor", "OTServBR"); + + loadStringConfig(L, HOUSE_RENT_PERIOD, "houseRentPeriod", "never"); + loadFloatConfig(L, HOUSE_PRICE_RENT_MULTIPLIER, "housePriceRentMultiplier", 1.0); + loadFloatConfig(L, HOUSE_RENT_RATE, "houseRentRate", 1.0); + loadStringConfig(L, MYSQL_HOST, "mysqlHost", "127.0.0.1"); + loadStringConfig(L, MYSQL_USER, "mysqlUser", "root"); + loadStringConfig(L, MYSQL_PASS, "mysqlPass", ""); + loadStringConfig(L, MYSQL_DB, "mysqlDatabase", "canary"); + loadStringConfig(L, MYSQL_SOCK, "mysqlSock", ""); + + loadStringConfig(L, AUTH_TYPE, "authType", "password"); + loadBoolConfig(L, RESET_SESSIONS_ON_STARTUP, "resetSessionsOnStartup", false); + + loadIntConfig(L, SQL_PORT, "mysqlPort", 3306); + loadIntConfig(L, GAME_PORT, "gameProtocolPort", 7172); + loadIntConfig(L, LOGIN_PORT, "loginProtocolPort", 7171); + loadIntConfig(L, STATUS_PORT, "statusProtocolPort", 7171); + + loadIntConfig(L, MARKET_OFFER_DURATION, "marketOfferDuration", 30 * 24 * 60 * 60); + + loadIntConfig(L, FREE_DEPOT_LIMIT, "freeDepotLimit", 2000); + loadIntConfig(L, PREMIUM_DEPOT_LIMIT, "premiumDepotLimit", 8000); + loadIntConfig(L, DEPOT_BOXES, "depotBoxes", 20); + loadIntConfig(L, STASH_ITEMS, "stashItemCount", 5000); + + loadBoolConfig(L, OLD_PROTOCOL, "allowOldProtocol", true); } - boolean[ALLOW_CHANGEOUTFIT] = getGlobalBoolean(L, "allowChangeOutfit", true); - boolean[ONE_PLAYER_ON_ACCOUNT] = getGlobalBoolean(L, "onePlayerOnlinePerAccount", true); - boolean[AIMBOT_HOTKEY_ENABLED] = getGlobalBoolean(L, "hotkeyAimbotEnabled", true); - boolean[REMOVE_RUNE_CHARGES] = getGlobalBoolean(L, "removeChargesFromRunes", true); - boolean[EXPERIENCE_FROM_PLAYERS] = getGlobalBoolean(L, "experienceByKillingPlayers", false); - boolean[FREE_PREMIUM] = getGlobalBoolean(L, "freePremium", false); - boolean[REPLACE_KICK_ON_LOGIN] = getGlobalBoolean(L, "replaceKickOnLogin", true); - boolean[MARKET_PREMIUM] = getGlobalBoolean(L, "premiumToCreateMarketOffer", true); - boolean[EMOTE_SPELLS] = getGlobalBoolean(L, "emoteSpells", false); - boolean[STAMINA_SYSTEM] = getGlobalBoolean(L, "staminaSystem", true); - boolean[WARN_UNSAFE_SCRIPTS] = getGlobalBoolean(L, "warnUnsafeScripts", true); - boolean[CONVERT_UNSAFE_SCRIPTS] = getGlobalBoolean(L, "convertUnsafeScripts", true); - boolean[CLASSIC_ATTACK_SPEED] = getGlobalBoolean(L, "classicAttackSpeed", false); - boolean[TOGGLE_ATTACK_SPEED_ONFIST] = getGlobalBoolean(L, "toggleAttackSpeedOnFist", false); - integer[MULTIPLIER_ATTACKONFIST] = getGlobalNumber(L, "multiplierSpeedOnFist", 5); - integer[MAX_SPEED_ATTACKONFIST] = getGlobalNumber(L, "maxSpeedOnFist", 500); - boolean[SCRIPTS_CONSOLE_LOGS] = getGlobalBoolean(L, "showScriptsLogInConsole", true); - boolean[STASH_MOVING] = getGlobalBoolean(L, "stashMoving", false); - boolean[ALLOW_BLOCK_SPAWN] = getGlobalBoolean(L, "allowBlockSpawn", true); - boolean[REMOVE_WEAPON_AMMO] = getGlobalBoolean(L, "removeWeaponAmmunition", true); - boolean[REMOVE_WEAPON_CHARGES] = getGlobalBoolean(L, "removeWeaponCharges", true); - boolean[REMOVE_POTION_CHARGES] = getGlobalBoolean(L, "removeChargesFromPotions", true); - boolean[GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE] = getGlobalBoolean(L, "globalServerSaveNotifyMessage", true); - boolean[GLOBAL_SERVER_SAVE_CLEAN_MAP] = getGlobalBoolean(L, "globalServerSaveCleanMap", false); - boolean[GLOBAL_SERVER_SAVE_CLOSE] = getGlobalBoolean(L, "globalServerSaveClose", false); - boolean[FORCE_MONSTERTYPE_LOAD] = getGlobalBoolean(L, "forceMonsterTypesOnLoad", true); - boolean[HOUSE_OWNED_BY_ACCOUNT] = getGlobalBoolean(L, "houseOwnedByAccount", false); - boolean[CLEAN_PROTECTION_ZONES] = getGlobalBoolean(L, "cleanProtectionZones", false); - boolean[GLOBAL_SERVER_SAVE_SHUTDOWN] = getGlobalBoolean(L, "globalServerSaveShutdown", true); - boolean[PUSH_WHEN_ATTACKING] = getGlobalBoolean(L, "pushWhenAttacking", false); - - boolean[WEATHER_RAIN] = getGlobalBoolean(L, "weatherRain", false); - boolean[WEATHER_THUNDER] = getGlobalBoolean(L, "thunderEffect", false); - boolean[ALL_CONSOLE_LOG] = getGlobalBoolean(L, "allConsoleLog", false); - boolean[TOGGLE_FREE_QUEST] = getGlobalBoolean(L, "toggleFreeQuest", true); - boolean[AUTOLOOT] = getGlobalBoolean(L, "autoLoot", false); - boolean[AUTOBANK] = getGlobalBoolean(L, "autoBank", false); - boolean[STAMINA_TRAINER] = getGlobalBoolean(L, "staminaTrainer", false); - boolean[STAMINA_PZ] = getGlobalBoolean(L, "staminaPz", false); - boolean[SORT_LOOT_BY_CHANCE] = getGlobalBoolean(L, "sortLootByChance", false); - boolean[TOGGLE_SAVE_INTERVAL] = getGlobalBoolean(L, "toggleSaveInterval", false); - boolean[TOGGLE_SAVE_INTERVAL_CLEAN_MAP] = getGlobalBoolean(L, "toggleSaveIntervalCleanMap", false); - boolean[TELEPORT_SUMMONS] = getGlobalBoolean(L, "teleportSummons", false); - boolean[ALLOW_RELOAD] = getGlobalBoolean(L, "allowReload", false); - - boolean[ONLY_PREMIUM_ACCOUNT] = getGlobalBoolean(L, "onlyPremiumAccount", false); - boolean[RATE_USE_STAGES] = getGlobalBoolean(L, "rateUseStages", false); - boolean[TOGGLE_IMBUEMENT_SHRINE_STORAGE] = getGlobalBoolean(L, "toggleImbuementShrineStorage", true); - boolean[TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY] = getGlobalBoolean(L, "toggleImbuementNonAggressiveFightOnly", false); - - boolean[TOGGLE_DOWNLOAD_MAP] = getGlobalBoolean(L, "toggleDownloadMap", false); - boolean[USE_ANY_DATAPACK_FOLDER] = getGlobalBoolean(L, "useAnyDatapackFolder", false); - boolean[INVENTORY_GLOW] = getGlobalBoolean(L, "inventoryGlowOnFiveBless", false); - boolean[XP_DISPLAY_MODE] = getGlobalBoolean(L, "experienceDisplayRates", true); - - string[DEFAULT_PRIORITY] = getGlobalString(L, "defaultPriority", "high"); - string[SERVER_NAME] = getGlobalString(L, "serverName", ""); - string[SERVER_MOTD] = getGlobalString(L, "serverMotd", ""); - string[OWNER_NAME] = getGlobalString(L, "ownerName", ""); - string[OWNER_EMAIL] = getGlobalString(L, "ownerEmail", ""); - string[URL] = getGlobalString(L, "url", ""); - string[LOCATION] = getGlobalString(L, "location", ""); - string[WORLD_TYPE] = getGlobalString(L, "worldType", "pvp"); - string[STORE_IMAGES_URL] = getGlobalString(L, "coinImagesURL", ""); - string[DISCORD_WEBHOOK_URL] = getGlobalString(L, "discordWebhookURL", ""); - string[SAVE_INTERVAL_TYPE] = getGlobalString(L, "saveIntervalType", ""); - string[GLOBAL_SERVER_SAVE_TIME] = getGlobalString(L, "globalServerSaveTime", "06:00"); - string[DATA_DIRECTORY] = getGlobalString(L, "dataPackDirectory", "data-otservbr-global"); - string[CORE_DIRECTORY] = getGlobalString(L, "coreDirectory", "data"); - - string[FORGE_FIENDISH_INTERVAL_TYPE] = getGlobalString(L, "forgeFiendishIntervalType", "hour"); - string[FORGE_FIENDISH_INTERVAL_TIME] = getGlobalString(L, "forgeFiendishIntervalTime", "1"); - - integer[MAX_PLAYERS] = getGlobalNumber(L, "maxPlayers"); - integer[PZ_LOCKED] = getGlobalNumber(L, "pzLocked", 60000); - integer[DEFAULT_DESPAWNRANGE] = getGlobalNumber(L, "deSpawnRange", 2); - integer[DEFAULT_DESPAWNRADIUS] = getGlobalNumber(L, "deSpawnRadius", 50); - integer[RATE_EXPERIENCE] = getGlobalNumber(L, "rateExp", 1); - integer[RATE_SKILL] = getGlobalNumber(L, "rateSkill", 1); - integer[RATE_LOOT] = getGlobalNumber(L, "rateLoot", 1); - integer[RATE_MAGIC] = getGlobalNumber(L, "rateMagic", 1); - integer[RATE_SPAWN] = getGlobalNumber(L, "rateSpawn", 1); - integer[RATE_KILLING_IN_THE_NAME_OF_POINTS] = getGlobalNumber(L, "rateKillingInTheNameOfPoints", 1); - - integer[HOUSE_PRICE_PER_SQM] = getGlobalNumber(L, "housePriceEachSQM", 1000); - integer[HOUSE_BUY_LEVEL] = getGlobalNumber(L, "houseBuyLevel", 0); - integer[HOUSE_LOSE_AFTER_INACTIVITY] = getGlobalNumber(L, "houseLoseAfterInactivity", 0); - boolean[HOUSE_PURSHASED_SHOW_PRICE] = getGlobalBoolean(L, "housePurchasedShowPrice", false); - boolean[ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS] = getGlobalBoolean(L, "onlyInvitedCanMoveHouseItems", true); - - integer[ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenActions", 200); - integer[EX_ACTIONS_DELAY_INTERVAL] = getGlobalNumber(L, "timeBetweenExActions", 1000); - integer[MAX_MESSAGEBUFFER] = getGlobalNumber(L, "maxMessageBuffer", 4); - integer[KICK_AFTER_MINUTES] = getGlobalNumber(L, "kickIdlePlayerAfterMinutes", 15); - integer[PROTECTION_LEVEL] = getGlobalNumber(L, "protectionLevel", 1); - integer[DEATH_LOSE_PERCENT] = getGlobalNumber(L, "deathLosePercent", -1); - integer[STATUSQUERY_TIMEOUT] = getGlobalNumber(L, "statusTimeout", 5000); - integer[FRAG_TIME] = getGlobalNumber(L, "timeToDecreaseFrags", 24 * 60 * 60 * 1000); - integer[WHITE_SKULL_TIME] = getGlobalNumber(L, "whiteSkullTime", 15 * 60 * 1000); - integer[STAIRHOP_DELAY] = getGlobalNumber(L, "stairJumpExhaustion", 2000); - integer[MAX_CONTAINER] = getGlobalNumber(L, "maxContainer", 500); - integer[MAX_CONTAINER_ITEM] = getGlobalNumber(L, "maxItem", 5000); - integer[EXP_FROM_PLAYERS_LEVEL_RANGE] = getGlobalNumber(L, "expFromPlayersLevelRange", 75); - integer[CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES] = getGlobalNumber(L, "checkExpiredMarketOffersEachMinutes", 60); - integer[MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER] = getGlobalNumber(L, "maxMarketOffersAtATimePerPlayer", 100); - integer[MAX_PACKETS_PER_SECOND] = getGlobalNumber(L, "maxPacketsPerSecond", 25); - integer[COMPRESSION_LEVEL] = getGlobalNumber(L, "packetCompressionLevel", 6); - integer[STORE_COIN_PACKET] = getGlobalNumber(L, "coinPacketSize", 25); - integer[DAY_KILLS_TO_RED] = getGlobalNumber(L, "dayKillsToRedSkull", 3); - integer[WEEK_KILLS_TO_RED] = getGlobalNumber(L, "weekKillsToRedSkull", 5); - integer[MONTH_KILLS_TO_RED] = getGlobalNumber(L, "monthKillsToRedSkull", 10); - integer[RED_SKULL_DURATION] = getGlobalNumber(L, "redSkullDuration", 30); - integer[BLACK_SKULL_DURATION] = getGlobalNumber(L, "blackSkullDuration", 45); - integer[ORANGE_SKULL_DURATION] = getGlobalNumber(L, "orangeSkullDuration", 7); - integer[GLOBAL_SERVER_SAVE_NOTIFY_DURATION] = getGlobalNumber(L, "globalServerSaveNotifyDuration", 5); - - integer[PARTY_LIST_MAX_DISTANCE] = getGlobalNumber(L, "partyListMaxDistance", 0); - - integer[PUSH_DELAY] = getGlobalNumber(L, "pushDelay", 1000); - integer[PUSH_DISTANCE_DELAY] = getGlobalNumber(L, "pushDistanceDelay", 1500); - - integer[STAMINA_ORANGE_DELAY] = getGlobalNumber(L, "staminaOrangeDelay", 1); - integer[STAMINA_GREEN_DELAY] = getGlobalNumber(L, "staminaGreenDelay", 5); - integer[STAMINA_PZ_GAIN] = getGlobalNumber(L, "staminaPzGain", 1); - integer[STAMINA_TRAINER_DELAY] = getGlobalNumber(L, "staminaTrainerDelay", 5); - integer[STAMINA_TRAINER_GAIN] = getGlobalNumber(L, "staminaTrainerGain", 1); - integer[SAVE_INTERVAL_TIME] = getGlobalNumber(L, "saveIntervalTime", 1); - integer[MAX_ALLOWED_ON_A_DUMMY] = getGlobalNumber(L, "maxAllowedOnADummy", 1); - integer[FREE_QUEST_STAGE] = getGlobalNumber(L, "freeQuestStage", 1); - integer[DEPOTCHEST] = getGlobalNumber(L, "depotChest", 4); - integer[CRITICALCHANCE] = getGlobalNumber(L, "criticalChance", 10); - - integer[ADVENTURERSBLESSING_LEVEL] = getGlobalNumber(L, "adventurersBlessingLevel", 21); - integer[FORGE_MAX_ITEM_TIER] = getGlobalNumber(L, "forgeMaxItemTier", 10); - integer[FORGE_COST_ONE_SLIVER] = getGlobalNumber(L, "forgeCostOneSliver", 20); - integer[FORGE_SLIVER_AMOUNT] = getGlobalNumber(L, "forgeSliverAmount", 3); - integer[FORGE_CORE_COST] = getGlobalNumber(L, "forgeCoreCost", 50); - integer[FORGE_MAX_DUST] = getGlobalNumber(L, "forgeMaxDust", 225); - integer[FORGE_FUSION_DUST_COST] = getGlobalNumber(L, "forgeFusionCost", 100); - integer[FORGE_TRANSFER_DUST_COST] = getGlobalNumber(L, "forgeTransferCost", 100); - integer[FORGE_BASE_SUCCESS_RATE] = getGlobalNumber(L, "forgeBaseSuccessRate", 50); - integer[FORGE_BONUS_SUCCESS_RATE] = getGlobalNumber(L, "forgeBonusSuccessRate", 15); - integer[FORGE_TIER_LOSS_REDUCTION] = getGlobalNumber(L, "forgeTierLossReduction", 50); - integer[FORGE_AMOUNT_MULTIPLIER] = getGlobalNumber(L, "forgeAmountMultiplier", 3); - integer[FORGE_MIN_SLIVERS] = getGlobalNumber(L, "forgeMinSlivers", 3); - integer[FORGE_MAX_SLIVERS] = getGlobalNumber(L, "forgeMaxSlivers", 7); - integer[FORGE_INFLUENCED_CREATURES_LIMIT] = getGlobalNumber(L, "forgeInfluencedLimit", 300); - integer[FORGE_FIENDISH_CREATURES_LIMIT] = getGlobalNumber(L, "forgeFiendishLimit", 3); - integer[DISCORD_WEBHOOK_DELAY_MS] = getGlobalNumber(L, "discordWebhookDelayMs", Webhook::DEFAULT_DELAY_MS); - - floating[BESTIARY_RATE_CHARM_SHOP_PRICE] = getGlobalFloat(L, "bestiaryRateCharmShopPrice", 1.0); - floating[RATE_HEALTH_REGEN] = getGlobalFloat(L, "rateHealthRegen", 1.0); - floating[RATE_HEALTH_REGEN_SPEED] = getGlobalFloat(L, "rateHealthRegenSpeed", 1.0); - floating[RATE_MANA_REGEN] = getGlobalFloat(L, "rateManaRegen", 1.0); - floating[RATE_MANA_REGEN_SPEED] = getGlobalFloat(L, "rateManaRegenSpeed", 1.0); - floating[RATE_SOUL_REGEN] = getGlobalFloat(L, "rateSoulRegen", 1.0); - floating[RATE_SOUL_REGEN_SPEED] = getGlobalFloat(L, "rateSoulRegenSpeed", 1.0); - floating[RATE_SPELL_COOLDOWN] = getGlobalFloat(L, "rateSpellCooldown", 1.0); - floating[RATE_ATTACK_SPEED] = getGlobalFloat(L, "rateAttackSpeed", 1.0); - floating[RATE_OFFLINE_TRAINING_SPEED] = getGlobalFloat(L, "rateOfflineTrainingSpeed", 1.0); - floating[RATE_EXERCISE_TRAINING_SPEED] = getGlobalFloat(L, "rateExerciseTrainingSpeed", 1.0); - - floating[RATE_MONSTER_HEALTH] = getGlobalFloat(L, "rateMonsterHealth", 1.0); - floating[RATE_MONSTER_ATTACK] = getGlobalFloat(L, "rateMonsterAttack", 1.0); - floating[RATE_MONSTER_DEFENSE] = getGlobalFloat(L, "rateMonsterDefense", 1.0); - floating[RATE_BOSS_HEALTH] = getGlobalFloat(L, "rateBossHealth", 1.0); - floating[RATE_BOSS_ATTACK] = getGlobalFloat(L, "rateBossAttack", 1.0); - floating[RATE_BOSS_DEFENSE] = getGlobalFloat(L, "rateBossDefense", 1.0); - integer[BOSS_DEFAULT_TIME_TO_FIGHT_AGAIN] = getGlobalNumber(L, "bossDefaultTimeToFightAgain", 20 * 60 * 60); - integer[BOSS_DEFAULT_TIME_TO_DEFEAT] = getGlobalNumber(L, "bossDefaultTimeToDefeat", 20 * 60); - - floating[RATE_NPC_HEALTH] = getGlobalFloat(L, "rateNpcHealth", 1.0); - floating[RATE_NPC_ATTACK] = getGlobalFloat(L, "rateNpcAttack", 1.0); - floating[RATE_NPC_DEFENSE] = getGlobalFloat(L, "rateNpcDefense", 1.0); - - boolean[PREY_ENABLED] = getGlobalBoolean(L, "preySystemEnabled", true); - boolean[PREY_FREE_THIRD_SLOT] = getGlobalBoolean(L, "preyFreeThirdSlot", false); - integer[PREY_REROLL_PRICE_LEVEL] = getGlobalNumber(L, "preyRerollPricePerLevel", 200); - integer[PREY_SELECTION_LIST_PRICE] = getGlobalNumber(L, "preySelectListPrice", 5); - integer[PREY_BONUS_TIME] = getGlobalNumber(L, "preyBonusTime", 7200); - integer[PREY_BONUS_REROLL_PRICE] = getGlobalNumber(L, "preyBonusRerollPrice", 1); - integer[PREY_FREE_REROLL_TIME] = getGlobalNumber(L, "preyFreeRerollTime", 72000); - - boolean[TASK_HUNTING_ENABLED] = getGlobalBoolean(L, "taskHuntingSystemEnabled", true); - boolean[TASK_HUNTING_FREE_THIRD_SLOT] = getGlobalBoolean(L, "taskHuntingFreeThirdSlot", false); - integer[TASK_HUNTING_LIMIT_EXHAUST] = getGlobalNumber(L, "taskHuntingLimitedTasksExhaust", 72000); - integer[TASK_HUNTING_REROLL_PRICE_LEVEL] = getGlobalNumber(L, "taskHuntingRerollPricePerLevel", 200); - integer[TASK_HUNTING_SELECTION_LIST_PRICE] = getGlobalNumber(L, "taskHuntingSelectListPrice", 5); - integer[TASK_HUNTING_BONUS_REROLL_PRICE] = getGlobalNumber(L, "taskHuntingBonusRerollPrice", 1); - integer[TASK_HUNTING_FREE_REROLL_TIME] = getGlobalNumber(L, "taskHuntingFreeRerollTime", 72000); - - integer[BESTIARY_KILL_MULTIPLIER] = getGlobalNumber(L, "bestiaryKillMultiplier", 1); - integer[BOSSTIARY_KILL_MULTIPLIER] = getGlobalNumber(L, "bosstiaryKillMultiplier", 1); - boolean[BOOSTED_BOSS_SLOT] = getGlobalBoolean(L, "boostedBossSlot", true); - integer[BOOSTED_BOSS_LOOT_BONUS] = getGlobalNumber(L, "boostedBossLootBonus", 250); - integer[BOOSTED_BOSS_KILL_BONUS] = getGlobalNumber(L, "boostedBossKillBonus", 3); - - integer[FAMILIAR_TIME] = getGlobalNumber(L, "familiarTime", 30); - - boolean[TOGGLE_GOLD_POUCH_ALLOW_ANYTHING] = getGlobalBoolean(L, "toggleGoldPouchAllowAnything", false); - boolean[TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY] = getGlobalBoolean(L, "toggleGoldPouchQuickLootOnly", false); - boolean[TOGGLE_SERVER_IS_RETRO] = getGlobalBoolean(L, "toggleServerIsRetroPVP", false); - boolean[TOGGLE_TRAVELS_FREE] = getGlobalBoolean(L, "toggleTravelsFree", false); - integer[BUY_AOL_COMMAND_FEE] = getGlobalNumber(L, "buyAolCommandFee", 0); - integer[BUY_BLESS_COMMAND_FEE] = getGlobalNumber(L, "buyBlessCommandFee", 0); - boolean[TELEPORT_PLAYER_TO_VOCATION_ROOM] = getGlobalBoolean(L, "teleportPlayerToVocationRoom", true); - - boolean[TOGGLE_HAZARDSYSTEM] = getGlobalBoolean(L, "toogleHazardSystem", true); - integer[HAZARD_CRITICAL_INTERVAL] = getGlobalNumber(L, "hazardCriticalInterval", 2000); - integer[HAZARD_CRITICAL_CHANCE] = getGlobalNumber(L, "hazardCriticalChance", 750); - integer[HAZARD_CRITICAL_MULTIPLIER] = getGlobalNumber(L, "hazardCriticalMultiplier", 25); - integer[HAZARD_DAMAGE_MULTIPLIER] = getGlobalNumber(L, "hazardDamageMultiplier", 200); - integer[HAZARD_DODGE_MULTIPLIER] = getGlobalNumber(L, "hazardDodgeMultiplier", 85); - integer[HAZARD_PODS_DROP_MULTIPLIER] = getGlobalNumber(L, "hazardPodsDropMultiplier", 87); - integer[HAZARD_PODS_TIME_TO_DAMAGE] = getGlobalNumber(L, "hazardPodsTimeToDamage", 2000); - integer[HAZARD_PODS_TIME_TO_SPAWN] = getGlobalNumber(L, "hazardPodsTimeToSpawn", 4000); - integer[HAZARD_EXP_BONUS_MULTIPLIER] = getGlobalNumber(L, "hazardExpBonusMultiplier", 2); - integer[HAZARD_LOOT_BONUS_MULTIPLIER] = getGlobalNumber(L, "hazardLootBonusMultiplier", 2); - integer[HAZARD_PODS_DAMAGE] = getGlobalNumber(L, "hazardPodsDamage", 5); - integer[HAZARD_SPAWN_PLUNDER_MULTIPLIER] = getGlobalNumber(L, "hazardSpawnPlunderMultiplier", 25); - integer[LOW_LEVEL_BONUS_EXP] = getGlobalNumber(L, "lowLevelBonusExp", 50); - - boolean[LOYALTY_ENABLED] = getGlobalBoolean(L, "loyaltyEnabled", true); - integer[LOYALTY_POINTS_PER_CREATION_DAY] = getGlobalNumber(L, "loyaltyPointsPerCreationDay", 1); - integer[LOYALTY_POINTS_PER_PREMIUM_DAY_SPENT] = getGlobalNumber(L, "loyaltyPointsPerPremiumDaySpent", 0); - integer[LOYALTY_POINTS_PER_PREMIUM_DAY_PURCHASED] = getGlobalNumber(L, "loyaltyPointsPerPremiumDayPurchased", 0); - floating[LOYALTY_BONUS_PERCENTAGE_MULTIPLIER] = getGlobalFloat(L, "loyaltyBonusPercentageMultiplier", 1.0); - - boolean[TOGGLE_WHEELSYSTEM] = getGlobalBoolean(L, "wheelSystemEnabled", true); - integer[WHEEL_POINTS_PER_LEVEL] = getGlobalNumber(L, "wheelPointsPerLevel", 1); - - boolean[PARTY_AUTO_SHARE_EXPERIENCE] = getGlobalBoolean(L, "partyAutoShareExperience", true); - boolean[PARTY_SHARE_LOOT_BOOSTS] = getGlobalBoolean(L, "partyShareLootBoosts", true); - floating[PARTY_SHARE_LOOT_BOOSTS_DIMINISHING_FACTOR] = getGlobalFloat(L, "partyShareLootBoostsDimishingFactor", 0.7f); - integer[TIBIADROME_CONCOCTION_COOLDOWN] = getGlobalNumber(L, "tibiadromeConcoctionCooldown", 24 * 60 * 60); - integer[TIBIADROME_CONCOCTION_DURATION] = getGlobalNumber(L, "tibiadromeConcoctionDuration", 1 * 60 * 60); - string[TIBIADROME_CONCOCTION_TICK_TYPE] = getGlobalString(L, "tibiadromeConcoctionTickType", "online"); - - string[M_CONST] = getGlobalString(L, "memoryConst", "1<<16"); - integer[T_CONST] = getGlobalNumber(L, "temporaryConst", 2); - integer[PARALLELISM] = getGlobalNumber(L, "parallelism", 2); + loadBoolConfig(L, ALLOW_CHANGEOUTFIT, "allowChangeOutfit", true); + loadBoolConfig(L, ONE_PLAYER_ON_ACCOUNT, "onePlayerOnlinePerAccount", true); + loadBoolConfig(L, AIMBOT_HOTKEY_ENABLED, "hotkeyAimbotEnabled", true); + loadBoolConfig(L, REMOVE_RUNE_CHARGES, "removeChargesFromRunes", true); + loadBoolConfig(L, EXPERIENCE_FROM_PLAYERS, "experienceByKillingPlayers", false); + loadBoolConfig(L, FREE_PREMIUM, "freePremium", false); + loadBoolConfig(L, REPLACE_KICK_ON_LOGIN, "replaceKickOnLogin", true); + loadBoolConfig(L, MARKET_PREMIUM, "premiumToCreateMarketOffer", true); + loadBoolConfig(L, EMOTE_SPELLS, "emoteSpells", false); + loadBoolConfig(L, STAMINA_SYSTEM, "staminaSystem", true); + loadBoolConfig(L, WARN_UNSAFE_SCRIPTS, "warnUnsafeScripts", true); + loadBoolConfig(L, CONVERT_UNSAFE_SCRIPTS, "convertUnsafeScripts", true); + loadBoolConfig(L, CLASSIC_ATTACK_SPEED, "classicAttackSpeed", false); + loadBoolConfig(L, TOGGLE_ATTACK_SPEED_ONFIST, "toggleAttackSpeedOnFist", false); + loadIntConfig(L, MULTIPLIER_ATTACKONFIST, "multiplierSpeedOnFist", 5); + loadIntConfig(L, MAX_SPEED_ATTACKONFIST, "maxSpeedOnFist", 500); + loadBoolConfig(L, SCRIPTS_CONSOLE_LOGS, "showScriptsLogInConsole", true); + loadBoolConfig(L, STASH_MOVING, "stashMoving", false); + loadBoolConfig(L, ALLOW_BLOCK_SPAWN, "allowBlockSpawn", true); + loadBoolConfig(L, REMOVE_WEAPON_AMMO, "removeWeaponAmmunition", true); + loadBoolConfig(L, REMOVE_WEAPON_CHARGES, "removeWeaponCharges", true); + loadBoolConfig(L, REMOVE_POTION_CHARGES, "removeChargesFromPotions", true); + loadBoolConfig(L, GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE, "globalServerSaveNotifyMessage", true); + loadBoolConfig(L, GLOBAL_SERVER_SAVE_CLEAN_MAP, "globalServerSaveCleanMap", false); + loadBoolConfig(L, GLOBAL_SERVER_SAVE_CLOSE, "globalServerSaveClose", false); + loadBoolConfig(L, FORCE_MONSTERTYPE_LOAD, "forceMonsterTypesOnLoad", true); + loadBoolConfig(L, HOUSE_OWNED_BY_ACCOUNT, "houseOwnedByAccount", false); + loadBoolConfig(L, CLEAN_PROTECTION_ZONES, "cleanProtectionZones", false); + loadBoolConfig(L, GLOBAL_SERVER_SAVE_SHUTDOWN, "globalServerSaveShutdown", true); + loadBoolConfig(L, PUSH_WHEN_ATTACKING, "pushWhenAttacking", false); + + loadBoolConfig(L, WEATHER_RAIN, "weatherRain", false); + loadBoolConfig(L, WEATHER_THUNDER, "thunderEffect", false); + loadBoolConfig(L, ALL_CONSOLE_LOG, "allConsoleLog", false); + loadBoolConfig(L, TOGGLE_FREE_QUEST, "toggleFreeQuest", true); + loadBoolConfig(L, AUTOLOOT, "autoLoot", false); + loadBoolConfig(L, AUTOBANK, "autoBank", false); + loadBoolConfig(L, STAMINA_TRAINER, "staminaTrainer", false); + loadBoolConfig(L, STAMINA_PZ, "staminaPz", false); + loadBoolConfig(L, SORT_LOOT_BY_CHANCE, "sortLootByChance", false); + loadBoolConfig(L, TOGGLE_SAVE_INTERVAL, "toggleSaveInterval", false); + loadBoolConfig(L, TOGGLE_SAVE_INTERVAL_CLEAN_MAP, "toggleSaveIntervalCleanMap", false); + loadBoolConfig(L, TELEPORT_SUMMONS, "teleportSummons", false); + loadBoolConfig(L, ALLOW_RELOAD, "allowReload", false); + + loadBoolConfig(L, ONLY_PREMIUM_ACCOUNT, "onlyPremiumAccount", false); + loadBoolConfig(L, RATE_USE_STAGES, "rateUseStages", false); + loadBoolConfig(L, TOGGLE_IMBUEMENT_SHRINE_STORAGE, "toggleImbuementShrineStorage", true); + loadBoolConfig(L, TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY, "toggleImbuementNonAggressiveFightOnly", false); + + loadBoolConfig(L, TOGGLE_DOWNLOAD_MAP, "toggleDownloadMap", false); + loadBoolConfig(L, USE_ANY_DATAPACK_FOLDER, "useAnyDatapackFolder", false); + loadBoolConfig(L, INVENTORY_GLOW, "inventoryGlowOnFiveBless", false); + loadBoolConfig(L, XP_DISPLAY_MODE, "experienceDisplayRates", true); + + loadStringConfig(L, DEFAULT_PRIORITY, "defaultPriority", "high"); + loadStringConfig(L, SERVER_NAME, "serverName", ""); + loadStringConfig(L, SERVER_MOTD, "serverMotd", ""); + loadStringConfig(L, OWNER_NAME, "ownerName", ""); + loadStringConfig(L, OWNER_EMAIL, "ownerEmail", ""); + loadStringConfig(L, URL, "url", ""); + loadStringConfig(L, LOCATION, "location", ""); + loadStringConfig(L, WORLD_TYPE, "worldType", "pvp"); + loadStringConfig(L, STORE_IMAGES_URL, "coinImagesURL", ""); + loadStringConfig(L, DISCORD_WEBHOOK_URL, "discordWebhookURL", ""); + loadStringConfig(L, SAVE_INTERVAL_TYPE, "saveIntervalType", ""); + loadStringConfig(L, GLOBAL_SERVER_SAVE_TIME, "globalServerSaveTime", "06:00"); + loadStringConfig(L, DATA_DIRECTORY, "dataPackDirectory", "data-otservbr-global"); + loadStringConfig(L, CORE_DIRECTORY, "coreDirectory", "data"); + + loadStringConfig(L, FORGE_FIENDISH_INTERVAL_TYPE, "forgeFiendishIntervalType", "hour"); + loadStringConfig(L, FORGE_FIENDISH_INTERVAL_TIME, "forgeFiendishIntervalTime", "1"); + + loadIntConfig(L, MAX_PLAYERS, "maxPlayers", 0); + loadIntConfig(L, PZ_LOCKED, "pzLocked", 60000); + loadIntConfig(L, DEFAULT_DESPAWNRANGE, "deSpawnRange", 2); + loadIntConfig(L, DEFAULT_DESPAWNRADIUS, "deSpawnRadius", 50); + loadIntConfig(L, RATE_EXPERIENCE, "rateExp", 1); + loadIntConfig(L, RATE_SKILL, "rateSkill", 1); + loadIntConfig(L, RATE_LOOT, "rateLoot", 1); + loadIntConfig(L, RATE_MAGIC, "rateMagic", 1); + loadIntConfig(L, RATE_SPAWN, "rateSpawn", 1); + loadIntConfig(L, RATE_KILLING_IN_THE_NAME_OF_POINTS, "rateKillingInTheNameOfPoints", 1); + + loadIntConfig(L, HOUSE_PRICE_PER_SQM, "housePriceEachSQM", 1000); + loadIntConfig(L, HOUSE_BUY_LEVEL, "houseBuyLevel", 0); + loadIntConfig(L, HOUSE_LOSE_AFTER_INACTIVITY, "houseLoseAfterInactivity", 0); + loadBoolConfig(L, HOUSE_PURSHASED_SHOW_PRICE, "housePurchasedShowPrice", false); + loadBoolConfig(L, ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, "onlyInvitedCanMoveHouseItems", true); + + loadIntConfig(L, ACTIONS_DELAY_INTERVAL, "timeBetweenActions", 200); + loadIntConfig(L, EX_ACTIONS_DELAY_INTERVAL, "timeBetweenExActions", 1000); + loadIntConfig(L, MAX_MESSAGEBUFFER, "maxMessageBuffer", 4); + loadIntConfig(L, KICK_AFTER_MINUTES, "kickIdlePlayerAfterMinutes", 15); + loadIntConfig(L, PROTECTION_LEVEL, "protectionLevel", 1); + loadIntConfig(L, DEATH_LOSE_PERCENT, "deathLosePercent", -1); + loadIntConfig(L, STATUSQUERY_TIMEOUT, "statusTimeout", 5000); + loadIntConfig(L, FRAG_TIME, "timeToDecreaseFrags", 24 * 60 * 60 * 1000); + loadIntConfig(L, WHITE_SKULL_TIME, "whiteSkullTime", 15 * 60 * 1000); + loadIntConfig(L, STAIRHOP_DELAY, "stairJumpExhaustion", 2000); + loadIntConfig(L, MAX_CONTAINER, "maxContainer", 500); + loadIntConfig(L, MAX_CONTAINER_ITEM, "maxItem", 5000); + loadIntConfig(L, EXP_FROM_PLAYERS_LEVEL_RANGE, "expFromPlayersLevelRange", 75); + loadIntConfig(L, CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES, "checkExpiredMarketOffersEachMinutes", 60); + loadIntConfig(L, MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER, "maxMarketOffersAtATimePerPlayer", 100); + loadIntConfig(L, MAX_PACKETS_PER_SECOND, "maxPacketsPerSecond", 25); + loadIntConfig(L, COMPRESSION_LEVEL, "packetCompressionLevel", 6); + loadIntConfig(L, STORE_COIN_PACKET, "coinPacketSize", 25); + loadIntConfig(L, DAY_KILLS_TO_RED, "dayKillsToRedSkull", 3); + loadIntConfig(L, WEEK_KILLS_TO_RED, "weekKillsToRedSkull", 5); + loadIntConfig(L, MONTH_KILLS_TO_RED, "monthKillsToRedSkull", 10); + loadIntConfig(L, RED_SKULL_DURATION, "redSkullDuration", 30); + loadIntConfig(L, BLACK_SKULL_DURATION, "blackSkullDuration", 45); + loadIntConfig(L, ORANGE_SKULL_DURATION, "orangeSkullDuration", 7); + loadIntConfig(L, GLOBAL_SERVER_SAVE_NOTIFY_DURATION, "globalServerSaveNotifyDuration", 5); + + loadIntConfig(L, PARTY_LIST_MAX_DISTANCE, "partyListMaxDistance", 0); + + loadIntConfig(L, PUSH_DELAY, "pushDelay", 1000); + loadIntConfig(L, PUSH_DISTANCE_DELAY, "pushDistanceDelay", 1500); + + loadIntConfig(L, STAMINA_ORANGE_DELAY, "staminaOrangeDelay", 1); + loadIntConfig(L, STAMINA_GREEN_DELAY, "staminaGreenDelay", 5); + loadIntConfig(L, STAMINA_PZ_GAIN, "staminaPzGain", 1); + loadIntConfig(L, STAMINA_TRAINER_DELAY, "staminaTrainerDelay", 5); + loadIntConfig(L, STAMINA_TRAINER_GAIN, "staminaTrainerGain", 1); + loadIntConfig(L, SAVE_INTERVAL_TIME, "saveIntervalTime", 1); + loadIntConfig(L, MAX_ALLOWED_ON_A_DUMMY, "maxAllowedOnADummy", 1); + loadIntConfig(L, FREE_QUEST_STAGE, "freeQuestStage", 1); + loadIntConfig(L, DEPOTCHEST, "depotChest", 4); + loadIntConfig(L, CRITICALCHANCE, "criticalChance", 10); + + loadIntConfig(L, ADVENTURERSBLESSING_LEVEL, "adventurersBlessingLevel", 21); + loadIntConfig(L, FORGE_MAX_ITEM_TIER, "forgeMaxItemTier", 10); + loadIntConfig(L, FORGE_COST_ONE_SLIVER, "forgeCostOneSliver", 20); + loadIntConfig(L, FORGE_SLIVER_AMOUNT, "forgeSliverAmount", 3); + loadIntConfig(L, FORGE_CORE_COST, "forgeCoreCost", 50); + loadIntConfig(L, FORGE_MAX_DUST, "forgeMaxDust", 225); + loadIntConfig(L, FORGE_FUSION_DUST_COST, "forgeFusionCost", 100); + loadIntConfig(L, FORGE_TRANSFER_DUST_COST, "forgeTransferCost", 100); + loadIntConfig(L, FORGE_BASE_SUCCESS_RATE, "forgeBaseSuccessRate", 50); + loadIntConfig(L, FORGE_BONUS_SUCCESS_RATE, "forgeBonusSuccessRate", 15); + loadIntConfig(L, FORGE_TIER_LOSS_REDUCTION, "forgeTierLossReduction", 50); + loadIntConfig(L, FORGE_AMOUNT_MULTIPLIER, "forgeAmountMultiplier", 3); + loadIntConfig(L, FORGE_MIN_SLIVERS, "forgeMinSlivers", 3); + loadIntConfig(L, FORGE_MAX_SLIVERS, "forgeMaxSlivers", 7); + loadIntConfig(L, FORGE_INFLUENCED_CREATURES_LIMIT, "forgeInfluencedLimit", 300); + loadIntConfig(L, FORGE_FIENDISH_CREATURES_LIMIT, "forgeFiendishLimit", 3); + loadIntConfig(L, DISCORD_WEBHOOK_DELAY_MS, "discordWebhookDelayMs", Webhook::DEFAULT_DELAY_MS); + + loadFloatConfig(L, BESTIARY_RATE_CHARM_SHOP_PRICE, "bestiaryRateCharmShopPrice", 1.0); + loadFloatConfig(L, RATE_HEALTH_REGEN, "rateHealthRegen", 1.0); + loadFloatConfig(L, RATE_HEALTH_REGEN_SPEED, "rateHealthRegenSpeed", 1.0); + loadFloatConfig(L, RATE_MANA_REGEN, "rateManaRegen", 1.0); + loadFloatConfig(L, RATE_MANA_REGEN_SPEED, "rateManaRegenSpeed", 1.0); + loadFloatConfig(L, RATE_SOUL_REGEN, "rateSoulRegen", 1.0); + loadFloatConfig(L, RATE_SOUL_REGEN_SPEED, "rateSoulRegenSpeed", 1.0); + loadFloatConfig(L, RATE_SPELL_COOLDOWN, "rateSpellCooldown", 1.0); + loadFloatConfig(L, RATE_ATTACK_SPEED, "rateAttackSpeed", 1.0); + loadFloatConfig(L, RATE_OFFLINE_TRAINING_SPEED, "rateOfflineTrainingSpeed", 1.0); + loadFloatConfig(L, RATE_EXERCISE_TRAINING_SPEED, "rateExerciseTrainingSpeed", 1.0); + + loadFloatConfig(L, RATE_MONSTER_HEALTH, "rateMonsterHealth", 1.0); + loadFloatConfig(L, RATE_MONSTER_ATTACK, "rateMonsterAttack", 1.0); + loadFloatConfig(L, RATE_MONSTER_DEFENSE, "rateMonsterDefense", 1.0); + loadFloatConfig(L, RATE_BOSS_HEALTH, "rateBossHealth", 1.0); + loadFloatConfig(L, RATE_BOSS_ATTACK, "rateBossAttack", 1.0); + loadFloatConfig(L, RATE_BOSS_DEFENSE, "rateBossDefense", 1.0); + loadIntConfig(L, BOSS_DEFAULT_TIME_TO_FIGHT_AGAIN, "bossDefaultTimeToFightAgain", 20 * 60 * 60); + loadIntConfig(L, BOSS_DEFAULT_TIME_TO_DEFEAT, "bossDefaultTimeToDefeat", 20 * 60); + + loadFloatConfig(L, RATE_NPC_HEALTH, "rateNpcHealth", 1.0); + loadFloatConfig(L, RATE_NPC_ATTACK, "rateNpcAttack", 1.0); + loadFloatConfig(L, RATE_NPC_DEFENSE, "rateNpcDefense", 1.0); + + loadBoolConfig(L, PREY_ENABLED, "preySystemEnabled", true); + loadBoolConfig(L, PREY_FREE_THIRD_SLOT, "preyFreeThirdSlot", false); + loadIntConfig(L, PREY_REROLL_PRICE_LEVEL, "preyRerollPricePerLevel", 200); + loadIntConfig(L, PREY_SELECTION_LIST_PRICE, "preySelectListPrice", 5); + loadIntConfig(L, PREY_BONUS_TIME, "preyBonusTime", 7200); + loadIntConfig(L, PREY_BONUS_REROLL_PRICE, "preyBonusRerollPrice", 1); + loadIntConfig(L, PREY_FREE_REROLL_TIME, "preyFreeRerollTime", 72000); + + loadBoolConfig(L, TASK_HUNTING_ENABLED, "taskHuntingSystemEnabled", true); + loadBoolConfig(L, TASK_HUNTING_FREE_THIRD_SLOT, "taskHuntingFreeThirdSlot", false); + loadIntConfig(L, TASK_HUNTING_LIMIT_EXHAUST, "taskHuntingLimitedTasksExhaust", 72000); + loadIntConfig(L, TASK_HUNTING_REROLL_PRICE_LEVEL, "taskHuntingRerollPricePerLevel", 200); + loadIntConfig(L, TASK_HUNTING_SELECTION_LIST_PRICE, "taskHuntingSelectListPrice", 5); + loadIntConfig(L, TASK_HUNTING_BONUS_REROLL_PRICE, "taskHuntingBonusRerollPrice", 1); + loadIntConfig(L, TASK_HUNTING_FREE_REROLL_TIME, "taskHuntingFreeRerollTime", 72000); + + loadIntConfig(L, BESTIARY_KILL_MULTIPLIER, "bestiaryKillMultiplier", 1); + loadIntConfig(L, BOSSTIARY_KILL_MULTIPLIER, "bosstiaryKillMultiplier", 1); + loadBoolConfig(L, BOOSTED_BOSS_SLOT, "boostedBossSlot", true); + loadIntConfig(L, BOOSTED_BOSS_LOOT_BONUS, "boostedBossLootBonus", 250); + loadIntConfig(L, BOOSTED_BOSS_KILL_BONUS, "boostedBossKillBonus", 3); + + loadIntConfig(L, FAMILIAR_TIME, "familiarTime", 30); + + loadBoolConfig(L, TOGGLE_GOLD_POUCH_ALLOW_ANYTHING, "toggleGoldPouchAllowAnything", false); + loadBoolConfig(L, TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY, "toggleGoldPouchQuickLootOnly", false); + loadBoolConfig(L, TOGGLE_SERVER_IS_RETRO, "toggleServerIsRetroPVP", false); + loadBoolConfig(L, TOGGLE_TRAVELS_FREE, "toggleTravelsFree", false); + loadIntConfig(L, BUY_AOL_COMMAND_FEE, "buyAolCommandFee", 0); + loadIntConfig(L, BUY_BLESS_COMMAND_FEE, "buyBlessCommandFee", 0); + loadBoolConfig(L, TELEPORT_PLAYER_TO_VOCATION_ROOM, "teleportPlayerToVocationRoom", true); + + loadBoolConfig(L, TOGGLE_HAZARDSYSTEM, "toogleHazardSystem", true); + loadIntConfig(L, HAZARD_CRITICAL_INTERVAL, "hazardCriticalInterval", 2000); + loadIntConfig(L, HAZARD_CRITICAL_CHANCE, "hazardCriticalChance", 750); + loadIntConfig(L, HAZARD_CRITICAL_MULTIPLIER, "hazardCriticalMultiplier", 25); + loadIntConfig(L, HAZARD_DAMAGE_MULTIPLIER, "hazardDamageMultiplier", 200); + loadIntConfig(L, HAZARD_DODGE_MULTIPLIER, "hazardDodgeMultiplier", 85); + loadIntConfig(L, HAZARD_PODS_DROP_MULTIPLIER, "hazardPodsDropMultiplier", 87); + loadIntConfig(L, HAZARD_PODS_TIME_TO_DAMAGE, "hazardPodsTimeToDamage", 2000); + loadIntConfig(L, HAZARD_PODS_TIME_TO_SPAWN, "hazardPodsTimeToSpawn", 4000); + loadIntConfig(L, HAZARD_EXP_BONUS_MULTIPLIER, "hazardExpBonusMultiplier", 2); + loadIntConfig(L, HAZARD_LOOT_BONUS_MULTIPLIER, "hazardLootBonusMultiplier", 2); + loadIntConfig(L, HAZARD_PODS_DAMAGE, "hazardPodsDamage", 5); + loadIntConfig(L, HAZARD_SPAWN_PLUNDER_MULTIPLIER, "hazardSpawnPlunderMultiplier", 25); + loadIntConfig(L, LOW_LEVEL_BONUS_EXP, "lowLevelBonusExp", 50); + + loadBoolConfig(L, LOYALTY_ENABLED, "loyaltyEnabled", true); + loadIntConfig(L, LOYALTY_POINTS_PER_CREATION_DAY, "loyaltyPointsPerCreationDay", 1); + loadIntConfig(L, LOYALTY_POINTS_PER_PREMIUM_DAY_SPENT, "loyaltyPointsPerPremiumDaySpent", 0); + loadIntConfig(L, LOYALTY_POINTS_PER_PREMIUM_DAY_PURCHASED, "loyaltyPointsPerPremiumDayPurchased", 0); + loadFloatConfig(L, LOYALTY_BONUS_PERCENTAGE_MULTIPLIER, "loyaltyBonusPercentageMultiplier", 1.0); + + loadBoolConfig(L, TOGGLE_WHEELSYSTEM, "wheelSystemEnabled", true); + loadIntConfig(L, WHEEL_POINTS_PER_LEVEL, "wheelPointsPerLevel", 1); + + loadBoolConfig(L, PARTY_AUTO_SHARE_EXPERIENCE, "partyAutoShareExperience", true); + loadBoolConfig(L, PARTY_SHARE_LOOT_BOOSTS, "partyShareLootBoosts", true); + loadFloatConfig(L, PARTY_SHARE_LOOT_BOOSTS_DIMINISHING_FACTOR, "partyShareLootBoostsDimishingFactor", 0.7f); + loadIntConfig(L, TIBIADROME_CONCOCTION_COOLDOWN, "tibiadromeConcoctionCooldown", 24 * 60 * 60); + loadIntConfig(L, TIBIADROME_CONCOCTION_DURATION, "tibiadromeConcoctionDuration", 1 * 60 * 60); + loadStringConfig(L, TIBIADROME_CONCOCTION_TICK_TYPE, "tibiadromeConcoctionTickType", "online"); + + loadStringConfig(L, M_CONST, "memoryConst", "1<<16"); + loadIntConfig(L, T_CONST, "temporaryConst", 2); + loadIntConfig(L, PARALLELISM, "parallelism", 2); // Vip System - boolean[VIP_SYSTEM_ENABLED] = getGlobalBoolean(L, "vipSystemEnabled", false); - integer[VIP_BONUS_EXP] = getGlobalNumber(L, "vipBonusExp", 0); - integer[VIP_BONUS_LOOT] = getGlobalNumber(L, "vipBonusLoot", 0); - integer[VIP_BONUS_SKILL] = getGlobalNumber(L, "vipBonusSkill", 0); - boolean[VIP_AUTOLOOT_VIP_ONLY] = getGlobalBoolean(L, "vipAutoLootVipOnly", false); - boolean[VIP_KEEP_HOUSE] = getGlobalBoolean(L, "vipKeepHouse", false); - boolean[VIP_STAY_ONLINE] = getGlobalBoolean(L, "vipStayOnline", false); - integer[VIP_FAMILIAR_TIME_COOLDOWN_REDUCTION] = getGlobalNumber(L, "vipFamiliarTimeCooldownReduction", 0); - - boolean[REWARD_CHEST_COLLECT_ENABLED] = getGlobalBoolean(L, "rewardChestCollectEnabled", true); - integer[REWARD_CHEST_MAX_COLLECT_ITEMS] = getGlobalNumber(L, "rewardChestMaxCollectItems", 200); + loadBoolConfig(L, VIP_SYSTEM_ENABLED, "vipSystemEnabled", false); + loadIntConfig(L, VIP_BONUS_EXP, "vipBonusExp", 0); + loadIntConfig(L, VIP_BONUS_LOOT, "vipBonusLoot", 0); + loadIntConfig(L, VIP_BONUS_SKILL, "vipBonusSkill", 0); + loadBoolConfig(L, VIP_AUTOLOOT_VIP_ONLY, "vipAutoLootVipOnly", false); + loadBoolConfig(L, VIP_KEEP_HOUSE, "vipKeepHouse", false); + loadBoolConfig(L, VIP_STAY_ONLINE, "vipStayOnline", false); + loadIntConfig(L, VIP_FAMILIAR_TIME_COOLDOWN_REDUCTION, "vipFamiliarTimeCooldownReduction", 0); + + loadBoolConfig(L, REWARD_CHEST_COLLECT_ENABLED, "rewardChestCollectEnabled", true); + loadIntConfig(L, REWARD_CHEST_MAX_COLLECT_ITEMS, "rewardChestMaxCollectItems", 200); // PVP System - floating[PVP_RATE_DAMAGE_TAKEN_PER_LEVEL] = getGlobalFloat(L, "pvpRateDamageTakenPerLevel", 0.0); - floating[PVP_RATE_DAMAGE_REDUCTION_PER_LEVEL] = getGlobalFloat(L, "pvpRateDamageReductionPerLevel", 0.0); - integer[PVP_MAX_LEVEL_DIFFERENCE] = getGlobalNumber(L, "pvpMaxLevelDifference", 0); + loadFloatConfig(L, PVP_RATE_DAMAGE_TAKEN_PER_LEVEL, "pvpRateDamageTakenPerLevel", 0.0); + loadFloatConfig(L, PVP_RATE_DAMAGE_REDUCTION_PER_LEVEL, "pvpRateDamageReductionPerLevel", 0.0); + loadIntConfig(L, PVP_MAX_LEVEL_DIFFERENCE, "pvpMaxLevelDifference", 0); - boolean[TOGGLE_MOUNT_IN_PZ] = getGlobalBoolean(L, "toggleMountInProtectionZone", false); + loadBoolConfig(L, TOGGLE_MOUNT_IN_PZ, "toggleMountInProtectionZone", false); - boolean[TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART] = getGlobalBoolean(L, "togglehouseTransferOnRestart", false); + loadBoolConfig(L, TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, "togglehouseTransferOnRestart", false); - boolean[TOGGLE_RECEIVE_REWARD] = getGlobalBoolean(L, "toggleReceiveReward", false); + loadBoolConfig(L, TOGGLE_RECEIVE_REWARD, "toggleReceiveReward", false); loaded = true; lua_close(L); @@ -409,51 +353,86 @@ bool ConfigManager::load() { } bool ConfigManager::reload() { - bool result = load(); - if (transformToSHA1(getString(SERVER_MOTD)) != g_game().getMotdHash()) { + const bool result = load(); + if (transformToSHA1(getString(SERVER_MOTD, __FUNCTION__)) != g_game().getMotdHash()) { g_game().incrementMotdNum(); } return result; } -static std::string dummyStr; +std::string ConfigManager::loadStringConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const std::string &defaultValue) { + std::string value = defaultValue; + lua_getglobal(L, identifier); + if (lua_isstring(L, -1)) { + value = lua_tostring(L, -1); + } + configs[key] = value; + lua_pop(L, 1); + return value; +} -const std::string &ConfigManager::getString(stringConfig_t what) const { - if (what >= LAST_STRING_CONFIG) { - g_logger().warn("[ConfigManager::getString] - Accessing invalid index: {}", fmt::underlying(what)); - return dummyStr; +int32_t ConfigManager::loadIntConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const int32_t &defaultValue) { + int32_t value = defaultValue; + lua_getglobal(L, identifier); + if (lua_isnumber(L, -1)) { + value = static_cast(lua_tointeger(L, -1)); } - return string[what]; + configs[key] = value; + lua_pop(L, 1); + return value; } -int32_t ConfigManager::getNumber(integerConfig_t what) const { - if (what >= LAST_INTEGER_CONFIG) { - g_logger().warn("[ConfigManager::getNumber] - Accessing invalid index: {}", fmt::underlying(what)); - return 0; +bool ConfigManager::loadBoolConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const bool &defaultValue) { + bool value = defaultValue; + lua_getglobal(L, identifier); + if (lua_isboolean(L, -1)) { + value = static_cast(lua_toboolean(L, -1)); } - return integer[what]; + configs[key] = value; + lua_pop(L, 1); + return value; } -int16_t ConfigManager::getShortNumber(integerConfig_t what) const { - if (what >= LAST_INTEGER_CONFIG) { - g_logger().warn("[ConfigManager::getShortNumber] - Accessing invalid index: {}", fmt::underlying(what)); - return 0; +float ConfigManager::loadFloatConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const float &defaultValue) { + float value = defaultValue; + lua_getglobal(L, identifier); + if (lua_isnumber(L, -1)) { + value = static_cast(lua_tonumber(L, -1)); } - return integer[what]; + configs[key] = value; + lua_pop(L, 1); + return value; } -bool ConfigManager::getBoolean(booleanConfig_t what) const { - if (what >= LAST_BOOLEAN_CONFIG) { - g_logger().warn("[ConfigManager::getBoolean] - Accessing invalid index: {}", fmt::underlying(what)); - return false; +const std::string &ConfigManager::getString(const ConfigKey_t &key, std::string_view context) const { + static const std::string dummyStr; + if (configs.contains(key) && std::holds_alternative(configs.at(key))) { + return std::get(configs.at(key)); + } + g_logger().warn("[ConfigManager::getString] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context); + return dummyStr; +} + +int32_t ConfigManager::getNumber(const ConfigKey_t &key, std::string_view context) const { + if (configs.contains(key) && std::holds_alternative(configs.at(key))) { + return std::get(configs.at(key)); + } + g_logger().warn("[ConfigManager::getNumber] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context); + return 0; +} + +bool ConfigManager::getBoolean(const ConfigKey_t &key, std::string_view context) const { + if (configs.contains(key) && std::holds_alternative(configs.at(key))) { + return std::get(configs.at(key)); } - return boolean[what]; + g_logger().warn("[ConfigManager::getBoolean] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context); + return false; } -float ConfigManager::getFloat(floatingConfig_t what) const { - if (what >= LAST_FLOATING_CONFIG) { - g_logger().warn("[ConfigManager::getFLoat] - Accessing invalid index: {}", fmt::underlying(what)); - return 0; +float ConfigManager::getFloat(const ConfigKey_t &key, std::string_view context) const { + if (configs.contains(key) && std::holds_alternative(configs.at(key))) { + return std::get(configs.at(key)); } - return floating[what]; + g_logger().warn("[ConfigManager::getFloat] - Accessing invalid or wrong type index: {}[{}], Function: {}", magic_enum::enum_name(key), fmt::underlying(key), context); + return 0.0f; } diff --git a/src/config/configmanager.hpp b/src/config/configmanager.hpp index 21e42f9e7..e419733b9 100644 --- a/src/config/configmanager.hpp +++ b/src/config/configmanager.hpp @@ -12,6 +12,8 @@ #include "declarations.hpp" #include "lib/di/container.hpp" +using ConfigValue = std::variant; + class ConfigManager { public: ConfigManager() = default; @@ -27,28 +29,27 @@ class ConfigManager { bool load(); bool reload(); - const std::string &getString(stringConfig_t what) const; - int32_t getNumber(integerConfig_t what) const; - int16_t getShortNumber(integerConfig_t what) const; - bool getBoolean(booleanConfig_t what) const; - float getFloat(floatingConfig_t what) const; - const std::string &setConfigFileLua(const std::string &what) { configFileLua = { what }; return configFileLua; }; - const std::string &getConfigFileLua() const { + [[nodiscard]] const std::string &getConfigFileLua() const { return configFileLua; }; -private: - std::string configFileLua = { "config.lua" }; + [[nodiscard]] const std::string &getString(const ConfigKey_t &key, std::string_view context) const; + [[nodiscard]] int32_t getNumber(const ConfigKey_t &key, std::string_view context) const; + [[nodiscard]] bool getBoolean(const ConfigKey_t &key, std::string_view context) const; + [[nodiscard]] float getFloat(const ConfigKey_t &key, std::string_view context) const; - std::string string[LAST_STRING_CONFIG] = {}; - int32_t integer[LAST_INTEGER_CONFIG] = {}; - bool boolean[LAST_BOOLEAN_CONFIG] = {}; - float floating[LAST_FLOATING_CONFIG] = {}; +private: + phmap::flat_hash_map configs; + std::string loadStringConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const std::string &defaultValue); + int32_t loadIntConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const int32_t &defaultValue); + bool loadBoolConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const bool &defaultValue); + float loadFloatConfig(lua_State* L, const ConfigKey_t &key, const char* identifier, const float &defaultValue); + std::string configFileLua = { "config.lua" }; bool loaded = false; }; diff --git a/src/creatures/appearance/mounts/mounts.cpp b/src/creatures/appearance/mounts/mounts.cpp index 22fdec2fe..e28b34ea7 100644 --- a/src/creatures/appearance/mounts/mounts.cpp +++ b/src/creatures/appearance/mounts/mounts.cpp @@ -21,7 +21,7 @@ bool Mounts::reload() { bool Mounts::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/mounts.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/mounts.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); @@ -30,8 +30,8 @@ bool Mounts::loadFromXml() { for (auto mountNode : doc.child("mounts").children()) { uint16_t lookType = pugi::cast(mountNode.attribute("clientid").value()); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { - g_logger().warn("{} - An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", __FUNCTION__, lookType); + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { + g_logger().warn("{} - An unregistered creature mount with id '{}' was blocked to prevent client crash.", __FUNCTION__, lookType); continue; } diff --git a/src/creatures/appearance/outfit/outfit.cpp b/src/creatures/appearance/outfit/outfit.cpp index b542e97e0..779ba64c9 100644 --- a/src/creatures/appearance/outfit/outfit.cpp +++ b/src/creatures/appearance/outfit/outfit.cpp @@ -16,7 +16,7 @@ bool Outfits::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/outfits.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/outfits.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); @@ -47,7 +47,7 @@ bool Outfits::loadFromXml() { } if (uint16_t lookType = pugi::cast(lookTypeAttribute.value()); - g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 + g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { g_logger().warn("[Outfits::loadFromXml] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", lookType); return false; diff --git a/src/creatures/combat/combat.cpp b/src/creatures/combat/combat.cpp index 2a646be07..151e5458a 100644 --- a/src/creatures/combat/combat.cpp +++ b/src/creatures/combat/combat.cpp @@ -276,7 +276,7 @@ bool Combat::isInPvpZone(std::shared_ptr attacker, std::shared_ptr attacker, std::shared_ptr target) { - uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL); + uint32_t protectionLevel = g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__); if (target->getLevel() < protectionLevel || attacker->getLevel() < protectionLevel) { return true; } @@ -569,7 +569,7 @@ void Combat::CombatHealthFunc(std::shared_ptr caster, std::shared_ptr< targetPlayer = target->getPlayer(); } - if (caster && attackerPlayer) { + if (attackerPlayer) { std::shared_ptr item = attackerPlayer->getWeapon(); damage = applyImbuementElementalDamage(attackerPlayer, item, damage); g_events().eventPlayerOnCombat(attackerPlayer, target, item, damage); @@ -582,6 +582,9 @@ void Combat::CombatHealthFunc(std::shared_ptr caster, std::shared_ptr< damage.secondary.value /= 2; } } + + damage.damageMultiplier += attackerPlayer->wheel()->getMajorStatConditional("Divine Empowerment", WheelMajor_t::DAMAGE); + g_logger().debug("Wheel Divine Empowerment damage multiplier {}", damage.damageMultiplier); } if (g_game().combatBlockHit(damage, caster, target, params.blockedByShield, params.blockedByArmor, params.itemId != 0)) { @@ -2021,13 +2024,12 @@ void Combat::applyExtensions(std::shared_ptr caster, std::shared_ptrgetPlayer(); auto monster = caster->getMonster(); if (player) { chance = player->getSkillLevel(SKILL_CRITICAL_HIT_CHANCE); - multiplier = player->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE); - + bonus = player->getSkillLevel(SKILL_CRITICAL_HIT_DAMAGE); if (target) { uint16_t playerCharmRaceid = player->parseRacebyCharm(CHARM_LOW, false, 0); if (playerCharmRaceid != 0) { @@ -2045,8 +2047,8 @@ void Combat::applyExtensions(std::shared_ptr caster, std::shared_ptrcritChance(); } - multiplier += damage.criticalDamage; - multiplier = 1 + multiplier / 100; + bonus += damage.criticalDamage; + double multiplier = 1.0 + static_cast(bonus) / 100; chance += (uint16_t)damage.criticalChance; if (chance != 0 && uniform_random(1, 100) <= chance) { diff --git a/src/creatures/combat/condition.cpp b/src/creatures/combat/condition.cpp index 4cf1834e1..1c4c636ba 100644 --- a/src/creatures/combat/condition.cpp +++ b/src/creatures/combat/condition.cpp @@ -1248,7 +1248,7 @@ uint32_t ConditionRegeneration::getHealthTicks(std::shared_ptr creatur std::shared_ptr player = creature->getPlayer(); if (player != nullptr && isBuff) { - return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN); + return healthTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); } return healthTicks; @@ -1258,7 +1258,7 @@ uint32_t ConditionRegeneration::getManaTicks(std::shared_ptr creature) std::shared_ptr player = creature->getPlayer(); if (player != nullptr && isBuff) { - return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN); + return manaTicks / g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); } return manaTicks; @@ -2257,7 +2257,7 @@ void ConditionOutfit::serialize(PropWriteStream &propWriteStream) { } bool ConditionOutfit::startCondition(std::shared_ptr creature) { - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { g_logger().warn("[ConditionOutfit::startCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); return false; } @@ -2289,7 +2289,7 @@ void ConditionOutfit::endCondition(std::shared_ptr creature) { } void ConditionOutfit::addCondition(std::shared_ptr creature, const std::shared_ptr addCondition) { - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { g_logger().warn("[ConditionOutfit::addCondition] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); return; } diff --git a/src/creatures/combat/spells.cpp b/src/creatures/combat/spells.cpp index d0f4d260d..4ae9d69ae 100644 --- a/src/creatures/combat/spells.cpp +++ b/src/creatures/combat/spells.cpp @@ -609,7 +609,7 @@ void Spell::setWheelOfDestinyBoost(WheelSpellBoost_t boost, WheelSpellGrade_t gr void Spell::applyCooldownConditions(std::shared_ptr player) const { WheelSpellGrade_t spellGrade = player->wheel()->getSpellUpgrade(getName()); bool isUpgraded = getWheelOfDestinyUpgraded() && static_cast(spellGrade) > 0; - auto rate_cooldown = (int32_t)g_configManager().getFloat(RATE_SPELL_COOLDOWN); + auto rate_cooldown = (int32_t)g_configManager().getFloat(RATE_SPELL_COOLDOWN, __FUNCTION__); if (cooldown > 0) { int32_t spellCooldown = cooldown; if (isUpgraded) { @@ -981,7 +981,7 @@ bool RuneSpell::executeUse(std::shared_ptr player, std::shared_ptr } postCastSpell(player); - if (hasCharges && item && g_configManager().getBoolean(REMOVE_RUNE_CHARGES)) { + if (hasCharges && item && g_configManager().getBoolean(REMOVE_RUNE_CHARGES, __FUNCTION__)) { int32_t newCount = std::max(0, item->getItemCount() - 1); g_game().transformItem(item, item->getID(), newCount); player->updateSupplyTracker(item); diff --git a/src/creatures/creature.cpp b/src/creatures/creature.cpp index 4d9894772..e9b674c54 100644 --- a/src/creatures/creature.cpp +++ b/src/creatures/creature.cpp @@ -470,7 +470,7 @@ void Creature::onCreatureMove(const std::shared_ptr &creature, const s stopEventWalk(); } - bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS); + bool configTeleportSummons = g_configManager().getBoolean(TELEPORT_SUMMONS, __FUNCTION__); checkSummonMove(newPos, configTeleportSummons); if (isLostSummon()) { handleLostSummon(configTeleportSummons); @@ -630,7 +630,7 @@ void Creature::onDeath() { std::shared_ptr mostDamageCreature = nullptr; const int64_t timeNow = OTSYS_TIME(); - const uint32_t inFightTicks = g_configManager().getNumber(PZ_LOCKED); + const uint32_t inFightTicks = g_configManager().getNumber(PZ_LOCKED, __FUNCTION__); int32_t mostDamage = 0; std::map, uint64_t> experienceMap; std::unordered_set> killers; @@ -788,7 +788,7 @@ bool Creature::hasBeenAttacked(uint32_t attackerId) { if (it == damageMap.end()) { return false; } - return (OTSYS_TIME() - it->second.ticks) <= g_configManager().getNumber(PZ_LOCKED); + return (OTSYS_TIME() - it->second.ticks) <= g_configManager().getNumber(PZ_LOCKED, __FUNCTION__); } std::shared_ptr Creature::getCorpse(std::shared_ptr, std::shared_ptr) { @@ -1064,7 +1064,7 @@ bool Creature::setFollowCreature(std::shared_ptr creature) { onWalkAborted(); } - hasFollowPath = false; + hasFollowPath = true; forceUpdateFollowPath = false; m_followCreature = creature; isUpdatingPath = true; diff --git a/src/creatures/interactions/chat.cpp b/src/creatures/interactions/chat.cpp index ddb6d0433..ec3472d7b 100644 --- a/src/creatures/interactions/chat.cpp +++ b/src/creatures/interactions/chat.cpp @@ -268,7 +268,7 @@ Chat::Chat() : bool Chat::load() { pugi::xml_document doc; - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); auto folder = coreFolder + "/chatchannels/chatchannels.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { diff --git a/src/creatures/monsters/monster.cpp b/src/creatures/monsters/monster.cpp index b2660933a..f4acbc1f3 100644 --- a/src/creatures/monsters/monster.cpp +++ b/src/creatures/monsters/monster.cpp @@ -773,7 +773,9 @@ void Monster::onThink(uint32_t interval) { } } else if (!targetList.empty()) { const bool attackedCreatureIsDisconnected = attackedCreature && attackedCreature->getPlayer() && attackedCreature->getPlayer()->isDisconnected(); - if (!attackedCreature || attackedCreatureIsDisconnected) { + const bool attackedCreatureIsUnattackable = attackedCreature && !canUseAttack(getPosition(), attackedCreature); + const bool attackedCreatureIsUnreachable = targetDistance <= 1 && attackedCreature && followCreature && !hasFollowPath; + if (!attackedCreature || attackedCreatureIsDisconnected || attackedCreatureIsUnattackable || attackedCreatureIsUnreachable) { if (!followCreature || !hasFollowPath || attackedCreatureIsDisconnected) { searchTarget(TARGETSEARCH_NEAREST); } else if (attackedCreature && isFleeing() && !canUseAttack(getPosition(), attackedCreature)) { @@ -1951,8 +1953,8 @@ void Monster::dropLoot(std::shared_ptr corpse, std::shared_ptr(uniform_random(minSlivers, maxSlivers)); @@ -1961,7 +1963,7 @@ void Monster::dropLoot(std::shared_ptr corpse, std::shared_ptrinternalAddThing(sliver); } } - if (!this->isRewardBoss() && g_configManager().getNumber(RATE_LOOT) > 0) { + if (!this->isRewardBoss() && g_configManager().getNumber(RATE_LOOT, __FUNCTION__) > 0) { g_callbacks().executeCallback(EventCallback_t::monsterOnDropLoot, &EventCallback::monsterOnDropLoot, getMonster(), corpse); g_callbacks().executeCallback(EventCallback_t::monsterPostDropLoot, &EventCallback::monsterPostDropLoot, getMonster(), corpse); } diff --git a/src/creatures/monsters/monsters.hpp b/src/creatures/monsters/monsters.hpp index a4723fcaa..bb911f2cc 100644 --- a/src/creatures/monsters/monsters.hpp +++ b/src/creatures/monsters/monsters.hpp @@ -185,15 +185,15 @@ class MonsterType { } float getHealthMultiplier() const { - return isBoss() ? g_configManager().getFloat(RATE_BOSS_HEALTH) : g_configManager().getFloat(RATE_MONSTER_HEALTH); + return isBoss() ? g_configManager().getFloat(RATE_BOSS_HEALTH, __FUNCTION__) : g_configManager().getFloat(RATE_MONSTER_HEALTH, __FUNCTION__); } float getAttackMultiplier() const { - return isBoss() ? g_configManager().getFloat(RATE_BOSS_ATTACK) : g_configManager().getFloat(RATE_MONSTER_ATTACK); + return isBoss() ? g_configManager().getFloat(RATE_BOSS_ATTACK, __FUNCTION__) : g_configManager().getFloat(RATE_MONSTER_ATTACK, __FUNCTION__); } float getDefenseMultiplier() const { - return isBoss() ? g_configManager().getFloat(RATE_BOSS_DEFENSE) : g_configManager().getFloat(RATE_MONSTER_DEFENSE); + return isBoss() ? g_configManager().getFloat(RATE_BOSS_DEFENSE, __FUNCTION__) : g_configManager().getFloat(RATE_MONSTER_DEFENSE, __FUNCTION__); } bool isBoss() const { diff --git a/src/creatures/monsters/spawns/spawn_monster.cpp b/src/creatures/monsters/spawns/spawn_monster.cpp index aa9bcb14c..9549ae593 100644 --- a/src/creatures/monsters/spawns/spawn_monster.cpp +++ b/src/creatures/monsters/spawns/spawn_monster.cpp @@ -95,7 +95,7 @@ bool SpawnsMonster::loadFromXML(const std::string &filemonstername) { boostedrate = 2; } - uint32_t interval = pugi::cast(childMonsterNode.attribute("spawntime").value()) * 1000 * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN) * boostedrate * eventschedule)); + uint32_t interval = pugi::cast(childMonsterNode.attribute("spawntime").value()) * 1000 * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * boostedrate * eventschedule)); if (interval >= MONSTER_MINSPAWN_INTERVAL && interval <= MONSTER_MAXSPAWN_INTERVAL) { spawnMonster.addMonster(nameAttribute.as_string(), pos, dir, static_cast(interval)); } else { @@ -233,7 +233,7 @@ void SpawnMonster::checkSpawnMonster() { scheduleSpawn(spawnMonsterId, sb, 3 * NONBLOCKABLE_SPAWN_MONSTER_INTERVAL); } - if (++spawnMonsterCount >= static_cast(g_configManager().getNumber(RATE_SPAWN))) { + if (++spawnMonsterCount >= static_cast(g_configManager().getNumber(RATE_SPAWN, __FUNCTION__))) { break; } } diff --git a/src/creatures/npcs/npc.cpp b/src/creatures/npcs/npc.cpp index 431d3113c..3991d01c1 100644 --- a/src/creatures/npcs/npc.cpp +++ b/src/creatures/npcs/npc.cpp @@ -36,7 +36,7 @@ Npc::Npc(const std::shared_ptr &npcType) : npcType(npcType) { defaultOutfit = npcType->info.outfit; currentOutfit = npcType->info.outfit; - float multiplier = g_configManager().getFloat(RATE_NPC_HEALTH); + float multiplier = g_configManager().getFloat(RATE_NPC_HEALTH, __FUNCTION__); health = npcType->info.health * multiplier; healthMax = npcType->info.healthMax * multiplier; baseSpeed = npcType->info.baseSpeed; @@ -261,7 +261,7 @@ void Npc::onPlayerBuyItem(std::shared_ptr player, uint16_t itemId, uint8 } uint32_t buyPrice = 0; - const std::vector &shopVector = getShopItemVector(); + const std::vector &shopVector = getShopItemVector(player->getGUID()); for (ShopBlock shopBlock : shopVector) { if (itemType.id == shopBlock.itemId && shopBlock.itemBuyPrice != 0) { buyPrice = shopBlock.itemBuyPrice; @@ -370,7 +370,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(); + const std::vector &shopVector = getShopItemVector(player->getGUID()); for (ShopBlock shopBlock : shopVector) { if (itemType.id == shopBlock.itemId && shopBlock.itemSellPrice != 0) { sellPrice = shopBlock.itemSellPrice; @@ -381,7 +381,7 @@ void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint } auto toRemove = amount; - for (auto inventoryItems = player->getInventoryItemsFromId(itemId, ignore); auto item : inventoryItems) { + for (auto item : player->getInventoryItemsFromId(itemId, ignore)) { if (!item || item->getTier() > 0 || item->hasImbuements()) { continue; } @@ -411,7 +411,7 @@ void Npc::onPlayerSellItem(std::shared_ptr player, uint16_t itemId, uint auto totalCost = static_cast(sellPrice * totalRemoved); if (getCurrency() == ITEM_GOLD_COIN) { totalPrice += totalCost; - if (g_configManager().getBoolean(AUTOBANK)) { + if (g_configManager().getBoolean(AUTOBANK, __FUNCTION__)) { player->setBankBalance(player->getBankBalance() + totalCost); } else { g_game().addMoney(player, totalCost); @@ -642,23 +642,25 @@ bool Npc::getRandomStep(Direction &moveDirection) { return false; } -void Npc::addShopPlayer(const std::shared_ptr &player) { +void Npc::addShopPlayer(const std::shared_ptr &player, const std::vector &shopItems /* = {}*/) { if (!player) { return; } - shopPlayerMap.try_emplace(player->getID(), player); + + shopPlayerMap.try_emplace(player->getGUID(), shopItems); } void Npc::removeShopPlayer(const std::shared_ptr &player) { if (!player) { return; } - shopPlayerMap.erase(player->getID()); + + shopPlayerMap.erase(player->getGUID()); } void Npc::closeAllShopWindows() { - for (auto &[_, playerPtr] : shopPlayerMap) { - auto shopPlayer = playerPtr.lock(); + for (const auto &[playerGUID, playerPtr] : shopPlayerMap) { + auto shopPlayer = g_game().getPlayerByGUID(playerGUID); if (shopPlayer) { shopPlayer->closeShopWindow(); } diff --git a/src/creatures/npcs/npc.hpp b/src/creatures/npcs/npc.hpp index 5f1183605..393b24867 100644 --- a/src/creatures/npcs/npc.hpp +++ b/src/creatures/npcs/npc.hpp @@ -96,7 +96,14 @@ class Npc final : public Creature { npcType->info.currencyId = currency; } - std::vector getShopItemVector() { + std::vector getShopItemVector(uint32_t playerGUID) { + if (playerGUID != 0) { + auto it = shopPlayerMap.find(playerGUID); + if (it != shopPlayerMap.end() && !it->second.empty()) { + return it->second; + } + } + return npcType->info.shopItemVector; } @@ -159,7 +166,7 @@ class Npc final : public Creature { internalLight = npcType->info.light; } - void addShopPlayer(const std::shared_ptr &player); + void addShopPlayer(const std::shared_ptr &player, const std::vector &shopItems = {}); void removeShopPlayer(const std::shared_ptr &player); void closeAllShopWindows(); @@ -178,7 +185,7 @@ class Npc final : public Creature { std::map playerInteractions; - phmap::flat_hash_map> shopPlayerMap; + phmap::flat_hash_map> shopPlayerMap; std::shared_ptr npcType; std::shared_ptr spawnNpc; diff --git a/src/creatures/npcs/npcs.cpp b/src/creatures/npcs/npcs.cpp index c18897d1c..0af1b0902 100644 --- a/src/creatures/npcs/npcs.cpp +++ b/src/creatures/npcs/npcs.cpp @@ -107,11 +107,11 @@ void NpcType::loadShop(const std::shared_ptr &npcType, ShopBlock shopBl bool Npcs::load(bool loadLibs /* = true*/, bool loadNpcs /* = true*/, bool reloading /* = false*/) const { if (loadLibs) { - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); return g_luaEnvironment().loadFile(coreFolder + "/npclib/load.lua", "load.lua") == 0; } if (loadNpcs) { - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); + auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); return g_scripts().loadScripts(datapackFolder + "/npc", false, reloading); } return false; diff --git a/src/creatures/players/grouping/familiars.cpp b/src/creatures/players/grouping/familiars.cpp index 0229519a6..58b0116fb 100644 --- a/src/creatures/players/grouping/familiars.cpp +++ b/src/creatures/players/grouping/familiars.cpp @@ -16,7 +16,7 @@ bool Familiars::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/familiars.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/familiars.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { g_logger().error("Failed to load Familiars"); diff --git a/src/creatures/players/grouping/groups.cpp b/src/creatures/players/grouping/groups.cpp index aea1c2b45..639837dab 100644 --- a/src/creatures/players/grouping/groups.cpp +++ b/src/creatures/players/grouping/groups.cpp @@ -69,7 +69,7 @@ void parseGroupFlags(Group &group, const pugi::xml_node &groupNode) { bool Groups::load() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/groups.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/groups.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); diff --git a/src/creatures/players/grouping/party.cpp b/src/creatures/players/grouping/party.cpp index b0a67a8ea..e78e4eddd 100644 --- a/src/creatures/players/grouping/party.cpp +++ b/src/creatures/players/grouping/party.cpp @@ -19,7 +19,7 @@ std::shared_ptr Party::create(std::shared_ptr leader) { auto party = std::make_shared(); party->m_leader = leader; leader->setParty(party); - if (g_configManager().getBoolean(PARTY_AUTO_SHARE_EXPERIENCE)) { + if (g_configManager().getBoolean(PARTY_AUTO_SHARE_EXPERIENCE, __FUNCTION__)) { party->setSharedExperience(leader, true); } return party; @@ -187,16 +187,16 @@ bool Party::passPartyLeadership(std::shared_ptr player) { for (auto member : getMembers()) { member->sendPartyCreatureShield(oldLeader); - member->sendPartyCreatureShield(leader); + member->sendPartyCreatureShield(player); } for (auto invitee : getInvitees()) { invitee->sendCreatureShield(oldLeader); - invitee->sendCreatureShield(leader); + invitee->sendCreatureShield(player); } - leader->sendPartyCreatureShield(oldLeader); - leader->sendPartyCreatureShield(leader); + player->sendPartyCreatureShield(oldLeader); + player->sendPartyCreatureShield(player); player->sendTextMessage(MESSAGE_PARTY_MANAGEMENT, "You are now the leader of the party."); return true; @@ -616,7 +616,7 @@ void Party::updatePlayerStatus(std::shared_ptr player) { return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); + int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (auto member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { @@ -639,7 +639,7 @@ void Party::updatePlayerStatus(std::shared_ptr player, const Position &o return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); + int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); if (maxDistance != 0) { for (auto member : getMembers()) { bool condition1 = (Position::getDistanceX(oldPos, member->getPosition()) <= maxDistance && Position::getDistanceY(oldPos, member->getPosition()) <= maxDistance); @@ -667,7 +667,7 @@ void Party::updatePlayerHealth(std::shared_ptr player, std::shared_ptrgetPosition(); auto leaderPosition = leader->getPosition(); for (auto member : getMembers()) { @@ -689,7 +689,7 @@ void Party::updatePlayerMana(std::shared_ptr player, uint8_t manaPercent return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); + int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (auto member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { @@ -708,7 +708,7 @@ void Party::updatePlayerVocation(std::shared_ptr player) { return; } - int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE); + int32_t maxDistance = g_configManager().getNumber(PARTY_LIST_MAX_DISTANCE, __FUNCTION__); for (auto member : getMembers()) { bool condition = (maxDistance == 0 || (Position::getDistanceX(player->getPosition(), member->getPosition()) <= maxDistance && Position::getDistanceY(player->getPosition(), member->getPosition()) <= maxDistance)); if (condition) { diff --git a/src/creatures/players/imbuements/imbuements.cpp b/src/creatures/players/imbuements/imbuements.cpp index 2d27d15bb..995ea3197 100644 --- a/src/creatures/players/imbuements/imbuements.cpp +++ b/src/creatures/players/imbuements/imbuements.cpp @@ -27,7 +27,7 @@ Imbuement* Imbuements::getImbuement(uint16_t id) { bool Imbuements::loadFromXml(bool /* reloading */) { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/imbuements.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/imbuements.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); @@ -346,7 +346,7 @@ std::vector Imbuements::getImbuements(std::shared_ptr player } // Parse the storages for each imbuement in imbuements.xml and config.lua (enable/disable storage) - if (g_configManager().getBoolean(TOGGLE_IMBUEMENT_SHRINE_STORAGE) + if (g_configManager().getBoolean(TOGGLE_IMBUEMENT_SHRINE_STORAGE, __FUNCTION__) && imbuement->getStorage() != 0 && player->getStorageValue(imbuement->getStorage() == -1) && imbuement->getBaseID() >= 1 && imbuement->getBaseID() <= 3) { diff --git a/src/creatures/players/management/waitlist.cpp b/src/creatures/players/management/waitlist.cpp index ff1ad2b00..38fd26e4b 100644 --- a/src/creatures/players/management/waitlist.cpp +++ b/src/creatures/players/management/waitlist.cpp @@ -64,7 +64,7 @@ bool WaitingList::clientLogin(std::shared_ptr player) { return true; } - auto maxPlayers = static_cast(g_configManager().getNumber(MAX_PLAYERS)); + auto maxPlayers = static_cast(g_configManager().getNumber(MAX_PLAYERS, __FUNCTION__)); if (maxPlayers == 0 || (info->priorityWaitList.empty() && info->waitList.empty() && g_game().getPlayersOnline() < maxPlayers)) { return true; } diff --git a/src/creatures/players/player.cpp b/src/creatures/players/player.cpp index f63d37999..0c68ec3a6 100644 --- a/src/creatures/players/player.cpp +++ b/src/creatures/players/player.cpp @@ -549,7 +549,7 @@ void Player::updateInventoryImbuement() { bool isInProtectionZone = playerTile && playerTile->hasFlag(TILESTATE_PROTECTIONZONE); // Check if the player is in fight mode bool isInFightMode = hasCondition(CONDITION_INFIGHT); - bool nonAggressiveFightOnly = g_configManager().getBoolean(TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY); + bool nonAggressiveFightOnly = g_configManager().getBoolean(TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY, __FUNCTION__); // Iterate through all items in the player's inventory for (auto [key, item] : getAllSlotItems()) { @@ -959,7 +959,7 @@ bool Player::canWalkthrough(std::shared_ptr creature) { if (player) { std::shared_ptr playerTile = player->getTile(); - if (!playerTile || (!playerTile->hasFlag(TILESTATE_NOPVPZONE) && !playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && player->getLevel() > static_cast(g_configManager().getNumber(PROTECTION_LEVEL)) && g_game().getWorldType() != WORLD_TYPE_NO_PVP)) { + if (!playerTile || (!playerTile->hasFlag(TILESTATE_NOPVPZONE) && !playerTile->hasFlag(TILESTATE_PROTECTIONZONE) && player->getLevel() > static_cast(g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__)) && g_game().getWorldType() != WORLD_TYPE_NO_PVP)) { return false; } @@ -1007,7 +1007,7 @@ bool Player::canWalkthroughEx(std::shared_ptr creature) { std::shared_ptr npc = creature->getNpc(); if (player) { std::shared_ptr playerTile = player->getTile(); - return playerTile && (playerTile->hasFlag(TILESTATE_NOPVPZONE) || playerTile->hasFlag(TILESTATE_PROTECTIONZONE) || player->getLevel() <= static_cast(g_configManager().getNumber(PROTECTION_LEVEL)) || g_game().getWorldType() == WORLD_TYPE_NO_PVP); + return playerTile && (playerTile->hasFlag(TILESTATE_NOPVPZONE) || playerTile->hasFlag(TILESTATE_PROTECTIONZONE) || player->getLevel() <= static_cast(g_configManager().getNumber(PROTECTION_LEVEL, __FUNCTION__)) || g_game().getWorldType() == WORLD_TYPE_NO_PVP); } else if (npc) { std::shared_ptr tile = npc->getTile(); std::shared_ptr houseTile = std::dynamic_pointer_cast(tile); @@ -1162,7 +1162,7 @@ std::shared_ptr Player::getDepotLocker(uint32_t depotId) { auto it = depotLockerMap.find(depotId); if (it != depotLockerMap.end()) { inbox->setParent(it->second); - for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES); i > 0; i--) { + for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__); i > 0; i--) { if (std::shared_ptr depotBox = getDepotChest(i, false)) { depotBox->setParent(it->second->getItemByIndex(0)->getContainer()); } @@ -1180,8 +1180,8 @@ std::shared_ptr Player::getDepotLocker(uint32_t depotId) { if (createSupplyStash) { depotLocker->internalAddThing(Item::CreateItem(ITEM_SUPPLY_STASH)); } - std::shared_ptr depotChest = Item::CreateItemAsContainer(ITEM_DEPOT, static_cast(g_configManager().getNumber(DEPOT_BOXES))); - for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES); i > 0; i--) { + std::shared_ptr depotChest = Item::CreateItemAsContainer(ITEM_DEPOT, static_cast(g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__))); + for (uint32_t i = g_configManager().getNumber(DEPOT_BOXES, __FUNCTION__); i > 0; i--) { std::shared_ptr depotBox = getDepotChest(i, true); depotChest->internalAddThing(depotBox); depotBox->setParent(depotChest); @@ -1474,7 +1474,7 @@ void Player::openImbuementWindow(std::shared_ptr item) { void Player::sendSaleItemList(const std::map &inventoryMap) const { if (client && shopOwner) { - client->sendSaleItemList(shopOwner->getShopItemVector(), inventoryMap); + client->sendSaleItemList(shopOwner->getShopItemVector(getGUID()), inventoryMap); } } @@ -1652,7 +1652,7 @@ void Player::onCreatureAppear(std::shared_ptr creature, bool isLogin) g_game().checkPlayersRecord(); IOLoginData::updateOnlineStatus(guid, true); - if (getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL) && getVocationId() > VOCATION_NONE) { + if (getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL, __FUNCTION__) && getVocationId() > VOCATION_NONE) { for (uint8_t i = 2; i <= 6; i++) { if (!hasBlessing(i)) { addBlessing(i, 1); @@ -1686,7 +1686,7 @@ void Player::onChangeZone(ZoneType_t zone) { onAttackedCreatureDisappear(false); } - if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ) && !group->access && isMounted()) { + if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ, __FUNCTION__) && !group->access && isMounted()) { dismount(); g_game().internalCreatureChangeOutfit(getPlayer(), defaultOutfit); wasMounted = true; @@ -1781,7 +1781,6 @@ bool Player::openShopWindow(std::shared_ptr npc) { } setShopOwner(npc); - npc->addShopPlayer(static_self_cast()); sendShop(npc); std::map inventoryMap; @@ -1871,7 +1870,7 @@ void Player::onCreatureMove(const std::shared_ptr &creature, const std } if (teleport || oldPos.z != newPos.z) { - int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY); + int32_t ticks = g_configManager().getNumber(STAIRHOP_DELAY, __FUNCTION__); if (ticks > 0) { if (const auto &condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_PACIFIED, ticks, 0)) { addCondition(condition); @@ -2008,7 +2007,7 @@ void Player::setNextActionTask(std::shared_ptr task, bool resetIdleTime /* actionTaskEvent = 0; } - if (!inEventMovePush && !g_configManager().getBoolean(PUSH_WHEN_ATTACKING)) { + if (!inEventMovePush && !g_configManager().getBoolean(PUSH_WHEN_ATTACKING, __FUNCTION__)) { cancelPush(); } @@ -2075,10 +2074,10 @@ void Player::onThink(uint32_t interval) { // Momentum (cooldown resets) triggerMomentum(); auto playerTile = getTile(); - const bool vipStaysOnline = isVip() && g_configManager().getBoolean(VIP_STAY_ONLINE); + const bool vipStaysOnline = isVip() && g_configManager().getBoolean(VIP_STAY_ONLINE, __FUNCTION__); if (playerTile && !playerTile->hasFlag(TILESTATE_NOLOGOUT) && !isAccessPlayer() && !isExerciseTraining() && !vipStaysOnline) { idleTime += interval; - const int32_t kickAfterMinutes = g_configManager().getNumber(KICK_AFTER_MINUTES); + const int32_t kickAfterMinutes = g_configManager().getNumber(KICK_AFTER_MINUTES, __FUNCTION__); if (idleTime > (kickAfterMinutes * 60000) + 60000) { removePlayer(true); } else if (client && idleTime == 60000 * kickAfterMinutes) { @@ -2116,7 +2115,7 @@ uint32_t Player::isMuted() const { } void Player::addMessageBuffer() { - if (MessageBufferCount > 0 && g_configManager().getNumber(MAX_MESSAGEBUFFER) != 0 && !hasFlag(PlayerFlags_t::CannotBeMuted)) { + if (MessageBufferCount > 0 && g_configManager().getNumber(MAX_MESSAGEBUFFER, __FUNCTION__) != 0 && !hasFlag(PlayerFlags_t::CannotBeMuted)) { --MessageBufferCount; } } @@ -2126,7 +2125,7 @@ void Player::removeMessageBuffer() { return; } - const int32_t maxMessageBuffer = g_configManager().getNumber(MAX_MESSAGEBUFFER); + const int32_t maxMessageBuffer = g_configManager().getNumber(MAX_MESSAGEBUFFER, __FUNCTION__); if (maxMessageBuffer != 0 && MessageBufferCount <= maxMessageBuffer + 1) { if (++MessageBufferCount > maxMessageBuffer) { uint32_t muteCount = 1; @@ -2241,7 +2240,7 @@ void Player::addExperience(std::shared_ptr target, uint64_t exp, bool std::shared_ptr monster = target && target->getMonster() ? target->getMonster() : nullptr; bool handleHazardExperience = monster && monster->getHazard() && getHazardSystemPoints() > 0; if (handleHazardExperience) { - exp += (exp * (1.75 * getHazardSystemPoints() * g_configManager().getNumber(HAZARD_EXP_BONUS_MULTIPLIER))) / 100.; + exp += (exp * (1.75 * getHazardSystemPoints() * g_configManager().getNumber(HAZARD_EXP_BONUS_MULTIPLIER, __FUNCTION__))) / 100.; } experience += exp; @@ -2249,7 +2248,7 @@ void Player::addExperience(std::shared_ptr target, uint64_t exp, bool if (sendText) { std::string expString = fmt::format("{} experience point{}.", exp, (exp != 1 ? "s" : "")); if (isVip()) { - uint8_t expPercent = g_configManager().getNumber(VIP_BONUS_EXP); + uint8_t expPercent = g_configManager().getNumber(VIP_BONUS_EXP, __FUNCTION__); if (expPercent > 0) { expString = expString + fmt::format(" (VIP bonus {}%)", expPercent > 100 ? 100 : expPercent); } @@ -2882,7 +2881,7 @@ void Player::addInFightTicks(bool pzlock /*= false*/) { updateImbuementTrackerStats(); - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(PZ_LOCKED), 0); + std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(PZ_LOCKED, __FUNCTION__), 0); addCondition(condition); } @@ -3625,7 +3624,7 @@ void Player::stashContainer(StashContainerList itemDict) { } } - if (getStashSize(stashItemDict) > g_configManager().getNumber(STASH_ITEMS)) { + if (getStashSize(stashItemDict) > g_configManager().getNumber(STASH_ITEMS, __FUNCTION__)) { sendCancelMessage("You don't have capacity in the Supply Stash to stow all this item->"); return; } @@ -4130,7 +4129,7 @@ bool Player::hasShopItemForSale(uint16_t itemId, uint8_t subType) const { } const ItemType &itemType = Item::items[itemId]; - std::vector shoplist = shopOwner->getShopItemVector(); + std::vector shoplist = shopOwner->getShopItemVector(getGUID()); return std::any_of(shoplist.begin(), shoplist.end(), [&](const ShopBlock &shopBlock) { return shopBlock.itemId == itemId && shopBlock.itemBuyPrice != 0 && (!itemType.isFluidContainer() || shopBlock.itemSubType == subType); }); @@ -4234,7 +4233,7 @@ void Player::doAttacking(uint32_t) { std::shared_ptr tool = getWeapon(); const WeaponShared_ptr weapon = g_weapons().getWeapon(tool); uint32_t delay = getAttackSpeed(); - bool classicSpeed = g_configManager().getBoolean(CLASSIC_ATTACK_SPEED); + bool classicSpeed = g_configManager().getBoolean(CLASSIC_ATTACK_SPEED, __FUNCTION__); if (weapon) { if (!weapon->interruptSwing()) { @@ -4264,9 +4263,9 @@ void Player::doAttacking(uint32_t) { } uint64_t Player::getGainedExperience(std::shared_ptr attacker) const { - if (g_configManager().getBoolean(EXPERIENCE_FROM_PLAYERS)) { + if (g_configManager().getBoolean(EXPERIENCE_FROM_PLAYERS, __FUNCTION__)) { auto attackerPlayer = attacker->getPlayer(); - if (attackerPlayer && attackerPlayer.get() != this && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_configManager().getNumber(EXP_FROM_PLAYERS_LEVEL_RANGE)) { + if (attackerPlayer && attackerPlayer.get() != this && skillLoss && std::abs(static_cast(attackerPlayer->getLevel() - level)) <= g_configManager().getNumber(EXP_FROM_PLAYERS_LEVEL_RANGE, __FUNCTION__)) { return std::max(0, std::floor(getLostExperience() * getDamageRatio(attacker) * 0.75)); } } @@ -4592,7 +4591,7 @@ bool Player::onKilledPlayer(const std::shared_ptr &target, bool lastHit) if (lastHit && hasCondition(CONDITION_INFIGHT)) { pzLocked = true; - std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(WHITE_SKULL_TIME), 0); + std::shared_ptr condition = Condition::createCondition(CONDITIONID_DEFAULT, CONDITION_INFIGHT, g_configManager().getNumber(WHITE_SKULL_TIME, __FUNCTION__), 0); addCondition(condition); } } @@ -4621,7 +4620,7 @@ void Player::addBestiaryKill(const std::shared_ptr &mType) { if (mType->isBoss()) { return; } - uint32_t kills = g_configManager().getNumber(BESTIARY_KILL_MULTIPLIER); + uint32_t kills = g_configManager().getNumber(BESTIARY_KILL_MULTIPLIER, __FUNCTION__); if (isConcoctionActive(Concoction_t::BestiaryBetterment)) { kills *= 2; } @@ -4632,9 +4631,9 @@ void Player::addBosstiaryKill(const std::shared_ptr &mType) { if (!mType->isBoss()) { return; } - uint32_t kills = g_configManager().getNumber(BOSSTIARY_KILL_MULTIPLIER); + uint32_t kills = g_configManager().getNumber(BOSSTIARY_KILL_MULTIPLIER, __FUNCTION__); if (g_ioBosstiary().getBoostedBossId() == mType->info.raceid) { - kills *= g_configManager().getNumber(BOOSTED_BOSS_KILL_BONUS); + kills *= g_configManager().getNumber(BOOSTED_BOSS_KILL_BONUS, __FUNCTION__); } g_ioBosstiary().addBosstiaryKill(getPlayer(), mType, kills); } @@ -4727,7 +4726,7 @@ void Player::changeMana(int32_t manaChange) { void Player::changeSoul(int32_t soulChange) { if (soulChange > 0) { - soul += std::min(soulChange * g_configManager().getFloat(RATE_SOUL_REGEN), vocation->getSoulMax() - soul); + soul += std::min(soulChange * g_configManager().getFloat(RATE_SOUL_REGEN, __FUNCTION__), vocation->getSoulMax() - soul); } else { soul = std::max(0, soul + soulChange); } @@ -4736,7 +4735,7 @@ void Player::changeSoul(int32_t soulChange) { } bool Player::canWear(uint16_t lookType, uint8_t addons) const { - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && lookType != 0 && !g_game().isLookTypeRegistered(lookType)) { g_logger().warn("[Player::canWear] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", lookType); return false; } @@ -4953,7 +4952,7 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { if (player && player->getSkull() == SKULL_NONE) { if (player.get() == this) { for (const auto &kill : unjustifiedKills) { - if (kill.unavenged && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION) * 24 * 60 * 60) { + if (kill.unavenged && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, __FUNCTION__) * 24 * 60 * 60) { return SKULL_ORANGE; } } @@ -4976,7 +4975,7 @@ Skulls_t Player::getSkullClient(std::shared_ptr creature) { bool Player::hasKilled(std::shared_ptr player) const { for (const auto &kill : unjustifiedKills) { - if (kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION) * 24 * 60 * 60 && kill.unavenged) { + if (kill.target == player->getGUID() && (time(nullptr) - kill.time) < g_configManager().getNumber(ORANGE_SKULL_DURATION, __FUNCTION__) * 24 * 60 * 60 && kill.unavenged) { return true; } } @@ -5042,14 +5041,14 @@ void Player::addUnjustifiedDead(std::shared_ptr attacked) { } if (getSkull() != SKULL_BLACK) { - if (dayKills >= 2 * g_configManager().getNumber(DAY_KILLS_TO_RED) || weekKills >= 2 * g_configManager().getNumber(WEEK_KILLS_TO_RED) || monthKills >= 2 * g_configManager().getNumber(MONTH_KILLS_TO_RED)) { + if (dayKills >= 2 * g_configManager().getNumber(DAY_KILLS_TO_RED, __FUNCTION__) || weekKills >= 2 * g_configManager().getNumber(WEEK_KILLS_TO_RED, __FUNCTION__) || monthKills >= 2 * g_configManager().getNumber(MONTH_KILLS_TO_RED, __FUNCTION__)) { setSkull(SKULL_BLACK); // start black skull time - skullTicks = static_cast(g_configManager().getNumber(BLACK_SKULL_DURATION)) * 24 * 60 * 60; - } else if (dayKills >= g_configManager().getNumber(DAY_KILLS_TO_RED) || weekKills >= g_configManager().getNumber(WEEK_KILLS_TO_RED) || monthKills >= g_configManager().getNumber(MONTH_KILLS_TO_RED)) { + skullTicks = static_cast(g_configManager().getNumber(BLACK_SKULL_DURATION, __FUNCTION__)) * 24 * 60 * 60; + } else if (dayKills >= g_configManager().getNumber(DAY_KILLS_TO_RED, __FUNCTION__) || weekKills >= g_configManager().getNumber(WEEK_KILLS_TO_RED, __FUNCTION__) || monthKills >= g_configManager().getNumber(MONTH_KILLS_TO_RED, __FUNCTION__)) { setSkull(SKULL_RED); // reset red skull time - skullTicks = static_cast(g_configManager().getNumber(RED_SKULL_DURATION)) * 24 * 60 * 60; + skullTicks = static_cast(g_configManager().getNumber(RED_SKULL_DURATION, __FUNCTION__)) * 24 * 60 * 60; } } @@ -5083,7 +5082,7 @@ double Player::getLostPercent() const { } } - int32_t deathLosePercent = g_configManager().getNumber(DEATH_LOSE_PERCENT); + int32_t deathLosePercent = g_configManager().getNumber(DEATH_LOSE_PERCENT, __FUNCTION__); if (deathLosePercent != -1) { if (isPromoted()) { deathLosePercent -= 3; @@ -5246,7 +5245,7 @@ uint16_t Player::getSkillLevel(skills_t skill) const { } bool Player::isPremium() const { - if (g_configManager().getBoolean(FREE_PREMIUM) || hasFlag(PlayerFlags_t::IsAlwaysPremium)) { + if (g_configManager().getBoolean(FREE_PREMIUM, __FUNCTION__) || hasFlag(PlayerFlags_t::IsAlwaysPremium)) { return true; } @@ -5563,9 +5562,9 @@ void Player::sendUnjustifiedPoints() { bool isRed = getSkull() == SKULL_RED; - auto dayMax = ((isRed ? 2 : 1) * g_configManager().getNumber(DAY_KILLS_TO_RED)); - auto weekMax = ((isRed ? 2 : 1) * g_configManager().getNumber(WEEK_KILLS_TO_RED)); - auto monthMax = ((isRed ? 2 : 1) * g_configManager().getNumber(MONTH_KILLS_TO_RED)); + auto dayMax = ((isRed ? 2 : 1) * g_configManager().getNumber(DAY_KILLS_TO_RED, __FUNCTION__)); + auto weekMax = ((isRed ? 2 : 1) * g_configManager().getNumber(WEEK_KILLS_TO_RED, __FUNCTION__)); + auto monthMax = ((isRed ? 2 : 1) * g_configManager().getNumber(MONTH_KILLS_TO_RED, __FUNCTION__)); uint8_t dayProgress = std::min(std::round(dayKills / dayMax * 100), 100.0); uint8_t weekProgress = std::min(std::round(weekKills / weekMax * 100), 100.0); @@ -5626,7 +5625,7 @@ bool Player::toggleMount(bool mount) { } auto tile = getTile(); - if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ) && !group->access && tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { + if (!g_configManager().getBoolean(TOGGLE_MOUNT_IN_PZ, __FUNCTION__) && !group->access && tile && tile->hasFlag(TILESTATE_PROTECTIONZONE)) { sendCancelMessage(RETURNVALUE_ACTIONNOTPERMITTEDINPROTECTIONZONE); return false; } @@ -6038,9 +6037,9 @@ size_t Player::getMaxDepotItems() const { if (group->maxDepotItems != 0) { return group->maxDepotItems; } else if (isPremium()) { - return g_configManager().getNumber(PREMIUM_DEPOT_LIMIT); + return g_configManager().getNumber(PREMIUM_DEPOT_LIMIT, __FUNCTION__); } - return g_configManager().getNumber(FREE_DEPOT_LIMIT); + return g_configManager().getNumber(FREE_DEPOT_LIMIT, __FUNCTION__); } std::forward_list> Player::getMuteConditions() const { @@ -6296,9 +6295,9 @@ void Player::stowItem(std::shared_ptr item, uint32_t count, bool allItems) } else if (item->getContainer()) { itemDict = item->getContainer()->getStowableItems(); for (std::shared_ptr containerItem : item->getContainer()->getItems(true)) { - uint32_t depotChest = g_configManager().getNumber(DEPOTCHEST); + uint32_t depotChest = g_configManager().getNumber(DEPOTCHEST, __FUNCTION__); bool validDepot = depotChest > 0 && depotChest < 21; - if (g_configManager().getBoolean(STASH_MOVING) && containerItem && !containerItem->isStackable() && validDepot) { + if (g_configManager().getBoolean(STASH_MOVING, __FUNCTION__) && containerItem && !containerItem->isStackable() && validDepot) { g_game().internalMoveItem(containerItem->getParent(), getDepotChest(depotChest, true), INDEX_WHEREEVER, containerItem, containerItem->getItemCount(), nullptr); movedItems++; moved = true; @@ -6357,9 +6356,9 @@ void Player::initializePrey() { if (preys.empty()) { for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { auto slot = std::make_unique(static_cast(slotId)); - if (!g_configManager().getBoolean(PREY_ENABLED)) { + if (!g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { slot->state = PreyDataState_Inactive; - } else if (slot->id == PreySlot_Three && !g_configManager().getBoolean(PREY_FREE_THIRD_SLOT)) { + } else if (slot->id == PreySlot_Three && !g_configManager().getBoolean(PREY_FREE_THIRD_SLOT, __FUNCTION__)) { slot->state = PreyDataState_Locked; } else if (slot->id == PreySlot_Two && !isPremium()) { slot->state = PreyDataState_Locked; @@ -6385,9 +6384,9 @@ void Player::initializeTaskHunting() { if (taskHunting.empty()) { for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { auto slot = std::make_unique(static_cast(slotId)); - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { slot->state = PreyTaskDataState_Inactive; - } else if (slot->id == PreySlot_Three && !g_configManager().getBoolean(TASK_HUNTING_FREE_THIRD_SLOT)) { + } else if (slot->id == PreySlot_Three && !g_configManager().getBoolean(TASK_HUNTING_FREE_THIRD_SLOT, __FUNCTION__)) { slot->state = PreyTaskDataState_Locked; } else if (slot->id == PreySlot_Two && !isPremium()) { slot->state = PreyTaskDataState_Locked; @@ -6400,7 +6399,7 @@ void Player::initializeTaskHunting() { } } - if (client && g_configManager().getBoolean(TASK_HUNTING_ENABLED) && !client->oldProtocol) { + if (client && g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__) && !client->oldProtocol) { client->writeToOutputBuffer(g_ioprey().getTaskHuntingBaseDate()); } } @@ -6820,7 +6819,9 @@ bool Player::saySpell( // Send to client for (std::shared_ptr spectator : spectators) { if (std::shared_ptr tmpPlayer = spectator->getPlayer()) { - valueEmote = tmpPlayer->getStorageValue(STORAGEVALUE_EMOTE); + if (g_configManager().getBoolean(EMOTE_SPELLS, __FUNCTION__)) { + valueEmote = tmpPlayer->getStorageValue(STORAGEVALUE_EMOTE); + } if (!ghostMode || tmpPlayer->canSeeCreature(static_self_cast())) { if (valueEmote == 1) { tmpPlayer->sendCreatureSay(static_self_cast(), TALKTYPE_MONSTER_SAY, text, pos); @@ -6926,7 +6927,7 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re return; } - auto dustCost = static_cast(g_configManager().getNumber(FORGE_FUSION_DUST_COST)); + auto dustCost = static_cast(g_configManager().getNumber(FORGE_FUSION_DUST_COST, __FUNCTION__)); if (success) { firstForgedItem->setTier(tier + 1); @@ -6985,7 +6986,7 @@ void Player::forgeFuseItems(uint16_t itemId, uint8_t tier, bool success, bool re } } } else { - auto isTierLost = uniform_random(1, 100) <= (reduceTierLoss ? g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION) : 100); + auto isTierLost = uniform_random(1, 100) <= (reduceTierLoss ? g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION, __FUNCTION__) : 100); if (isTierLost) { if (secondForgedItem->getTier() >= 1) { secondForgedItem->setTier(tier - 1); @@ -7130,12 +7131,12 @@ void Player::forgeTransferItemTier(uint16_t donorItemId, uint8_t tier, uint16_t return; } - if (getForgeDusts() < g_configManager().getNumber(FORGE_TRANSFER_DUST_COST)) { + if (getForgeDusts() < g_configManager().getNumber(FORGE_TRANSFER_DUST_COST, __FUNCTION__)) { g_logger().error("[Log 8] Failed to remove transfer dusts from player with name {}", getName()); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } else { - setForgeDusts(getForgeDusts() - g_configManager().getNumber(FORGE_TRANSFER_DUST_COST)); + setForgeDusts(getForgeDusts() - g_configManager().getNumber(FORGE_TRANSFER_DUST_COST, __FUNCTION__)); } uint8_t coresAmount = 0; @@ -7192,14 +7193,14 @@ void Player::forgeResourceConversion(uint8_t action) { ReturnValue returnValue = RETURNVALUE_NOERROR; if (actionEnum == ForgeConversion_t::FORGE_ACTION_DUSTTOSLIVERS) { auto dusts = getForgeDusts(); - auto cost = static_cast(g_configManager().getNumber(FORGE_COST_ONE_SLIVER) * g_configManager().getNumber(FORGE_SLIVER_AMOUNT)); + auto cost = static_cast(g_configManager().getNumber(FORGE_COST_ONE_SLIVER, __FUNCTION__) * g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); if (cost > dusts) { g_logger().error("[{}] Not enough dust", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; } - auto itemCount = static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT)); + auto itemCount = static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__)); std::shared_ptr item = Item::CreateItem(ITEM_FORGE_SLIVER, itemCount); returnValue = g_game().internalPlayerAddItem(static_self_cast(), item); if (returnValue != RETURNVALUE_NOERROR) { @@ -7213,7 +7214,7 @@ void Player::forgeResourceConversion(uint8_t action) { setForgeDusts(dusts - cost); } else if (actionEnum == ForgeConversion_t::FORGE_ACTION_SLIVERSTOCORES) { auto [sliverCount, coreCount] = getForgeSliversAndCores(); - auto cost = static_cast(g_configManager().getNumber(FORGE_CORE_COST)); + auto cost = static_cast(g_configManager().getNumber(FORGE_CORE_COST, __FUNCTION__)); if (cost > sliverCount) { g_logger().error("[{}] Not enough sliver", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); @@ -7241,7 +7242,7 @@ void Player::forgeResourceConversion(uint8_t action) { history.gained = 1; } else { auto dustLevel = getForgeDustLevel(); - if (dustLevel >= g_configManager().getNumber(FORGE_MAX_DUST)) { + if (dustLevel >= g_configManager().getNumber(FORGE_MAX_DUST, __FUNCTION__)) { g_logger().error("[{}] Maximum level reached", __FUNCTION__); sendForgeError(RETURNVALUE_CONTACTADMINISTRATOR); return; @@ -7551,7 +7552,7 @@ bool Player::canAutoWalk(const Position &toPosition, const std::function ******************************************************************************/ void Player::setHazardSystemPoints(int32_t count) { - if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM)) { + if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM, __FUNCTION__)) { return; } addStorageValue(STORAGEVALUE_HAZARDCOUNT, std::max(0, std::min(0xFFFF, count)), true); @@ -7568,7 +7569,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptr(normal_random(1, 10000)); - auto critChance = g_configManager().getNumber(HAZARD_CRITICAL_CHANCE); + auto critChance = g_configManager().getNumber(HAZARD_CRITICAL_CHANCE, __FUNCTION__); // Critical chance - if (monster->getHazardSystemCrit() && (lastHazardSystemCriticalHit + g_configManager().getNumber(HAZARD_CRITICAL_INTERVAL)) <= OTSYS_TIME() && chance <= critChance && !damage.critical) { + if (monster->getHazardSystemCrit() && (lastHazardSystemCriticalHit + g_configManager().getNumber(HAZARD_CRITICAL_INTERVAL, __FUNCTION__)) <= OTSYS_TIME() && chance <= critChance && !damage.critical) { damage.critical = true; damage.extension = true; damage.exString = "(Hazard)"; - stage = (points - 1) * static_cast(g_configManager().getNumber(HAZARD_CRITICAL_MULTIPLIER)); + stage = (points - 1) * static_cast(g_configManager().getNumber(HAZARD_CRITICAL_MULTIPLIER, __FUNCTION__)); damage.primary.value += static_cast(std::ceil((static_cast(damage.primary.value) * (5000 + stage)) / 10000)); damage.secondary.value += static_cast(std::ceil((static_cast(damage.secondary.value) * (5000 + stage)) / 10000)); lastHazardSystemCriticalHit = OTSYS_TIME(); @@ -7610,7 +7611,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptrgetHazardSystemDamageBoost() /* && !damage.critical*/) { - stage = points * static_cast(g_configManager().getNumber(HAZARD_DAMAGE_MULTIPLIER)); + stage = points * static_cast(g_configManager().getNumber(HAZARD_DAMAGE_MULTIPLIER, __FUNCTION__)); if (stage != 0) { damage.extension = true; damage.exString = "(Hazard)"; @@ -7623,7 +7624,7 @@ void Player::parseAttackRecvHazardSystem(CombatDamage &damage, std::shared_ptr monster) { - if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM)) { + if (!g_configManager().getBoolean(TOGGLE_HAZARDSYSTEM, __FUNCTION__)) { return; } @@ -7655,7 +7656,7 @@ void Player::parseAttackDealtHazardSystem(CombatDamage &damage, std::shared_ptr< // Dodge chance uint16_t stage; if (monster->getHazardSystemDodge()) { - stage = points * g_configManager().getNumber(HAZARD_DODGE_MULTIPLIER); + stage = points * g_configManager().getNumber(HAZARD_DODGE_MULTIPLIER, __FUNCTION__); auto chance = static_cast(normal_random(1, 10000)); if (chance <= stage) { damage.primary.value = 0; diff --git a/src/creatures/players/player.hpp b/src/creatures/players/player.hpp index 9757717e6..9f6c01252 100644 --- a/src/creatures/players/player.hpp +++ b/src/creatures/players/player.hpp @@ -612,7 +612,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } bool isVip() const { - return g_configManager().getBoolean(VIP_SYSTEM_ENABLED) && getPremiumDays() > 0; + return g_configManager().getBoolean(VIP_SYSTEM_ENABLED, __FUNCTION__) && getPremiumDays() > 0; } void setTibiaCoins(int32_t v); @@ -2088,13 +2088,13 @@ class Player final : public Creature, public Cylinder, public Bankable { } void sendPreyTimeLeft(const std::unique_ptr &slot) const { - if (g_configManager().getBoolean(PREY_ENABLED) && client) { + if (g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__) && client) { client->sendPreyTimeLeft(slot); } } void reloadPreySlot(PreySlot_t slotid) { - if (g_configManager().getBoolean(PREY_ENABLED) && client) { + if (g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__) && client) { client->sendPreyData(getPreySlotById(slotid)); client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints()); } @@ -2144,7 +2144,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } uint32_t getPreyRerollPrice() const { - return getLevel() * g_configManager().getNumber(PREY_REROLL_PRICE_LEVEL); + return getLevel() * g_configManager().getNumber(PREY_REROLL_PRICE_LEVEL, __FUNCTION__); } std::vector getPreyBlackList() const { @@ -2164,7 +2164,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } const std::unique_ptr &getPreyWithMonster(uint16_t raceId) const { - if (!g_configManager().getBoolean(PREY_ENABLED)) { + if (!g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { return PreySlotNull; } @@ -2192,7 +2192,7 @@ class Player final : public Creature, public Cylinder, public Bankable { } void reloadTaskSlot(PreySlot_t slotid) { - if (g_configManager().getBoolean(TASK_HUNTING_ENABLED) && client) { + if (g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__) && client) { client->sendTaskHuntingData(getTaskHuntingSlotById(slotid)); client->sendResourcesBalance(getMoney(), getBankBalance(), getPreyCards(), getTaskHuntingPoints()); } @@ -2260,11 +2260,11 @@ class Player final : public Creature, public Cylinder, public Bankable { } uint32_t getTaskHuntingRerollPrice() const { - return getLevel() * g_configManager().getNumber(TASK_HUNTING_REROLL_PRICE_LEVEL); + return getLevel() * g_configManager().getNumber(TASK_HUNTING_REROLL_PRICE_LEVEL, __FUNCTION__); } const std::unique_ptr &getTaskHuntingWithCreature(uint16_t raceId) const { - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return TaskHuntingSlotNull; } @@ -2517,8 +2517,8 @@ class Player final : public Creature, public Cylinder, public Bankable { } bool checkAutoLoot() const { - const bool autoLoot = g_configManager().getBoolean(AUTOLOOT) && getStorageValue(STORAGEVALUE_AUTO_LOOT) > 0; - if (g_configManager().getBoolean(VIP_SYSTEM_ENABLED) && g_configManager().getBoolean(VIP_AUTOLOOT_VIP_ONLY)) { + const bool autoLoot = g_configManager().getBoolean(AUTOLOOT, __FUNCTION__) && getStorageValue(STORAGEVALUE_AUTO_LOOT) > 0; + if (g_configManager().getBoolean(VIP_SYSTEM_ENABLED, __FUNCTION__) && g_configManager().getBoolean(VIP_AUTOLOOT_VIP_ONLY, __FUNCTION__)) { return autoLoot && isVip(); } return autoLoot; @@ -2636,7 +2636,7 @@ class Player final : public Creature, public Cylinder, public Bankable { std::map maxValuePerSkill = { { SKILL_LIFE_LEECH_CHANCE, 100 }, { SKILL_MANA_LEECH_CHANCE, 100 }, - { SKILL_CRITICAL_HIT_CHANCE, g_configManager().getNumber(CRITICALCHANCE) } + { SKILL_CRITICAL_HIT_CHANCE, g_configManager().getNumber(CRITICALCHANCE, "std::map::maxValuePerSkill") } }; std::map> rewardMap; @@ -2873,14 +2873,14 @@ class Player final : public Creature, public Cylinder, public Bankable { bool isPromoted() const; - bool onFistAttackSpeed = g_configManager().getBoolean(TOGGLE_ATTACK_SPEED_ONFIST); - uint32_t MAX_ATTACK_SPEED = g_configManager().getNumber(MAX_SPEED_ATTACKONFIST); + bool onFistAttackSpeed = g_configManager().getBoolean(TOGGLE_ATTACK_SPEED_ONFIST, "Player.hpp::onFistAttackSpeed"); + uint32_t MAX_ATTACK_SPEED = g_configManager().getNumber(MAX_SPEED_ATTACKONFIST, "Player.hpp::MAX_ATTACK_SPEED"); uint32_t getAttackSpeed() const { if (onFistAttackSpeed) { uint32_t baseAttackSpeed = vocation->getAttackSpeed(); uint32_t skillLevel = getSkillLevel(SKILL_FIST); - uint32_t attackSpeed = baseAttackSpeed - (skillLevel * g_configManager().getNumber(MULTIPLIER_ATTACKONFIST)); + uint32_t attackSpeed = baseAttackSpeed - (skillLevel * g_configManager().getNumber(MULTIPLIER_ATTACKONFIST, __FUNCTION__)); if (attackSpeed < MAX_ATTACK_SPEED) { attackSpeed = MAX_ATTACK_SPEED; diff --git a/src/creatures/players/storages/storages.cpp b/src/creatures/players/storages/storages.cpp index 59ceb6aa8..8476fa978 100644 --- a/src/creatures/players/storages/storages.cpp +++ b/src/creatures/players/storages/storages.cpp @@ -15,7 +15,7 @@ bool Storages::loadFromXML() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/storages.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/storages.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { diff --git a/src/creatures/players/vocations/vocation.cpp b/src/creatures/players/vocations/vocation.cpp index 9c4fb9577..a27413b61 100644 --- a/src/creatures/players/vocations/vocation.cpp +++ b/src/creatures/players/vocations/vocation.cpp @@ -16,7 +16,7 @@ bool Vocations::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/vocations.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/vocations.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); diff --git a/src/creatures/players/vocations/vocation.hpp b/src/creatures/players/vocations/vocation.hpp index de9018afb..45f5d29d3 100644 --- a/src/creatures/players/vocations/vocation.hpp +++ b/src/creatures/players/vocations/vocation.hpp @@ -52,19 +52,19 @@ class Vocation { } uint32_t getManaGainTicks() const { - return gainManaTicks / g_configManager().getFloat(RATE_MANA_REGEN_SPEED); + return gainManaTicks / g_configManager().getFloat(RATE_MANA_REGEN_SPEED, __FUNCTION__); } uint32_t getManaGainAmount() const { - return gainManaAmount * g_configManager().getFloat(RATE_MANA_REGEN); + return gainManaAmount * g_configManager().getFloat(RATE_MANA_REGEN, __FUNCTION__); } uint32_t getHealthGainTicks() const { - return gainHealthTicks / g_configManager().getFloat(RATE_HEALTH_REGEN_SPEED); + return gainHealthTicks / g_configManager().getFloat(RATE_HEALTH_REGEN_SPEED, __FUNCTION__); } uint32_t getHealthGainAmount() const { - return gainHealthAmount * g_configManager().getFloat(RATE_HEALTH_REGEN); + return gainHealthAmount * g_configManager().getFloat(RATE_HEALTH_REGEN, __FUNCTION__); } uint8_t getSoulMax() const { @@ -72,7 +72,7 @@ class Vocation { } uint32_t getSoulGainTicks() const { - return gainSoulTicks / g_configManager().getFloat(RATE_SOUL_REGEN_SPEED); + return gainSoulTicks / g_configManager().getFloat(RATE_SOUL_REGEN_SPEED, __FUNCTION__); } uint32_t getBaseAttackSpeed() const { @@ -80,7 +80,7 @@ class Vocation { } uint32_t getAttackSpeed() const { - return attackSpeed / g_configManager().getFloat(RATE_ATTACK_SPEED); + return attackSpeed / g_configManager().getFloat(RATE_ATTACK_SPEED, __FUNCTION__); } uint32_t getBaseSpeed() const { diff --git a/src/creatures/players/wheel/player_wheel.cpp b/src/creatures/players/wheel/player_wheel.cpp index ad65a95ec..cf07955af 100644 --- a/src/creatures/players/wheel/player_wheel.cpp +++ b/src/creatures/players/wheel/player_wheel.cpp @@ -87,7 +87,7 @@ namespace { PlayerWheel::PlayerWheel(Player &initPlayer) : m_player(initPlayer) { - auto pointsPerLevel = (uint16_t)g_configManager().getNumber(WHEEL_POINTS_PER_LEVEL); + auto pointsPerLevel = (uint16_t)g_configManager().getNumber(WHEEL_POINTS_PER_LEVEL, __FUNCTION__); m_pointsPerLevel = pointsPerLevel > 0 ? pointsPerLevel : 1; } @@ -2173,7 +2173,6 @@ void PlayerWheel::downgradeSpell(const std::string &name) { std::shared_ptr PlayerWheel::getCombatDataSpell(CombatDamage &damage) { std::shared_ptr spell = nullptr; - damage.damageMultiplier += getMajorStatConditional("Divine Empowerment", WheelMajor_t::DAMAGE); WheelSpellGrade_t spellGrade = WheelSpellGrade_t::NONE; if (!(damage.instantSpellName).empty()) { spellGrade = getSpellUpgrade(damage.instantSpellName); diff --git a/src/database/database.cpp b/src/database/database.cpp index 4f6eaf918..a097c9f9b 100644 --- a/src/database/database.cpp +++ b/src/database/database.cpp @@ -24,7 +24,7 @@ Database &Database::getInstance() { } bool Database::connect() { - return connect(&g_configManager().getString(MYSQL_HOST), &g_configManager().getString(MYSQL_USER), &g_configManager().getString(MYSQL_PASS), &g_configManager().getString(MYSQL_DB), g_configManager().getNumber(SQL_PORT), &g_configManager().getString(MYSQL_SOCK)); + return connect(&g_configManager().getString(MYSQL_HOST, __FUNCTION__), &g_configManager().getString(MYSQL_USER, __FUNCTION__), &g_configManager().getString(MYSQL_PASS, __FUNCTION__), &g_configManager().getString(MYSQL_DB, __FUNCTION__), g_configManager().getNumber(SQL_PORT, __FUNCTION__), &g_configManager().getString(MYSQL_SOCK, __FUNCTION__)); } bool Database::connect(const std::string* host, const std::string* user, const std::string* password, const std::string* database, uint32_t port, const std::string* sock) { diff --git a/src/database/databasemanager.cpp b/src/database/databasemanager.cpp index a4b6b3b0e..373a91fa2 100644 --- a/src/database/databasemanager.cpp +++ b/src/database/databasemanager.cpp @@ -18,7 +18,7 @@ bool DatabaseManager::optimizeTables() { Database &db = Database::getInstance(); std::ostringstream query; - query << "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)) << " AND `DATA_FREE` > 0"; + query << "SELECT `TABLE_NAME` FROM `information_schema`.`TABLES` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB, __FUNCTION__)) << " AND `DATA_FREE` > 0"; DBResult_ptr result = db.storeQuery(query.str()); if (!result) { return false; @@ -47,14 +47,14 @@ bool DatabaseManager::tableExists(const std::string &tableName) { Database &db = Database::getInstance(); std::ostringstream query; - query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)) << " AND `TABLE_NAME` = " << db.escapeString(tableName) << " LIMIT 1"; + query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB, __FUNCTION__)) << " AND `TABLE_NAME` = " << db.escapeString(tableName) << " LIMIT 1"; return db.storeQuery(query.str()).get() != nullptr; } bool DatabaseManager::isDatabaseSetup() { Database &db = Database::getInstance(); std::ostringstream query; - query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB)); + query << "SELECT `TABLE_NAME` FROM `information_schema`.`tables` WHERE `TABLE_SCHEMA` = " << db.escapeString(g_configManager().getString(MYSQL_DB, __FUNCTION__)); return db.storeQuery(query.str()).get() != nullptr; } @@ -86,7 +86,7 @@ void DatabaseManager::updateDatabase() { int32_t version = getDatabaseVersion(); do { std::ostringstream ss; - ss << g_configManager().getString(DATA_DIRECTORY) + "/migrations/" << version << ".lua"; + ss << g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/migrations/" << version << ".lua"; if (luaL_dofile(L, ss.str().c_str()) != 0) { g_logger().error("DatabaseManager::updateDatabase - Version: {}" "] {}", diff --git a/src/game/functions/game_reload.cpp b/src/game/functions/game_reload.cpp index 4a53c95c2..873cd60ec 100644 --- a/src/game/functions/game_reload.cpp +++ b/src/game/functions/game_reload.cpp @@ -95,10 +95,10 @@ bool GameReload::reloadEvents() const { } bool GameReload::reloadCore() const { - if (auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + if (auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); g_luaEnvironment().loadFile(coreFolder + "/core.lua", "core.lua") == 0) { // Reload scripts lib - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); + auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); if (!g_scripts().loadScripts(datapackFolder + "/scripts/lib", true, false)) { return false; } @@ -124,7 +124,7 @@ bool GameReload::reloadMonsters() const { // Clear registered MonsterType vector g_monsters().clear(); // Resets monster spells to prevent the spell from being incorrectly cleared from memory - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); + auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); if (!g_scripts().loadScripts(datapackFolder + "/scripts/lib", true, false)) { return false; } @@ -151,9 +151,9 @@ bool GameReload::reloadScripts() const { g_scripts().clearAllScripts(); Zone::clearZones(); // Reset scripts lib to prevent the objects from being incorrectly cleared from memory - auto datapackFolder = g_configManager().getString(DATA_DIRECTORY); + auto datapackFolder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__); g_scripts().loadScripts(datapackFolder + "/scripts/lib", true, false); - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); g_scripts().loadScripts(datapackFolder + "/scripts", false, true); g_scripts().loadScripts(coreFolder + "/scripts", false, true); diff --git a/src/game/game.cpp b/src/game/game.cpp index 5aa0e6eec..5dcba79ad 100644 --- a/src/game/game.cpp +++ b/src/game/game.cpp @@ -129,7 +129,7 @@ namespace InternalGame { return false; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { if (std::shared_ptr houseTile = std::dynamic_pointer_cast(itemTile)) { const auto &house = houseTile->getHouse(); std::shared_ptr targetThing = g_game().internalGetThing(player, toPos, toStackPos, toItemId, STACKPOS_FIND_THING); @@ -274,10 +274,10 @@ void Game::loadBoostedCreature() { void Game::start(ServiceManager* manager) { // Game client protocols - manager->add(static_cast(g_configManager().getNumber(GAME_PORT))); - manager->add(static_cast(g_configManager().getNumber(LOGIN_PORT))); + manager->add(static_cast(g_configManager().getNumber(GAME_PORT, __FUNCTION__))); + manager->add(static_cast(g_configManager().getNumber(LOGIN_PORT, __FUNCTION__))); // OT protocols - manager->add(static_cast(g_configManager().getNumber(STATUS_PORT))); + manager->add(static_cast(g_configManager().getNumber(STATUS_PORT, __FUNCTION__))); serviceManager = manager; @@ -417,14 +417,14 @@ bool Game::loadItemsPrice() { } void Game::loadMainMap(const std::string &filename) { - Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE); - Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS); - map.loadMap(g_configManager().getString(DATA_DIRECTORY) + "/world/" + filename + ".otbm", true, true, true, true, true); + Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE, __FUNCTION__); + Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS, __FUNCTION__); + map.loadMap(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/world/" + filename + ".otbm", true, true, true, true, true); } void Game::loadCustomMaps(const std::filesystem::path &customMapPath) { - Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE); - Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS); + Monster::despawnRange = g_configManager().getNumber(DEFAULT_DESPAWNRANGE, __FUNCTION__); + Monster::despawnRadius = g_configManager().getNumber(DEFAULT_DESPAWNRADIUS, __FUNCTION__); namespace fs = std::filesystem; @@ -455,7 +455,7 @@ void Game::loadCustomMaps(const std::filesystem::path &customMapPath) { } // Avoid loading main map again. - if (filename == g_configManager().getString(MAP_NAME)) { + if (filename == g_configManager().getString(MAP_NAME, __FUNCTION__)) { g_logger().warn("Custom map {} is main map", filename); continue; } @@ -1025,7 +1025,7 @@ FILELOADER_ERRORS Game::loadAppearanceProtobuf(const std::string &file) { Item::items.loadFromProtobuf(); // Only iterate other objects if necessary - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__)) { // Registering distance effects for (uint32_t it = 0; it < appearances.effect_size(); it++) { registeredMagicEffects.push_back(static_cast(appearances.effect(it).id())); @@ -1093,7 +1093,7 @@ void Game::playerMoveThing(uint32_t playerId, const Position &fromPos, uint16_t if (Position::areInRange<1, 1, 0>(movingCreature->getPosition(), player->getPosition())) { std::shared_ptr task = createPlayerTask( - g_configManager().getNumber(PUSH_DELAY), + g_configManager().getNumber(PUSH_DELAY, __FUNCTION__), std::bind(&Game::playerMoveCreatureByID, this, player->getID(), movingCreature->getID(), movingCreature->getPosition(), tile->getPosition()), "Game::playerMoveCreatureByID" ); @@ -1584,11 +1584,11 @@ ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::s } if (containerID == ITEM_GOLD_POUCH) { - if (g_configManager().getBoolean(TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY)) { + if (g_configManager().getBoolean(TOGGLE_GOLD_POUCH_QUICKLOOT_ONLY, __FUNCTION__)) { return RETURNVALUE_CONTAINERNOTENOUGHROOM; } - bool allowAnything = g_configManager().getBoolean(TOGGLE_GOLD_POUCH_ALLOW_ANYTHING); + bool allowAnything = g_configManager().getBoolean(TOGGLE_GOLD_POUCH_ALLOW_ANYTHING, __FUNCTION__); if (!allowAnything && item->getID() != ITEM_GOLD_COIN && item->getID() != ITEM_PLATINUM_COIN && item->getID() != ITEM_CRYSTAL_COIN) { return RETURNVALUE_CONTAINERNOTENOUGHROOM; @@ -1625,6 +1625,10 @@ ReturnValue Game::checkMoveItemToCylinder(std::shared_ptr player, std::s isValidMoveItem = true; } + if (item->getID() == ITEM_GOLD_POUCH) { + isValidMoveItem = true; + } + if (!isValidMoveItem) { return RETURNVALUE_NOTPOSSIBLE; } @@ -2759,7 +2763,7 @@ ReturnValue Game::internalCollectLootItems(std::shared_ptr player, std:: } // Send money to the bank - if (g_configManager().getBoolean(AUTOBANK)) { + if (g_configManager().getBoolean(AUTOBANK, __FUNCTION__)) { if (item->getID() == ITEM_GOLD_COIN || item->getID() == ITEM_PLATINUM_COIN || item->getID() == ITEM_CRYSTAL_COIN) { uint64_t money = 0; if (item->getID() == ITEM_PLATINUM_COIN) { @@ -3241,7 +3245,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t f } bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); - if (isHotkey && !g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED)) { + if (isHotkey && !g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED, __FUNCTION__)) { return; } @@ -3257,7 +3261,7 @@ void Game::playerUseItemEx(uint32_t playerId, const Position &fromPos, uint8_t f return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS) && !InternalGame::playerCanUseItemWithOnHouseTile(player, item, toPos, toStackPos, toItemId)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemWithOnHouseTile(player, item, toPos, toStackPos, toItemId)) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; } @@ -3370,7 +3374,7 @@ void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPo } bool isHotkey = (pos.x == 0xFFFF && pos.y == 0 && pos.z == 0); - if (isHotkey && !g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED)) { + if (isHotkey && !g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED, __FUNCTION__)) { return; } @@ -3386,7 +3390,7 @@ void Game::playerUseItem(uint32_t playerId, const Position &pos, uint8_t stackPo return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { player->sendCancelMessage(RETURNVALUE_CANNOTUSETHISOBJECT); return; } @@ -3473,7 +3477,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uin } bool isHotkey = (fromPos.x == 0xFFFF && fromPos.y == 0 && fromPos.z == 0); - if (!g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED)) { + if (!g_configManager().getBoolean(AIMBOT_HOTKEY_ENABLED, __FUNCTION__)) { if (creature->getPlayer() || isHotkey) { player->sendCancelMessage(RETURNVALUE_DIRECTPLAYERSHOOT); return; @@ -3492,7 +3496,7 @@ void Game::playerUseWithCreature(uint32_t playerId, const Position &fromPos, uin return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { if (std::shared_ptr houseTile = std::dynamic_pointer_cast(item->getTile())) { const auto &house = houseTile->getHouse(); if (house && item->getRealParent() && item->getRealParent() != player && (!house->isInvited(player) || house->getHouseAccessLevel(player) == HOUSE_GUEST)) { @@ -3774,7 +3778,7 @@ void Game::playerSetShowOffSocket(uint32_t playerId, Outfit_t &outfit, const Pos return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -4296,7 +4300,7 @@ void Game::playerRequestTrade(uint32_t playerId, const Position &pos, uint8_t st return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { if (std::shared_ptr houseTile = std::dynamic_pointer_cast(tradeItem->getTile())) { const auto &house = houseTile->getHouse(); if (house && tradeItem->getRealParent() != player && (!house->isInvited(player) || house->getHouseAccessLevel(player) == HOUSE_GUEST)) { @@ -5040,7 +5044,7 @@ void Game::playerSetLootContainer(uint32_t playerId, ObjectCategory_t category, } std::shared_ptr container = thing->getContainer(); - if (!container || (container->getID() == ITEM_GOLD_POUCH && category != OBJECTCATEGORY_GOLD && !g_configManager().getBoolean(TOGGLE_GOLD_POUCH_ALLOW_ANYTHING))) { + if (!container || (container->getID() == ITEM_GOLD_POUCH && category != OBJECTCATEGORY_GOLD && !g_configManager().getBoolean(TOGGLE_GOLD_POUCH_ALLOW_ANYTHING, __FUNCTION__))) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -5387,7 +5391,7 @@ void Game::playerTurn(uint32_t playerId, Direction dir) { } void Game::playerRequestOutfit(uint32_t playerId) { - if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT)) { + if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT, __FUNCTION__)) { return; } @@ -5409,7 +5413,7 @@ void Game::playerToggleMount(uint32_t playerId, bool mount) { } void Game::playerChangeOutfit(uint32_t playerId, Outfit_t outfit, uint8_t isMountRandomized /* = 0*/) { - if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT)) { + if (!g_configManager().getBoolean(ALLOW_CHANGEOUTFIT, __FUNCTION__)) { return; } @@ -5572,11 +5576,11 @@ bool Game::playerSaySpell(std::shared_ptr player, SpeakClasses type, con result = g_spells().playerSaySpell(player, words); if (result == TALKACTION_BREAK) { - if (!g_configManager().getBoolean(PUSH_WHEN_ATTACKING)) { + if (!g_configManager().getBoolean(PUSH_WHEN_ATTACKING, __FUNCTION__)) { player->cancelPush(); } - if (g_configManager().getBoolean(EMOTE_SPELLS) && player->getStorageValue(STORAGEVALUE_EMOTE) == 1) { + if (g_configManager().getBoolean(EMOTE_SPELLS, __FUNCTION__) && player->getStorageValue(STORAGEVALUE_EMOTE) == 1) { return internalCreatureSay(player, TALKTYPE_MONSTER_SAY, words, false); } else { return player->saySpell(type, words, false); @@ -5793,7 +5797,7 @@ void Game::checkCreatures() { auto &checkCreatureList = checkCreatureLists[index]; size_t it = 0, end = checkCreatureList.size(); while (it < end) { - const auto &creature = checkCreatureList[it]; + auto creature = checkCreatureList[it]; if (creature && creature->creatureCheck) { if (creature->getHealth() > 0) { creature->onThink(EVENT_CREATURE_THINK_INTERVAL); @@ -6295,15 +6299,15 @@ float Game::pvpLevelDifferenceDamageMultiplier(std::shared_ptr attacker, levelDifference = std::abs(levelDifference); bool isLowerLevel = target->getLevel() < attacker->getLevel(); - int32_t maxLevelDifference = g_configManager().getNumber(PVP_MAX_LEVEL_DIFFERENCE); + int32_t maxLevelDifference = g_configManager().getNumber(PVP_MAX_LEVEL_DIFFERENCE, __FUNCTION__); levelDifference = std::min(levelDifference, maxLevelDifference); float levelDiffRate = 1.0; if (isLowerLevel) { - float rateDamageTakenByLevel = g_configManager().getFloat(PVP_RATE_DAMAGE_TAKEN_PER_LEVEL) / 100; + float rateDamageTakenByLevel = g_configManager().getFloat(PVP_RATE_DAMAGE_TAKEN_PER_LEVEL, __FUNCTION__) / 100; levelDiffRate += levelDifference * rateDamageTakenByLevel; } else { - float rateDamageReductionByLevel = g_configManager().getFloat(PVP_RATE_DAMAGE_REDUCTION_PER_LEVEL) / 100; + float rateDamageReductionByLevel = g_configManager().getFloat(PVP_RATE_DAMAGE_REDUCTION_PER_LEVEL, __FUNCTION__) / 100; levelDiffRate -= levelDifference * rateDamageReductionByLevel; } @@ -6621,10 +6625,8 @@ bool Game::combatChangeHealth(std::shared_ptr attacker, std::shared_pt } } + std::string attackMsg = fmt::format("{} attack", damage.critical ? "critical " : " "); std::stringstream ss; - ss << (damage.critical ? "critical " : " ") << "attack"; - std::string attackMsg = ss.str(); - ss.str({}); if (target->hasCondition(CONDITION_MANASHIELD) && damage.primary.type != COMBAT_UNDEFINEDDAMAGE) { int32_t manaDamage = std::min(target->getMana(), healthChange); @@ -6911,17 +6913,19 @@ void Game::buildMessageAsSpectator( ) const { if (spectatorMessage.empty()) { ss.str({}); + auto attackMsg = damage.critical ? "critical " : ""; + auto article = damage.critical ? "a" : "an"; ss << ucfirst(target->getNameDescription()) << " loses " << damageString; if (attacker) { ss << " due to "; if (attacker == target) { if (targetPlayer) { - ss << targetPlayer->getPossessivePronoun() << " own attack"; + ss << targetPlayer->getPossessivePronoun() << " own " << attackMsg << "attack"; } else { - ss << "its own attack"; + ss << "its own " << attackMsg << "attack"; } } else { - ss << "an attack by " << attacker->getNameDescription(); + ss << article << " " << attackMsg << "attack by " << attacker->getNameDescription(); } } ss << '.'; @@ -6941,13 +6945,15 @@ void Game::buildMessageAsTarget( const std::string &damageString ) const { ss.str({}); + auto attackMsg = damage.critical ? "critical " : ""; + auto article = damage.critical ? "a" : "an"; ss << "You lose " << damageString; if (!attacker) { ss << '.'; } else if (targetPlayer == attackerPlayer) { - ss << " due to your own attack."; + ss << " due to your own " << attackMsg << "attack."; } else { - ss << " due to an attack by " << attacker->getNameDescription() << '.'; + ss << " due to " << article << " " << attackMsg << "attack by " << attacker->getNameDescription() << '.'; } if (damage.extension) { ss << " " << damage.exString; @@ -6961,7 +6967,7 @@ void Game::buildMessageAsAttacker( std::stringstream &ss, const std::string &damageString ) const { ss.str({}); - ss << ucfirst(target->getNameDescription()) << " loses " << damageString << " due to your attack."; + ss << ucfirst(target->getNameDescription()) << " loses " << damageString << " due to your " << (damage.critical ? "critical " : " ") << "attack."; if (damage.extension) { ss << " " << damage.exString; } @@ -7217,7 +7223,13 @@ bool Game::combatChangeMana(std::shared_ptr attacker, std::shared_ptr< } target->drainMana(attacker, manaLoss); - + if (targetPlayer) { + std::string cause = "(other)"; + if (attacker) { + cause = attacker->getName(); + } + targetPlayer->updateInputAnalyzer(damage.primary.type, damage.primary.value * -1, cause); + } std::stringstream ss; std::string damageString = std::to_string(manaLoss); @@ -7565,7 +7577,7 @@ void Game::loadMotdNum() { result = db.storeQuery("SELECT `value` FROM `server_config` WHERE `config` = 'motd_hash'"); if (result) { motdHash = result->getString("value"); - if (motdHash != transformToSHA1(g_configManager().getString(SERVER_MOTD))) { + if (motdHash != transformToSHA1(g_configManager().getString(SERVER_MOTD, __FUNCTION__))) { ++motdNum; } } else { @@ -7581,7 +7593,7 @@ void Game::saveMotdNum() const { db.executeQuery(query.str()); query.str(std::string()); - query << "UPDATE `server_config` SET `value` = '" << transformToSHA1(g_configManager().getString(SERVER_MOTD)) << "' WHERE `config` = 'motd_hash'"; + query << "UPDATE `server_config` SET `value` = '" << transformToSHA1(g_configManager().getString(SERVER_MOTD, __FUNCTION__)) << "' WHERE `config` = 'motd_hash'"; db.executeQuery(query.str()); } @@ -7730,7 +7742,8 @@ void Game::playerLeaveParty(uint32_t playerId) { } std::shared_ptr party = player->getParty(); - if (!party || player->hasCondition(CONDITION_INFIGHT)) { + if (!party || player->hasCondition(CONDITION_INFIGHT) && !player->getZoneType() == ZONE_PROTECTION) { + player->sendTextMessage(TextMessage(MESSAGE_FAILURE, "You cannot leave party, contact the administrator.")); return; } @@ -8396,12 +8409,12 @@ bool checkCanInitCreateMarketOffer(std::shared_ptr player, uint8_t type, g_logger().debug("{} - Offer amount: {}", __FUNCTION__, amount); - if (g_configManager().getBoolean(MARKET_PREMIUM) && !player->isPremium()) { + if (g_configManager().getBoolean(MARKET_PREMIUM, __FUNCTION__) && !player->isPremium()) { player->sendTextMessage(MESSAGE_MARKET, "Only premium accounts may create offers for that object."); return false; } - const uint32_t maxOfferCount = g_configManager().getNumber(MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER); + const uint32_t maxOfferCount = g_configManager().getNumber(MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER, __FUNCTION__); if (maxOfferCount != 0 && IOMarket::getPlayerOfferCount(player->getGUID()) >= maxOfferCount) { offerStatus << "Player " << player->getName() << "excedeed max offer count " << maxOfferCount; return false; @@ -8577,7 +8590,7 @@ void Game::playerCancelMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 IOMarket::moveOfferToHistory(offer.id, OFFERSTATE_CANCELLED); offer.amount = 0; - offer.timestamp += g_configManager().getNumber(MARKET_OFFER_DURATION); + offer.timestamp += g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); player->sendMarketCancelOffer(offer); // Send market window again for update stats player->sendMarketEnter(player->getLastDepotId()); @@ -8833,7 +8846,7 @@ void Game::playerAcceptMarketOffer(uint32_t playerId, uint32_t timestamp, uint16 return; } - const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION); + const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); IOMarket::appendHistory(player->getGUID(), (offer.type == MARKETACTION_BUY ? MARKETACTION_SELL : MARKETACTION_BUY), offer.itemId, amount, offer.price, time(nullptr), offer.tier, OFFERSTATE_ACCEPTEDEX); @@ -8932,8 +8945,8 @@ void Game::playerForgeFuseItems(uint32_t playerId, uint16_t itemId, uint8_t tier player->updateUIExhausted(); uint8_t coreCount = (usedCore ? 1 : 0) + (reduceTierLoss ? 1 : 0); - auto baseSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE)); - auto bonusSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE) + g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE)); + auto baseSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE, __FUNCTION__)); + auto bonusSuccess = static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE, __FUNCTION__) + g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE, __FUNCTION__)); auto roll = static_cast(uniform_random(1, 100)) <= (usedCore ? bonusSuccess : baseSuccess); bool success = roll ? true : false; @@ -9043,7 +9056,7 @@ void Game::playerSetMonsterPodium(uint32_t playerId, uint32_t monsterRaceId, con return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -9135,7 +9148,7 @@ void Game::playerRotatePodium(uint32_t playerId, const Position &pos, uint8_t st return; } - if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { + if (g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__) && !InternalGame::playerCanUseItemOnHouseTile(player, item)) { player->sendCancelMessage(RETURNVALUE_NOTPOSSIBLE); return; } @@ -9457,7 +9470,7 @@ void Game::sendUpdateCreature(std::shared_ptr creature) { } uint32_t Game::makeInfluencedMonster() { - if (auto influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT); + if (auto influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT, __FUNCTION__); // Condition forgeableMonsters.empty() || influencedMonsters.size() >= influencedLimit) { return 0; @@ -9538,7 +9551,7 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool cr } } - if (auto fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT); + if (auto fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT, __FUNCTION__); // Condition forgeableMonsters.empty() || fiendishMonsters.size() >= fiendishLimit) { return 0; @@ -9577,8 +9590,8 @@ uint32_t Game::makeFiendishMonster(uint32_t forgeableMonsterId /* = 0*/, bool cr } // Get interval time to fiendish - std::string saveIntervalType = g_configManager().getString(FORGE_FIENDISH_INTERVAL_TYPE); - auto saveIntervalConfigTime = std::atoi(g_configManager().getString(FORGE_FIENDISH_INTERVAL_TIME).c_str()); + std::string saveIntervalType = g_configManager().getString(FORGE_FIENDISH_INTERVAL_TYPE, __FUNCTION__); + auto saveIntervalConfigTime = std::atoi(g_configManager().getString(FORGE_FIENDISH_INTERVAL_TIME, __FUNCTION__).c_str()); int intervalTime = 0; time_t timeToChangeFiendish; if (saveIntervalType == "second") { @@ -9693,7 +9706,7 @@ void Game::updateForgeableMonsters() { } } - uint32_t fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT); // Fiendish Creatures limit + uint32_t fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT, __FUNCTION__); // Fiendish Creatures limit if (fiendishMonsters.size() < fiendishLimit) { createFiendishMonsters(); } @@ -9701,7 +9714,7 @@ void Game::updateForgeableMonsters() { void Game::createFiendishMonsters() { uint32_t created = 0; - uint32_t fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT); // Fiendish Creatures limit + uint32_t fiendishLimit = g_configManager().getNumber(FORGE_FIENDISH_CREATURES_LIMIT, __FUNCTION__); // Fiendish Creatures limit while (fiendishMonsters.size() < fiendishLimit) { if (fiendishMonsters.size() >= fiendishLimit) { g_logger().warn("[{}] - Returning in creation of Fiendish, size: {}, max is: {}.", __FUNCTION__, fiendishMonsters.size(), fiendishLimit); @@ -9720,7 +9733,7 @@ void Game::createFiendishMonsters() { void Game::createInfluencedMonsters() { uint32_t created = 0; - uint32_t influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT); + uint32_t influencedLimit = g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT, __FUNCTION__); while (created < influencedLimit) { if (influencedMonsters.size() >= influencedLimit) { g_logger().warn("[{}] - Returning in creation of Influenced, size: {}, max is: {}.", __FUNCTION__, influencedMonsters.size(), influencedLimit); @@ -9747,7 +9760,7 @@ void Game::checkForgeEventId(uint32_t monsterId) { bool Game::addInfluencedMonster(std::shared_ptr monster) { if (monster && monster->canBeForgeMonster()) { - if (auto maxInfluencedMonsters = static_cast(g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT)); + if (auto maxInfluencedMonsters = static_cast(g_configManager().getNumber(FORGE_INFLUENCED_CREATURES_LIMIT, __FUNCTION__)); // If condition (influencedMonsters.size() + 1) > maxInfluencedMonsters) { return false; @@ -9853,7 +9866,7 @@ void Game::playerCheckActivity(const std::string &playerName, int interval) { if (!player->isAccessPlayer()) { player->m_deathTime += interval; - const int32_t kickAfterMinutes = g_configManager().getNumber(KICK_AFTER_MINUTES); + const int32_t kickAfterMinutes = g_configManager().getNumber(KICK_AFTER_MINUTES, __FUNCTION__); if (player->m_deathTime > (kickAfterMinutes * 60000) + 60000) { g_logger().info("Player with name '{}' has logged out due to inactivity after death", player->getName()); g_game().removePlayerUniqueLogin(playerName); @@ -9922,7 +9935,7 @@ const std::unique_ptr &Game::getIOWheel() const { } void Game::transferHouseItemsToDepot() { - if (!g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART)) { + if (!g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__)) { return; } diff --git a/src/game/scheduling/dispatcher.cpp b/src/game/scheduling/dispatcher.cpp index a24ef7704..fff897def 100644 --- a/src/game/scheduling/dispatcher.cpp +++ b/src/game/scheduling/dispatcher.cpp @@ -21,13 +21,13 @@ Dispatcher &Dispatcher::getInstance() { } void Dispatcher::init() { - updateClock(); + UPDATE_OTSYS_TIME(); threadPool.addLoad([this] { std::unique_lock asyncLock(dummyMutex); while (!threadPool.getIoContext().stopped()) { - updateClock(); + UPDATE_OTSYS_TIME(); executeEvents(); executeScheduledEvents(); @@ -104,7 +104,7 @@ void Dispatcher::executeScheduledEvents() { auto it = scheduledTasks.begin(); while (it != scheduledTasks.end()) { const auto &task = *it; - if (task->getTime() > Task::TIME_NOW) { + if (task->getTime() > OTSYS_TIME()) { break; } @@ -168,17 +168,17 @@ void Dispatcher::mergeEvents() { checkPendingTasks(); } -std::chrono::nanoseconds Dispatcher::timeUntilNextScheduledTask() const { - static constexpr auto CHRONO_NANO_0 = std::chrono::nanoseconds(0); - static constexpr auto CHRONO_MILI_MAX = std::chrono::milliseconds::max(); +std::chrono::milliseconds Dispatcher::timeUntilNextScheduledTask() const { + constexpr auto CHRONO_0 = std::chrono::milliseconds(0); + constexpr auto CHRONO_MILI_MAX = std::chrono::milliseconds::max(); if (scheduledTasks.empty()) { return CHRONO_MILI_MAX; } const auto &task = *scheduledTasks.begin(); - const auto timeRemaining = task->getTime() - Task::TIME_NOW; - return std::max(timeRemaining, CHRONO_NANO_0); + const auto timeRemaining = std::chrono::milliseconds(task->getTime() - OTSYS_TIME()); + return std::max(timeRemaining, CHRONO_0); } void Dispatcher::addEvent(std::function &&f, std::string_view context, uint32_t expiresAfterMs) { diff --git a/src/game/scheduling/dispatcher.hpp b/src/game/scheduling/dispatcher.hpp index 9d0a5c517..1c5f72658 100644 --- a/src/game/scheduling/dispatcher.hpp +++ b/src/game/scheduling/dispatcher.hpp @@ -32,7 +32,7 @@ enum class DispatcherType : uint8_t { struct DispatcherContext { bool isOn() const { - return Task::TIME_NOW != SYSTEM_TIME_ZERO; + return OTSYS_TIME() != 0; } bool isGroup(const TaskGroup _group) const { @@ -134,11 +134,6 @@ class Dispatcher { private: thread_local static DispatcherContext dispacherContext; - // Update Time Cache - static void updateClock() { - Task::TIME_NOW = std::chrono::system_clock::now(); - } - const auto &getThreadTask() const { return threads[ThreadPool::getThreadId()]; } @@ -159,7 +154,7 @@ class Dispatcher { inline void executeSerialEvents(std::vector &tasks); inline void executeParallelEvents(std::vector &tasks, const uint8_t groupId); - inline std::chrono::nanoseconds timeUntilNextScheduledTask() const; + inline std::chrono::milliseconds timeUntilNextScheduledTask() const; inline void checkPendingTasks() { hasPendingTasks = false; diff --git a/src/game/scheduling/events_scheduler.cpp b/src/game/scheduling/events_scheduler.cpp index fc41f2c8b..5eaebba70 100644 --- a/src/game/scheduling/events_scheduler.cpp +++ b/src/game/scheduling/events_scheduler.cpp @@ -15,7 +15,7 @@ bool EventsScheduler::loadScheduleEventFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/XML/events.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/XML/events.xml"; if (!doc.load_file(folder.c_str())) { printXMLError(__FUNCTION__, folder, doc.load_file(folder.c_str())); consoleHandlerExit(); diff --git a/src/game/scheduling/task.cpp b/src/game/scheduling/task.cpp index c9e6157ab..28418a4a1 100644 --- a/src/game/scheduling/task.cpp +++ b/src/game/scheduling/task.cpp @@ -10,8 +10,6 @@ #include "pch.hpp" #include "task.hpp" #include "lib/logging/log_with_spd_log.hpp" - -std::chrono::system_clock::time_point Task::TIME_NOW = SYSTEM_TIME_ZERO; std::atomic_uint_fast64_t Task::LAST_EVENT_ID = 0; bool Task::execute() const { diff --git a/src/game/scheduling/task.hpp b/src/game/scheduling/task.hpp index f42602242..18dfd5d39 100644 --- a/src/game/scheduling/task.hpp +++ b/src/game/scheduling/task.hpp @@ -11,19 +11,15 @@ #include "utils/tools.hpp" #include -static constexpr auto SYSTEM_TIME_ZERO = std::chrono::system_clock::time_point(std::chrono::milliseconds(0)); - class Task { public: - static std::chrono::system_clock::time_point TIME_NOW; - Task(uint32_t expiresAfterMs, std::function &&f, std::string_view context) : - func(std::move(f)), context(context), utime(TIME_NOW), expiration(expiresAfterMs > 0 ? TIME_NOW + std::chrono::milliseconds(expiresAfterMs) : SYSTEM_TIME_ZERO) { + func(std::move(f)), context(context), utime(OTSYS_TIME()), expiration(expiresAfterMs > 0 ? OTSYS_TIME() + expiresAfterMs : 0) { assert(!this->context.empty() && "Context cannot be empty!"); } Task(std::function &&f, std::string_view context, uint32_t delay, bool cycle = false, bool log = true) : - func(std::move(f)), context(context), utime(TIME_NOW + std::chrono::milliseconds(delay)), delay(delay), cycle(cycle), log(log) { + func(std::move(f)), context(context), utime(OTSYS_TIME() + delay), delay(delay), cycle(cycle), log(log) { assert(!this->context.empty() && "Context cannot be empty!"); } @@ -54,7 +50,7 @@ class Task { } bool hasExpired() const { - return expiration != SYSTEM_TIME_ZERO && expiration < TIME_NOW; + return expiration != 0 && expiration < OTSYS_TIME(); } bool isCycle() const { @@ -75,7 +71,7 @@ class Task { static std::atomic_uint_fast64_t LAST_EVENT_ID; void updateTime() { - utime = TIME_NOW + std::chrono::milliseconds(delay); + utime = OTSYS_TIME() + delay; } bool hasTraceableContext() const { @@ -117,8 +113,8 @@ class Task { std::function func = nullptr; std::string_view context; - std::chrono::system_clock::time_point utime = SYSTEM_TIME_ZERO; - std::chrono::system_clock::time_point expiration = SYSTEM_TIME_ZERO; + int64_t utime = 0; + int64_t expiration = 0; uint64_t id = 0; uint32_t delay = 0; diff --git a/src/io/functions/iologindata_load_player.cpp b/src/io/functions/iologindata_load_player.cpp index f404a52b8..33a8b0a8f 100644 --- a/src/io/functions/iologindata_load_player.cpp +++ b/src/io/functions/iologindata_load_player.cpp @@ -93,9 +93,9 @@ bool IOLoginDataLoad::preLoadPlayer(std::shared_ptr player, const std::s uint32_t premiumDays = player->getAccount()->getPremiumRemainingDays(); uint32_t premiumDaysPurchased = player->getAccount()->getPremiumDaysPurchased(); - player->loyaltyPoints = player->getAccount()->getAccountAgeInDays() * g_configManager().getNumber(LOYALTY_POINTS_PER_CREATION_DAY) - + (premiumDaysPurchased - premiumDays) * g_configManager().getNumber(LOYALTY_POINTS_PER_PREMIUM_DAY_SPENT) - + premiumDaysPurchased * g_configManager().getNumber(LOYALTY_POINTS_PER_PREMIUM_DAY_PURCHASED); + player->loyaltyPoints = player->getAccount()->getAccountAgeInDays() * g_configManager().getNumber(LOYALTY_POINTS_PER_CREATION_DAY, __FUNCTION__) + + (premiumDaysPurchased - premiumDays) * g_configManager().getNumber(LOYALTY_POINTS_PER_PREMIUM_DAY_SPENT, __FUNCTION__) + + premiumDaysPurchased * g_configManager().getNumber(LOYALTY_POINTS_PER_PREMIUM_DAY_PURCHASED, __FUNCTION__); return true; } @@ -243,7 +243,7 @@ void IOLoginDataLoad::loadPlayerDefaultOutfit(std::shared_ptr player, DB } player->defaultOutfit.lookType = result->getNumber("looktype"); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && player->defaultOutfit.lookType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && player->defaultOutfit.lookType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookType)) { g_logger().warn("[IOLoginData::loadPlayer] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", player->defaultOutfit.lookType); return; } @@ -259,7 +259,7 @@ void IOLoginDataLoad::loadPlayerDefaultOutfit(std::shared_ptr player, DB player->defaultOutfit.lookMountFeet = static_cast(result->getNumber("lookmountfeet")); player->defaultOutfit.lookFamiliarsType = result->getNumber("lookfamiliarstype"); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && player->defaultOutfit.lookFamiliarsType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookFamiliarsType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && player->defaultOutfit.lookFamiliarsType != 0 && !g_game().isLookTypeRegistered(player->defaultOutfit.lookFamiliarsType)) { g_logger().warn("[IOLoginData::loadPlayer] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", player->defaultOutfit.lookFamiliarsType); return; } @@ -323,7 +323,7 @@ void IOLoginDataLoad::loadPlayerKills(std::shared_ptr player, DBResult_p if ((result = db.storeQuery(query.str()))) { do { time_t killTime = result->getNumber("time"); - if ((time(nullptr) - killTime) <= g_configManager().getNumber(FRAG_TIME)) { + if ((time(nullptr) - killTime) <= g_configManager().getNumber(FRAG_TIME, __FUNCTION__)) { player->unjustifiedKills.emplace_back(result->getNumber("target"), killTime, result->getNumber("unavenged")); } } while (result->next()); @@ -471,7 +471,7 @@ void IOLoginDataLoad::loadPlayerInventoryItems(std::shared_ptr player, D return; } - bool oldProtocol = g_configManager().getBoolean(OLD_PROTOCOL) && player->getProtocolVersion() < 1200; + bool oldProtocol = g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) && player->getProtocolVersion() < 1200; Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT `pid`, `sid`, `itemtype`, `count`, `attributes` FROM `player_items` WHERE `player_id` = " << player->getGUID() << " ORDER BY `sid` DESC"; @@ -685,7 +685,7 @@ void IOLoginDataLoad::loadPlayerPreyClass(std::shared_ptr player, DBResu return; } - if (g_configManager().getBoolean(PREY_ENABLED)) { + if (g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `player_prey` WHERE `player_id` = " << player->getGUID(); @@ -732,7 +732,7 @@ void IOLoginDataLoad::loadPlayerTaskHuntingClass(std::shared_ptr player, return; } - if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { Database &db = Database::getInstance(); std::ostringstream query; query << "SELECT * FROM `player_taskhunt` WHERE `player_id` = " << player->getGUID(); diff --git a/src/io/functions/iologindata_save_player.cpp b/src/io/functions/iologindata_save_player.cpp index 1c3db4053..3f2e7a233 100644 --- a/src/io/functions/iologindata_save_player.cpp +++ b/src/io/functions/iologindata_save_player.cpp @@ -583,7 +583,7 @@ bool IOLoginDataSave::savePlayerPreyClass(std::shared_ptr player) { } Database &db = Database::getInstance(); - if (g_configManager().getBoolean(PREY_ENABLED)) { + if (g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { std::ostringstream query; for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { if (const auto &slot = player->getPreySlotById(static_cast(slotId))) { @@ -637,7 +637,7 @@ bool IOLoginDataSave::savePlayerTaskHuntingClass(std::shared_ptr player) } Database &db = Database::getInstance(); - if (g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { std::ostringstream query; for (uint8_t slotId = PreySlot_First; slotId <= PreySlot_Last; slotId++) { if (const auto &slot = player->getTaskHuntingSlotById(static_cast(slotId))) { diff --git a/src/io/iologindata.cpp b/src/io/iologindata.cpp index f2d42ad54..584f36e20 100644 --- a/src/io/iologindata.cpp +++ b/src/io/iologindata.cpp @@ -25,7 +25,7 @@ bool IOLoginData::gameWorldAuthentication(const std::string &accountDescriptor, return false; } - if (g_configManager().getString(AUTH_TYPE) == "session") { + if (g_configManager().getString(AUTH_TYPE, __FUNCTION__) == "session") { if (!account.authenticate()) { return false; } diff --git a/src/io/iomap.hpp b/src/io/iomap.hpp index 0c93b4a8e..e74f1ce3b 100644 --- a/src/io/iomap.hpp +++ b/src/io/iomap.hpp @@ -32,7 +32,7 @@ class IOMap { if (map->monsterfile.empty()) { // OTBM file doesn't tell us about the monsterfile, // Lets guess it is mapname-monster.xml. - map->monsterfile = g_configManager().getString(MAP_NAME); + map->monsterfile = g_configManager().getString(MAP_NAME, __FUNCTION__); map->monsterfile += "-monster.xml"; } @@ -48,7 +48,7 @@ class IOMap { if (map->zonesfile.empty()) { // OTBM file doesn't tell us about the zonesfile, // Lets guess it is mapname-zone.xml. - map->zonesfile = g_configManager().getString(MAP_NAME); + map->zonesfile = g_configManager().getString(MAP_NAME, __FUNCTION__); map->zonesfile += "-zones.xml"; } @@ -64,7 +64,7 @@ class IOMap { if (map->npcfile.empty()) { // OTBM file doesn't tell us about the npcfile, // Lets guess it is mapname-npc.xml. - map->npcfile = g_configManager().getString(MAP_NAME); + map->npcfile = g_configManager().getString(MAP_NAME, __FUNCTION__); map->npcfile += "-npc.xml"; } @@ -80,7 +80,7 @@ class IOMap { if (map->housefile.empty()) { // OTBM file doesn't tell us about the housefile, // Lets guess it is mapname-house.xml. - map->housefile = g_configManager().getString(MAP_NAME); + map->housefile = g_configManager().getString(MAP_NAME, __FUNCTION__); map->housefile += "-house.xml"; } diff --git a/src/io/iomapserialize.cpp b/src/io/iomapserialize.cpp index 7862e1a11..db1bac1e5 100644 --- a/src/io/iomapserialize.cpp +++ b/src/io/iomapserialize.cpp @@ -274,7 +274,7 @@ bool IOMapSerialize::loadHouseInfo() { uint32_t owner = result->getNumber("owner"); int32_t newOwner = result->getNumber("new_owner"); // Transfer house owner - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && newOwner >= 0) { g_game().setTransferPlayerHouseItems(houseId, owner); if (newOwner == 0) { diff --git a/src/io/iomarket.cpp b/src/io/iomarket.cpp index 6aa25e65f..ad0459983 100644 --- a/src/io/iomarket.cpp +++ b/src/io/iomarket.cpp @@ -18,7 +18,7 @@ uint8_t IOMarket::getTierFromDatabaseTable(const std::string &string) { auto tier = static_cast(std::atoi(string.c_str())); - if (tier > g_configManager().getNumber(FORGE_MAX_ITEM_TIER)) { + if (tier > g_configManager().getNumber(FORGE_MAX_ITEM_TIER, __FUNCTION__)) { g_logger().error("{} - Failed to get number value {} for tier table result", __FUNCTION__, tier); return 0; } @@ -37,7 +37,7 @@ MarketOfferList IOMarket::getActiveOffers(MarketAction_t action, uint16_t itemId return offerList; } - const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION); + const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); do { MarketOffer offer; @@ -59,7 +59,7 @@ MarketOfferList IOMarket::getActiveOffers(MarketAction_t action, uint16_t itemId MarketOfferList IOMarket::getOwnOffers(MarketAction_t action, uint32_t playerId) { MarketOfferList offerList; - const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION); + const int32_t marketOfferDuration = g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); std::ostringstream query; query << "SELECT `id`, `amount`, `price`, `created`, `itemtype`, `tier` FROM `market_offers` WHERE `player_id` = " << playerId << " AND `sale` = " << action; @@ -191,13 +191,13 @@ void IOMarket::processExpiredOffers(DBResult_ptr result, bool) { } void IOMarket::checkExpiredOffers() { - const time_t lastExpireDate = getTimeNow() - g_configManager().getNumber(MARKET_OFFER_DURATION); + const time_t lastExpireDate = getTimeNow() - g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); std::ostringstream query; query << "SELECT `id`, `amount`, `price`, `itemtype`, `player_id`, `sale`, `tier` FROM `market_offers` WHERE `created` <= " << lastExpireDate; g_databaseTasks().store(query.str(), IOMarket::processExpiredOffers); - int32_t checkExpiredMarketOffersEachMinutes = g_configManager().getNumber(CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES); + int32_t checkExpiredMarketOffersEachMinutes = g_configManager().getNumber(CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES, __FUNCTION__); if (checkExpiredMarketOffersEachMinutes <= 0) { return; } @@ -219,7 +219,7 @@ uint32_t IOMarket::getPlayerOfferCount(uint32_t playerId) { MarketOfferEx IOMarket::getOfferByCounter(uint32_t timestamp, uint16_t counter) { MarketOfferEx offer; - const int32_t created = timestamp - g_configManager().getNumber(MARKET_OFFER_DURATION); + const int32_t created = timestamp - g_configManager().getNumber(MARKET_OFFER_DURATION, __FUNCTION__); std::ostringstream query; query << "SELECT `id`, `sale`, `itemtype`, `amount`, `created`, `price`, `player_id`, `anonymous`, `tier`, (SELECT `name` FROM `players` WHERE `id` = `player_id`) AS `player_name` FROM `market_offers` WHERE `created` = " << created << " AND (`id` & 65535) = " << counter << " LIMIT 1"; diff --git a/src/io/ioprey.cpp b/src/io/ioprey.cpp index 50c3070b4..b953d1807 100644 --- a/src/io/ioprey.cpp +++ b/src/io/ioprey.cpp @@ -21,7 +21,7 @@ PreySlot::PreySlot(PreySlot_t id) : eraseBonus(); reloadBonusValue(); reloadBonusType(); - freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME) * 1000; + freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME, __FUNCTION__) * 1000; } void PreySlot::reloadBonusType() { @@ -55,7 +55,7 @@ void PreySlot::reloadBonusValue() { void PreySlot::reloadMonsterGrid(std::vector blackList, uint32_t level) { raceIdList.clear(); - if (!g_configManager().getBoolean(PREY_ENABLED)) { + if (!g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { return; } @@ -130,13 +130,13 @@ void PreySlot::reloadMonsterGrid(std::vector blackList, uint32_t level // Task hunting class TaskHuntingSlot::TaskHuntingSlot(PreySlot_t id) : id(id) { - freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_FREE_REROLL_TIME) * 1000; + freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_FREE_REROLL_TIME, __FUNCTION__) * 1000; } void TaskHuntingSlot::reloadMonsterGrid(std::vector blackList, uint32_t level) { raceIdList.clear(); - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return; } @@ -209,7 +209,7 @@ void TaskHuntingSlot::reloadMonsterGrid(std::vector blackList, uint32_ } void TaskHuntingSlot::reloadReward() { - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return; } @@ -255,10 +255,10 @@ void IOPrey::checkPlayerPreys(std::shared_ptr player, uint8_t amount) co slot && slot->isOccupied()) { if (slot->bonusTimeLeft <= amount) { if (slot->option == PreyOption_AutomaticReroll) { - if (player->usePreyCards(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE)))) { + if (player->usePreyCards(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE, __FUNCTION__)))) { slot->reloadBonusType(); slot->reloadBonusValue(); - slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME)); + slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME, __FUNCTION__)); player->sendTextMessage(MESSAGE_STATUS, "Your prey bonus type and time has been succesfully reseted."); player->reloadPreySlot(static_cast(slotId)); continue; @@ -266,8 +266,8 @@ void IOPrey::checkPlayerPreys(std::shared_ptr player, uint8_t amount) co player->sendTextMessage(MESSAGE_STATUS, "You don't have enought prey cards to enable automatic reroll when your slot expire."); } else if (slot->option == PreyOption_Locked) { - if (player->usePreyCards(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE)))) { - slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME)); + if (player->usePreyCards(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE, __FUNCTION__)))) { + slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME, __FUNCTION__)); player->sendTextMessage(MESSAGE_STATUS, "Your prey bonus time has been succesfully reseted."); player->reloadPreySlot(static_cast(slotId)); continue; @@ -300,7 +300,7 @@ void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, player->sendMessageDialog("You don't have enought money to reroll the prey slot."); return; } else if (slot->freeRerollTimeStamp <= OTSYS_TIME()) { - slot->freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME) * 1000; + slot->freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(PREY_FREE_REROLL_TIME, __FUNCTION__) * 1000; } slot->eraseBonus(true); @@ -309,7 +309,7 @@ void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, } slot->reloadMonsterGrid(player->getPreyBlackList(), player->getLevel()); } else if (action == PreyAction_ListAll_Cards) { - if (!player->usePreyCards(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE)))) { + if (!player->usePreyCards(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE, __FUNCTION__)))) { player->sendMessageDialog("You don't have enought prey cards to choose a monsters on the list."); return; } @@ -337,19 +337,19 @@ void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, slot->state = PreyDataState_Active; slot->selectedRaceId = raceId; slot->removeMonsterType(raceId); - slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME)); + slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME, __FUNCTION__)); } else if (action == PreyAction_BonusReroll) { if (!slot->isOccupied()) { player->sendMessageDialog("You don't have any active monster on this prey slot."); return; - } else if (!player->usePreyCards(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE)))) { + } else if (!player->usePreyCards(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE, __FUNCTION__)))) { player->sendMessageDialog("You don't have enought prey cards to reroll this prey slot bonus type."); return; } slot->reloadBonusType(); slot->reloadBonusValue(); - slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME)); + slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME, __FUNCTION__)); } else if (action == PreyAction_MonsterSelection) { if (slot->isOccupied()) { player->sendMessageDialog("You already have an active monster on this prey slot."); @@ -369,12 +369,12 @@ void IOPrey::parsePreyAction(std::shared_ptr player, PreySlot_t slotId, slot->state = PreyDataState_Active; slot->selectedRaceId = slot->raceIdList[index]; slot->removeMonsterType(slot->selectedRaceId); - slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME)); + slot->bonusTimeLeft = static_cast(g_configManager().getNumber(PREY_BONUS_TIME, __FUNCTION__)); } else if (action == PreyAction_Option) { - if (option == PreyOption_AutomaticReroll && player->getPreyCards() < static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE))) { + if (option == PreyOption_AutomaticReroll && player->getPreyCards() < static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE, __FUNCTION__))) { player->sendMessageDialog("You don't have enought prey cards to enable automatic reroll when your slot expire."); return; - } else if (option == PreyOption_Locked && player->getPreyCards() < static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE))) { + } else if (option == PreyOption_Locked && player->getPreyCards() < static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE, __FUNCTION__))) { player->sendMessageDialog("You don't have enought prey cards to lock monster and bonus when the slot expire."); return; } @@ -405,7 +405,7 @@ void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t s player->sendMessageDialog("You don't have enought money to reroll the task hunting slot."); return; } else if (slot->freeRerollTimeStamp <= OTSYS_TIME()) { - slot->freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_FREE_REROLL_TIME) * 1000; + slot->freeRerollTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_FREE_REROLL_TIME, __FUNCTION__) * 1000; } slot->eraseTask(); @@ -413,7 +413,7 @@ void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t s slot->state = PreyTaskDataState_Selection; slot->reloadMonsterGrid(player->getTaskHuntingBlackList(), player->getLevel()); } else if (action == PreyTaskAction_RewardsReroll) { - if (!player->usePreyCards(static_cast(g_configManager().getNumber(TASK_HUNTING_BONUS_REROLL_PRICE)))) { + if (!player->usePreyCards(static_cast(g_configManager().getNumber(TASK_HUNTING_BONUS_REROLL_PRICE, __FUNCTION__)))) { player->sendMessageDialog("You don't have enought prey cards to reroll you task reward rarity."); return; } @@ -425,7 +425,7 @@ void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t s ss << "You need to wait " << ((slot->disabledUntilTimeStamp - OTSYS_TIME()) / 60000) << " minutes to select a new creature on task."; player->sendMessageDialog(ss.str()); return; - } else if (!player->usePreyCards(static_cast(g_configManager().getNumber(TASK_HUNTING_SELECTION_LIST_PRICE)))) { + } else if (!player->usePreyCards(static_cast(g_configManager().getNumber(TASK_HUNTING_SELECTION_LIST_PRICE, __FUNCTION__)))) { player->sendMessageDialog("You don't have enought prey cards to choose a creature on list for you task hunting slot."); return; } @@ -512,7 +512,7 @@ void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t s player->addTaskHuntingPoints(reward); player->sendMessageDialog(ss.str()); slot->reloadMonsterGrid(player->getTaskHuntingBlackList(), player->getLevel()); - slot->disabledUntilTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_LIMIT_EXHAUST) * 1000; + slot->disabledUntilTimeStamp = OTSYS_TIME() + g_configManager().getNumber(TASK_HUNTING_LIMIT_EXHAUST, __FUNCTION__) * 1000; } } else { g_logger().warn("[IOPrey::parseTaskHuntingAction] - Unknown task action: {}", fmt::underlying(action)); @@ -522,7 +522,7 @@ void IOPrey::parseTaskHuntingAction(std::shared_ptr player, PreySlot_t s } void IOPrey::initializeTaskHuntOptions() { - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return; } diff --git a/src/items/bed.cpp b/src/items/bed.cpp index 2e0baa9e7..1b1a3a726 100644 --- a/src/items/bed.cpp +++ b/src/items/bed.cpp @@ -236,8 +236,8 @@ void BedItem::regeneratePlayer(std::shared_ptr player) const { regen = sleptTime / 30; } - player->changeHealth(regen * g_configManager().getFloat(RATE_HEALTH_REGEN), false); - player->changeMana(regen * g_configManager().getFloat(RATE_MANA_REGEN)); + player->changeHealth(regen * g_configManager().getFloat(RATE_HEALTH_REGEN, __FUNCTION__), false); + player->changeMana(regen * g_configManager().getFloat(RATE_MANA_REGEN, __FUNCTION__)); } const int32_t soulRegen = sleptTime / (60 * 15); // RATE_SOUL_REGEN_SPEED? diff --git a/src/items/containers/container.cpp b/src/items/containers/container.cpp index af17ce692..cfc77c441 100644 --- a/src/items/containers/container.cpp +++ b/src/items/containers/container.cpp @@ -17,7 +17,7 @@ Container::Container(uint16_t type) : Container(type, items[type].maxItems) { - m_maxItems = static_cast(g_configManager().getNumber(MAX_CONTAINER_ITEM)); + m_maxItems = static_cast(g_configManager().getNumber(MAX_CONTAINER_ITEM, __FUNCTION__)); if (getID() == ITEM_GOLD_POUCH || isStoreInbox()) { pagination = true; m_maxItems = 2000; @@ -476,7 +476,7 @@ ReturnValue Container::queryAdd(int32_t addIndex, const std::shared_ptr & if (std::shared_ptr topParentContainer = getTopParentContainer()) { if (std::shared_ptr addContainer = item->getContainer()) { uint32_t addContainerCount = addContainer->getContainerHoldingCount() + 1; - uint32_t maxContainer = static_cast(g_configManager().getNumber(MAX_CONTAINER)); + uint32_t maxContainer = static_cast(g_configManager().getNumber(MAX_CONTAINER, __FUNCTION__)); if (addContainerCount + topParentContainer->getContainerHoldingCount() > maxContainer) { return RETURNVALUE_CONTAINERISFULL; } diff --git a/src/items/item.hpp b/src/items/item.hpp index b1847b47d..5dce06750 100644 --- a/src/items/item.hpp +++ b/src/items/item.hpp @@ -656,7 +656,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { } auto tier = getAttribute(ItemAttribute_t::TIER); - if (tier > g_configManager().getNumber(FORGE_MAX_ITEM_TIER)) { + if (tier > g_configManager().getNumber(FORGE_MAX_ITEM_TIER, __FUNCTION__)) { g_logger().error("{} - Item {} have a wrong tier {}", __FUNCTION__, getName(), tier); return 0; } @@ -664,7 +664,7 @@ class Item : virtual public Thing, public ItemProperties, public SharedObject { return tier; } void setTier(uint8_t tier) { - auto configTier = g_configManager().getNumber(FORGE_MAX_ITEM_TIER); + auto configTier = g_configManager().getNumber(FORGE_MAX_ITEM_TIER, __FUNCTION__); if (tier > configTier) { g_logger().error("{} - It is not possible to set a tier higher than {}", __FUNCTION__, configTier); return; diff --git a/src/items/items.cpp b/src/items/items.cpp index 690e01a5b..5b4a7419e 100644 --- a/src/items/items.cpp +++ b/src/items/items.cpp @@ -75,7 +75,7 @@ bool Items::reload() { void Items::loadFromProtobuf() { using namespace Canary::protobuf::appearances; - bool supportAnimation = g_configManager().getBoolean(OLD_PROTOCOL); + bool supportAnimation = g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__); for (uint32_t it = 0; it < g_game().appearances.object_size(); ++it) { Appearance object = g_game().appearances.object(it); @@ -192,7 +192,7 @@ void Items::loadFromProtobuf() { bool Items::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/items/items.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/items/items.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); diff --git a/src/items/items.hpp b/src/items/items.hpp index d8b761894..169718019 100644 --- a/src/items/items.hpp +++ b/src/items/items.hpp @@ -66,7 +66,7 @@ struct Abilities { } uint32_t getHealthGain() const { - return healthGain * g_configManager().getFloat(RATE_HEALTH_REGEN); + return healthGain * g_configManager().getFloat(RATE_HEALTH_REGEN, __FUNCTION__); } void setHealthTicks(uint32_t value) { @@ -74,7 +74,7 @@ struct Abilities { } uint32_t getHealthTicks() const { - return healthTicks / g_configManager().getFloat(RATE_HEALTH_REGEN_SPEED); + return healthTicks / g_configManager().getFloat(RATE_HEALTH_REGEN_SPEED, __FUNCTION__); } void setManaGain(uint32_t value) { @@ -82,7 +82,7 @@ struct Abilities { } uint32_t getManaGain() const { - return manaGain * g_configManager().getFloat(RATE_MANA_REGEN); + return manaGain * g_configManager().getFloat(RATE_MANA_REGEN, __FUNCTION__); } void setManaTicks(uint32_t value) { @@ -90,7 +90,7 @@ struct Abilities { } uint32_t getManaTicks() const { - return manaTicks / g_configManager().getFloat(RATE_MANA_REGEN_SPEED); + return manaTicks / g_configManager().getFloat(RATE_MANA_REGEN_SPEED, __FUNCTION__); } private: diff --git a/src/items/tile.cpp b/src/items/tile.cpp index 22c325cfd..787c5ed9b 100644 --- a/src/items/tile.cpp +++ b/src/items/tile.cpp @@ -382,7 +382,7 @@ void Tile::onAddTileItem(std::shared_ptr item) { spectator->onAddTileItem(static_self_cast(), cylinderMapPos); } - if ((!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) + if ((!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES, __FUNCTION__)) && item->isCleanable()) { if (!this->getHouse()) { g_game().addTileToClean(static_self_cast()); @@ -499,7 +499,7 @@ void Tile::onRemoveTileItem(const CreatureVector &spectators, const std::vector< spectator->onRemoveTileItem(static_self_cast(), cylinderMapPos, iType, item); } - if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES)) { + if (!hasFlag(TILESTATE_PROTECTIONZONE) || g_configManager().getBoolean(CLEAN_PROTECTION_ZONES, __FUNCTION__)) { auto items = getItemList(); if (!items || items->empty()) { g_game().removeTileToClean(static_self_cast()); diff --git a/src/items/weapons/weapons.cpp b/src/items/weapons/weapons.cpp index 08f1d75c0..0e5d1e949 100644 --- a/src/items/weapons/weapons.cpp +++ b/src/items/weapons/weapons.cpp @@ -271,14 +271,14 @@ void Weapon::onUsedWeapon(std::shared_ptr player, std::shared_ptr switch (action) { case WEAPONACTION_REMOVECOUNT: - if (g_configManager().getBoolean(REMOVE_WEAPON_AMMO)) { + if (g_configManager().getBoolean(REMOVE_WEAPON_AMMO, __FUNCTION__)) { Weapon::decrementItemCount(item); player->updateSupplyTracker(item); } break; case WEAPONACTION_REMOVECHARGE: { - if (uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES)) { + if (uint16_t charges = item->getCharges() != 0 && g_configManager().getBoolean(REMOVE_WEAPON_CHARGES, __FUNCTION__)) { g_game().transformItem(item, item->getID(), charges - 1); } break; diff --git a/src/lua/creature/actions.cpp b/src/lua/creature/actions.cpp index ba9236976..4ce69aed8 100644 --- a/src/lua/creature/actions.cpp +++ b/src/lua/creature/actions.cpp @@ -407,14 +407,14 @@ bool Actions::useItem(std::shared_ptr player, const Position &pos, uint8 } if (it.isRune() || it.type == ITEM_TYPE_POTION) { - player->setNextPotionAction(OTSYS_TIME() + g_configManager().getNumber(ACTIONS_DELAY_INTERVAL)); + player->setNextPotionAction(OTSYS_TIME() + g_configManager().getNumber(ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } else { - player->setNextAction(OTSYS_TIME() + g_configManager().getNumber(ACTIONS_DELAY_INTERVAL)); + player->setNextAction(OTSYS_TIME() + g_configManager().getNumber(ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } // only send cooldown icon if it's an multi use item if (it.isMultiUse()) { - player->sendUseItemCooldown(g_configManager().getNumber(ACTIONS_DELAY_INTERVAL)); + player->sendUseItemCooldown(g_configManager().getNumber(ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } return true; } @@ -460,13 +460,13 @@ bool Actions::useItemEx(std::shared_ptr player, const Position &fromPos, } if (it.isRune() || it.type == ITEM_TYPE_POTION) { - player->setNextPotionAction(OTSYS_TIME() + g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL)); + player->setNextPotionAction(OTSYS_TIME() + g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } else { - player->setNextAction(OTSYS_TIME() + g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL)); + player->setNextAction(OTSYS_TIME() + g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } if (it.isMultiUse()) { - player->sendUseItemCooldown(g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL)); + player->sendUseItemCooldown(g_configManager().getNumber(EX_ACTIONS_DELAY_INTERVAL, __FUNCTION__)); } return true; } diff --git a/src/lua/creature/events.cpp b/src/lua/creature/events.cpp index 055394214..3ce3f88bd 100644 --- a/src/lua/creature/events.cpp +++ b/src/lua/creature/events.cpp @@ -21,7 +21,7 @@ Events::Events() : bool Events::loadFromXml() { pugi::xml_document doc; - auto folder = g_configManager().getString(CORE_DIRECTORY) + "/events/events.xml"; + auto folder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/events/events.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); @@ -41,7 +41,7 @@ bool Events::loadFromXml() { if (res.second) { const std::string &lowercase = asLowerCaseString(className); const std::string &scriptName = lowercase + ".lua"; - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); if (scriptInterface.loadFile(coreFolder + "/events/scripts/" + scriptName, scriptName) != 0) { g_logger().warn("{} - Can not load script: {}.lua", __FUNCTION__, lowercase); g_logger().warn(scriptInterface.getLastLuaError()); diff --git a/src/lua/creature/raids.cpp b/src/lua/creature/raids.cpp index 1770a7b36..bb0d1f1af 100644 --- a/src/lua/creature/raids.cpp +++ b/src/lua/creature/raids.cpp @@ -26,7 +26,7 @@ bool Raids::loadFromXml() { } pugi::xml_document doc; - auto folder = g_configManager().getString(DATA_DIRECTORY) + "/raids/raids.xml"; + auto folder = g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/raids.xml"; pugi::xml_parse_result result = doc.load_file(folder.c_str()); if (!result) { printXMLError(__FUNCTION__, folder, result); @@ -82,7 +82,7 @@ bool Raids::loadFromXml() { } auto newRaid = std::make_shared(name, interval, margin, repeat); - if (newRaid->loadFromXml(g_configManager().getString(DATA_DIRECTORY) + "/raids/" + file)) { + if (newRaid->loadFromXml(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/" + file)) { raidList.push_back(newRaid); } else { g_logger().error("{} - Failed to load raid: {}", __FUNCTION__, name); @@ -566,7 +566,7 @@ bool ScriptEvent::configureRaidEvent(const pugi::xml_node &eventNode) { std::string scriptName = std::string(scriptAttribute.as_string()); - if (!loadScript(g_configManager().getString(DATA_DIRECTORY) + "/raids/scripts/" + scriptName, scriptName)) { + if (!loadScript(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/raids/scripts/" + scriptName, scriptName)) { g_logger().error("[{}] can not load raid script: {}", __FUNCTION__, scriptName); return false; } diff --git a/src/lua/functions/core/game/bank_functions.cpp b/src/lua/functions/core/game/bank_functions.cpp index 90e4fdecb..f6732b8bf 100644 --- a/src/lua/functions/core/game/bank_functions.cpp +++ b/src/lua/functions/core/game/bank_functions.cpp @@ -7,7 +7,7 @@ int BankFunctions::luaBankCredit(lua_State* L) { // Bank.credit(playerOrGuild, amount) auto bank = getBank(L, 1); if (bank == nullptr) { - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } uint64_t amount = getNumber(L, 2); @@ -19,7 +19,7 @@ int BankFunctions::luaBankDebit(lua_State* L) { // Bank.debit(playerOrGuild, amount) auto bank = getBank(L, 1); if (bank == nullptr) { - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } uint64_t amount = getNumber(L, 2); @@ -31,7 +31,7 @@ int BankFunctions::luaBankBalance(lua_State* L) { // Bank.balance(playerOrGuild[, amount]]) auto bank = getBank(L, 1); if (bank == nullptr) { - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } if (lua_gettop(L) == 1) { @@ -47,7 +47,7 @@ int BankFunctions::luaBankHasBalance(lua_State* L) { // Bank.hasBalance(playerOrGuild, amount) auto bank = getBank(L, 1); if (bank == nullptr) { - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } uint64_t amount = getNumber(L, 2); @@ -60,13 +60,13 @@ int BankFunctions::luaBankTransfer(lua_State* L) { auto source = getBank(L, 1); if (source == nullptr) { g_logger().debug("BankFunctions::luaBankTransfer: source is null"); - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } std::shared_ptr destination = getBank(L, 2); if (destination == nullptr) { g_logger().debug("BankFunctions::luaBankTransfer: destination is null"); - lua_pushnil(L); + reportErrorFunc("Bank is nullptr"); return 1; } uint64_t amount = getNumber(L, 3); @@ -78,12 +78,12 @@ int BankFunctions::luaBankTransferToGuild(lua_State* L) { // Bank.transfer(fromPlayerOrGuild, toGuild, amount) auto source = getBank(L, 1); if (source == nullptr) { - lua_pushnil(L); + reportErrorFunc("Source is nullptr"); return 1; } std::shared_ptr destination = getBank(L, 2, true /* isGuild */); if (destination == nullptr) { - lua_pushnil(L); + reportErrorFunc("Destination is nullptr"); return 1; } uint64_t amount = getNumber(L, 3); @@ -93,20 +93,21 @@ int BankFunctions::luaBankTransferToGuild(lua_State* L) { int BankFunctions::luaBankWithdraw(lua_State* L) { // Bank.withdraw(player, amount[, source = player]) - auto player = getPlayer(L, 1); + const auto &player = getPlayer(L, 1); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + uint64_t amount = getNumber(L, 2); if (lua_gettop(L) == 2) { - if (!player) { - return 1; - } - const auto bank = std::make_shared(player); pushBoolean(L, bank->withdraw(player, amount)); return 1; } auto source = getBank(L, 3); if (source == nullptr) { - lua_pushnil(L); + reportErrorFunc("Source is nullptr"); return 1; } pushBoolean(L, source->withdraw(player, amount)); @@ -115,8 +116,9 @@ int BankFunctions::luaBankWithdraw(lua_State* L) { int BankFunctions::luaBankDeposit(lua_State* L) { // Bank.deposit(player, amount[, destination = player]) - auto player = getPlayer(L, 1); + const auto &player = getPlayer(L, 1); if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; } const auto bank = std::make_shared(player); @@ -134,7 +136,7 @@ int BankFunctions::luaBankDeposit(lua_State* L) { } auto destination = getBank(L, 3); if (destination == nullptr) { - lua_pushnil(L); + reportErrorFunc("Destination is nullptr"); return 1; } pushBoolean(L, g_game().removeMoney(player, amount) && destination->credit(amount)); diff --git a/src/lua/functions/core/game/config_functions.cpp b/src/lua/functions/core/game/config_functions.cpp index 96ce09cdc..cefb26151 100644 --- a/src/lua/functions/core/game/config_functions.cpp +++ b/src/lua/functions/core/game/config_functions.cpp @@ -14,265 +14,68 @@ void ConfigFunctions::init(lua_State* L) { registerTable(L, "configManager"); - registerMethod(L, "configManager", "getString", ConfigFunctions::luaConfigManagerGetString); - registerMethod(L, "configManager", "getNumber", ConfigFunctions::luaConfigManagerGetNumber); - registerMethod(L, "configManager", "getBoolean", ConfigFunctions::luaConfigManagerGetBoolean); - registerMethod(L, "configManager", "getFloat", ConfigFunctions::luaConfigManagerGetFloat); - -#define registerEnumIn(L, tableName, value) \ - do { \ - std::string enumName = #value; \ - registerVariable(L, tableName, enumName.substr(enumName.find_last_of(':') + 1), value); \ + registerMethod(L, "configManager", "getString", luaConfigManagerGetString); + registerMethod(L, "configManager", "getNumber", luaConfigManagerGetNumber); + registerMethod(L, "configManager", "getBoolean", luaConfigManagerGetBoolean); + registerMethod(L, "configManager", "getFloat", luaConfigManagerGetFloat); + +#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) registerTable(L, "configKeys"); - registerEnumIn(L, "configKeys", ALLOW_CHANGEOUTFIT); - registerEnumIn(L, "configKeys", ONE_PLAYER_ON_ACCOUNT); - registerEnumIn(L, "configKeys", AIMBOT_HOTKEY_ENABLED); - registerEnumIn(L, "configKeys", REMOVE_RUNE_CHARGES); - registerEnumIn(L, "configKeys", EXPERIENCE_FROM_PLAYERS); - registerEnumIn(L, "configKeys", FREE_PREMIUM); - registerEnumIn(L, "configKeys", REPLACE_KICK_ON_LOGIN); - registerEnumIn(L, "configKeys", BIND_ONLY_GLOBAL_ADDRESS); - registerEnumIn(L, "configKeys", OPTIMIZE_DATABASE); - registerEnumIn(L, "configKeys", MARKET_PREMIUM); - registerEnumIn(L, "configKeys", EMOTE_SPELLS); - registerEnumIn(L, "configKeys", STAMINA_SYSTEM); - registerEnumIn(L, "configKeys", WARN_UNSAFE_SCRIPTS); - registerEnumIn(L, "configKeys", CONVERT_UNSAFE_SCRIPTS); - registerEnumIn(L, "configKeys", ALLOW_BLOCK_SPAWN); - registerEnumIn(L, "configKeys", CLASSIC_ATTACK_SPEED); - registerEnumIn(L, "configKeys", REMOVE_WEAPON_AMMO); - registerEnumIn(L, "configKeys", REMOVE_WEAPON_CHARGES); - registerEnumIn(L, "configKeys", REMOVE_POTION_CHARGES); - registerEnumIn(L, "configKeys", WEATHER_RAIN); - registerEnumIn(L, "configKeys", ALLOW_RELOAD); - registerEnumIn(L, "configKeys", WEATHER_THUNDER); - registerEnumIn(L, "configKeys", TOGGLE_FREE_QUEST); - registerEnumIn(L, "configKeys", FREE_QUEST_STAGE); - registerEnumIn(L, "configKeys", ALL_CONSOLE_LOG); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_MESSAGE); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_NOTIFY_DURATION); - registerEnumIn(L, "configKeys", XP_DISPLAY_MODE); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLEAN_MAP); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_CLOSE); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_SHUTDOWN); - registerEnumIn(L, "configKeys", MAP_NAME); - registerEnumIn(L, "configKeys", TOGGLE_MAP_CUSTOM); - registerEnumIn(L, "configKeys", MAP_CUSTOM_NAME); - registerEnumIn(L, "configKeys", HOUSE_RENT_PERIOD); - registerEnumIn(L, "configKeys", SERVER_NAME); - registerEnumIn(L, "configKeys", SERVER_MOTD); - registerEnumIn(L, "configKeys", OWNER_NAME); - registerEnumIn(L, "configKeys", OWNER_EMAIL); - registerEnumIn(L, "configKeys", URL); - registerEnumIn(L, "configKeys", LOCATION); - registerEnumIn(L, "configKeys", IP); - registerEnumIn(L, "configKeys", WORLD_TYPE); - registerEnumIn(L, "configKeys", MYSQL_HOST); - registerEnumIn(L, "configKeys", MYSQL_USER); - registerEnumIn(L, "configKeys", MYSQL_PASS); - registerEnumIn(L, "configKeys", MYSQL_DB); - registerEnumIn(L, "configKeys", MYSQL_SOCK); - registerEnumIn(L, "configKeys", DEFAULT_PRIORITY); - registerEnumIn(L, "configKeys", MAP_AUTHOR); - registerEnumIn(L, "configKeys", STORE_IMAGES_URL); - registerEnumIn(L, "configKeys", PARTY_LIST_MAX_DISTANCE); - registerEnumIn(L, "configKeys", SQL_PORT); - registerEnumIn(L, "configKeys", MAX_PLAYERS); - registerEnumIn(L, "configKeys", PZ_LOCKED); - registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRANGE); - registerEnumIn(L, "configKeys", PREY_ENABLED); - registerEnumIn(L, "configKeys", PREY_FREE_THIRD_SLOT); - registerEnumIn(L, "configKeys", PREY_REROLL_PRICE_LEVEL); - registerEnumIn(L, "configKeys", PREY_BONUS_TIME); - registerEnumIn(L, "configKeys", PREY_BONUS_REROLL_PRICE); - registerEnumIn(L, "configKeys", PREY_FREE_REROLL_TIME); - registerEnumIn(L, "configKeys", TASK_HUNTING_ENABLED); - registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_THIRD_SLOT); - registerEnumIn(L, "configKeys", TASK_HUNTING_LIMIT_EXHAUST); - registerEnumIn(L, "configKeys", TASK_HUNTING_REROLL_PRICE_LEVEL); - registerEnumIn(L, "configKeys", TASK_HUNTING_SELECTION_LIST_PRICE); - registerEnumIn(L, "configKeys", TASK_HUNTING_BONUS_REROLL_PRICE); - registerEnumIn(L, "configKeys", TASK_HUNTING_FREE_REROLL_TIME); - registerEnumIn(L, "configKeys", DEFAULT_DESPAWNRADIUS); - registerEnumIn(L, "configKeys", RATE_EXPERIENCE); - registerEnumIn(L, "configKeys", RATE_SKILL); - registerEnumIn(L, "configKeys", RATE_LOOT); - registerEnumIn(L, "configKeys", RATE_MAGIC); - registerEnumIn(L, "configKeys", RATE_SPAWN); - registerEnumIn(L, "configKeys", RATE_KILLING_IN_THE_NAME_OF_POINTS); - registerEnumIn(L, "configKeys", HOUSE_PRICE_PER_SQM); - registerEnumIn(L, "configKeys", HOUSE_BUY_LEVEL); - registerEnumIn(L, "configKeys", HOUSE_LOSE_AFTER_INACTIVITY); - registerEnumIn(L, "configKeys", MAX_MESSAGEBUFFER); - registerEnumIn(L, "configKeys", ACTIONS_DELAY_INTERVAL); - registerEnumIn(L, "configKeys", EX_ACTIONS_DELAY_INTERVAL); - registerEnumIn(L, "configKeys", KICK_AFTER_MINUTES); - registerEnumIn(L, "configKeys", PROTECTION_LEVEL); - registerEnumIn(L, "configKeys", DEATH_LOSE_PERCENT); - registerEnumIn(L, "configKeys", STATUSQUERY_TIMEOUT); - registerEnumIn(L, "configKeys", FRAG_TIME); - registerEnumIn(L, "configKeys", WHITE_SKULL_TIME); - registerEnumIn(L, "configKeys", GAME_PORT); - registerEnumIn(L, "configKeys", LOGIN_PORT); - registerEnumIn(L, "configKeys", STATUS_PORT); - registerEnumIn(L, "configKeys", STAIRHOP_DELAY); - registerEnumIn(L, "configKeys", MARKET_OFFER_DURATION); - registerEnumIn(L, "configKeys", CHECK_EXPIRED_MARKET_OFFERS_EACH_MINUTES); - registerEnumIn(L, "configKeys", MAX_MARKET_OFFERS_AT_A_TIME_PER_PLAYER); - registerEnumIn(L, "configKeys", EXP_FROM_PLAYERS_LEVEL_RANGE); - registerEnumIn(L, "configKeys", MAX_PACKETS_PER_SECOND); - registerEnumIn(L, "configKeys", STORE_COIN_PACKET); - registerEnumIn(L, "configKeys", DAY_KILLS_TO_RED); - registerEnumIn(L, "configKeys", WEEK_KILLS_TO_RED); - registerEnumIn(L, "configKeys", MONTH_KILLS_TO_RED); - registerEnumIn(L, "configKeys", RED_SKULL_DURATION); - registerEnumIn(L, "configKeys", BLACK_SKULL_DURATION); - registerEnumIn(L, "configKeys", ORANGE_SKULL_DURATION); - registerEnumIn(L, "configKeys", RATE_MONSTER_HEALTH); - registerEnumIn(L, "configKeys", RATE_MONSTER_ATTACK); - registerEnumIn(L, "configKeys", RATE_MONSTER_DEFENSE); - registerEnumIn(L, "configKeys", RATE_BOSS_HEALTH); - registerEnumIn(L, "configKeys", RATE_BOSS_ATTACK); - registerEnumIn(L, "configKeys", RATE_BOSS_DEFENSE); - registerEnumIn(L, "configKeys", BOSS_DEFAULT_TIME_TO_FIGHT_AGAIN); - registerEnumIn(L, "configKeys", BOSS_DEFAULT_TIME_TO_DEFEAT); - registerEnumIn(L, "configKeys", RATE_NPC_HEALTH); - registerEnumIn(L, "configKeys", RATE_NPC_ATTACK); - registerEnumIn(L, "configKeys", RATE_NPC_DEFENSE); - - registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN); - registerEnumIn(L, "configKeys", RATE_HEALTH_REGEN_SPEED); - registerEnumIn(L, "configKeys", RATE_MANA_REGEN); - registerEnumIn(L, "configKeys", RATE_MANA_REGEN_SPEED); - registerEnumIn(L, "configKeys", RATE_SOUL_REGEN); - registerEnumIn(L, "configKeys", RATE_SOUL_REGEN_SPEED); - - registerEnumIn(L, "configKeys", RATE_SPELL_COOLDOWN); - registerEnumIn(L, "configKeys", RATE_ATTACK_SPEED); - registerEnumIn(L, "configKeys", RATE_OFFLINE_TRAINING_SPEED); - registerEnumIn(L, "configKeys", RATE_EXERCISE_TRAINING_SPEED); - - registerEnumIn(L, "configKeys", STAMINA_TRAINER); - registerEnumIn(L, "configKeys", STAMINA_PZ); - registerEnumIn(L, "configKeys", STAMINA_ORANGE_DELAY); - registerEnumIn(L, "configKeys", STAMINA_GREEN_DELAY); - registerEnumIn(L, "configKeys", STAMINA_TRAINER_DELAY); - registerEnumIn(L, "configKeys", STAMINA_PZ_GAIN); - registerEnumIn(L, "configKeys", STAMINA_TRAINER_GAIN); - registerEnumIn(L, "configKeys", SORT_LOOT_BY_CHANCE); - registerEnumIn(L, "configKeys", MAX_ALLOWED_ON_A_DUMMY); - - registerEnumIn(L, "configKeys", PUSH_WHEN_ATTACKING); - registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL); - registerEnumIn(L, "configKeys", SAVE_INTERVAL_TYPE); - registerEnumIn(L, "configKeys", TOGGLE_SAVE_INTERVAL_CLEAN_MAP); - registerEnumIn(L, "configKeys", SAVE_INTERVAL_TIME); - registerEnumIn(L, "configKeys", RATE_USE_STAGES); - registerEnumIn(L, "configKeys", TOGGLE_IMBUEMENT_SHRINE_STORAGE); - registerEnumIn(L, "configKeys", TOGGLE_IMBUEMENT_NON_AGGRESSIVE_FIGHT_ONLY); - registerEnumIn(L, "configKeys", GLOBAL_SERVER_SAVE_TIME); - registerEnumIn(L, "configKeys", DATA_DIRECTORY); - registerEnumIn(L, "configKeys", CORE_DIRECTORY); - - registerEnumIn(L, "configKeys", FORGE_COST_ONE_SLIVER); - registerEnumIn(L, "configKeys", FORGE_SLIVER_AMOUNT); - registerEnumIn(L, "configKeys", FORGE_CORE_COST); - registerEnumIn(L, "configKeys", FORGE_MAX_DUST); - registerEnumIn(L, "configKeys", FORGE_FUSION_DUST_COST); - registerEnumIn(L, "configKeys", FORGE_TRANSFER_DUST_COST); - registerEnumIn(L, "configKeys", FORGE_BASE_SUCCESS_RATE); - registerEnumIn(L, "configKeys", FORGE_BONUS_SUCCESS_RATE); - registerEnumIn(L, "configKeys", FORGE_TIER_LOSS_REDUCTION); - registerEnumIn(L, "configKeys", FORGE_AMOUNT_MULTIPLIER); - registerEnumIn(L, "configKeys", FORGE_INFLUENCED_CREATURES_LIMIT); - - registerEnumIn(L, "configKeys", BESTIARY_KILL_MULTIPLIER); - registerEnumIn(L, "configKeys", BOSSTIARY_KILL_MULTIPLIER); - registerEnumIn(L, "configKeys", BOOSTED_BOSS_SLOT); - registerEnumIn(L, "configKeys", BOOSTED_BOSS_LOOT_BONUS); - registerEnumIn(L, "configKeys", BOOSTED_BOSS_KILL_BONUS); - registerEnumIn(L, "configKeys", BESTIARY_RATE_CHARM_SHOP_PRICE); - - registerEnumIn(L, "configKeys", FAMILIAR_TIME); - - registerEnumIn(L, "configKeys", TOGGLE_GOLD_POUCH_ALLOW_ANYTHING); - registerEnumIn(L, "configKeys", TOGGLE_SERVER_IS_RETRO); - registerEnumIn(L, "configKeys", TOGGLE_TRAVELS_FREE); - registerEnumIn(L, "configKeys", BUY_AOL_COMMAND_FEE); - registerEnumIn(L, "configKeys", BUY_BLESS_COMMAND_FEE); - registerEnumIn(L, "configKeys", TELEPORT_PLAYER_TO_VOCATION_ROOM); - - registerEnumIn(L, "configKeys", HAZARD_SPAWN_PLUNDER_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_CRITICAL_INTERVAL); - registerEnumIn(L, "configKeys", HAZARD_CRITICAL_CHANCE); - registerEnumIn(L, "configKeys", HAZARD_CRITICAL_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_DAMAGE_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_DODGE_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_PODS_DROP_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_PODS_TIME_TO_DAMAGE); - registerEnumIn(L, "configKeys", HAZARD_PODS_TIME_TO_SPAWN); - registerEnumIn(L, "configKeys", HAZARD_EXP_BONUS_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_LOOT_BONUS_MULTIPLIER); - registerEnumIn(L, "configKeys", HAZARD_PODS_DAMAGE); - registerEnumIn(L, "configKeys", TOGGLE_HAZARDSYSTEM); - registerEnumIn(L, "configKeys", LOW_LEVEL_BONUS_EXP); - - registerEnumIn(L, "configKeys", LOYALTY_ENABLED); - registerEnumIn(L, "configKeys", LOYALTY_POINTS_PER_CREATION_DAY); - registerEnumIn(L, "configKeys", LOYALTY_POINTS_PER_PREMIUM_DAY_SPENT); - registerEnumIn(L, "configKeys", LOYALTY_POINTS_PER_PREMIUM_DAY_PURCHASED); - registerEnumIn(L, "configKeys", LOYALTY_BONUS_PERCENTAGE_MULTIPLIER); - - registerEnumIn(L, "configKeys", PARTY_SHARE_LOOT_BOOSTS); - registerEnumIn(L, "configKeys", PARTY_SHARE_LOOT_BOOSTS_DIMINISHING_FACTOR); - registerEnumIn(L, "configKeys", TIBIADROME_CONCOCTION_COOLDOWN); - registerEnumIn(L, "configKeys", TIBIADROME_CONCOCTION_DURATION); - registerEnumIn(L, "configKeys", TIBIADROME_CONCOCTION_TICK_TYPE); - - registerEnumIn(L, "configKeys", AUTH_TYPE); - registerEnumIn(L, "configKeys", RESET_SESSIONS_ON_STARTUP); - - registerEnumIn(L, "configKeys", TOGGLE_ATTACK_SPEED_ONFIST); - registerEnumIn(L, "configKeys", MULTIPLIER_ATTACKONFIST); - registerEnumIn(L, "configKeys", MAX_SPEED_ATTACKONFIST); - - registerEnumIn(L, "configKeys", M_CONST); - registerEnumIn(L, "configKeys", T_CONST); - registerEnumIn(L, "configKeys", PARALLELISM); - - registerEnumIn(L, "configKeys", AUTOLOOT); - - registerEnumIn(L, "configKeys", VIP_SYSTEM_ENABLED); - registerEnumIn(L, "configKeys", VIP_BONUS_EXP); - registerEnumIn(L, "configKeys", VIP_BONUS_LOOT); - registerEnumIn(L, "configKeys", VIP_BONUS_SKILL); - registerEnumIn(L, "configKeys", VIP_AUTOLOOT_VIP_ONLY); - registerEnumIn(L, "configKeys", VIP_STAY_ONLINE); - registerEnumIn(L, "configKeys", VIP_FAMILIAR_TIME_COOLDOWN_REDUCTION); - - registerEnumIn(L, "configKeys", TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); - - registerEnumIn(L, "configKeys", TOGGLE_RECEIVE_REWARD); -#undef registerEnumIn + for (auto value : magic_enum::enum_values()) { + auto enumName = magic_enum::enum_name(value).data(); + if (enumName) { + registerMagicEnumIn(L, "configKeys", value); + g_logger().debug("Registering ConfigManager enum name '{}' value '{}' to lua", enumName, fmt::underlying(value)); + } + } +#undef registerMagicEnumIn } int ConfigFunctions::luaConfigManagerGetString(lua_State* L) { - pushString(L, g_configManager().getString(getNumber(L, -1))); + auto key = getNumber(L, -1); + if (!key) { + reportErrorFunc("Wrong enum"); + return 1; + } + + pushString(L, g_configManager().getString(getNumber(L, -1), __FUNCTION__)); return 1; } int ConfigFunctions::luaConfigManagerGetNumber(lua_State* L) { - lua_pushnumber(L, g_configManager().getNumber(getNumber(L, -1))); + auto key = getNumber(L, -1); + if (!key) { + reportErrorFunc("Wrong enum"); + return 1; + } + + lua_pushnumber(L, g_configManager().getNumber(getNumber(L, -1), __FUNCTION__)); return 1; } int ConfigFunctions::luaConfigManagerGetBoolean(lua_State* L) { - pushBoolean(L, g_configManager().getBoolean(getNumber(L, -1))); + auto key = getNumber(L, -1); + if (!key) { + reportErrorFunc("Wrong enum"); + return 1; + } + + pushBoolean(L, g_configManager().getBoolean(getNumber(L, -1), __FUNCTION__)); return 1; } int ConfigFunctions::luaConfigManagerGetFloat(lua_State* L) { - lua_pushnumber(L, g_configManager().getFloat(getNumber(L, -1))); + auto key = getNumber(L, -1); + if (!key) { + reportErrorFunc("Wrong enum"); + return 1; + } + + lua_pushnumber(L, g_configManager().getFloat(key, __FUNCTION__)); return 1; } diff --git a/src/lua/functions/core/game/global_functions.cpp b/src/lua/functions/core/game/global_functions.cpp index 7abf3b2c6..e2961e262 100644 --- a/src/lua/functions/core/game/global_functions.cpp +++ b/src/lua/functions/core/game/global_functions.cpp @@ -592,7 +592,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { return 1; } - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) || g_configManager().getBoolean(CONVERT_UNSAFE_SCRIPTS)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) || g_configManager().getBoolean(CONVERT_UNSAFE_SCRIPTS, __FUNCTION__)) { std::vector> indexes; for (int i = 3; i <= parameters; ++i) { if (lua_getmetatable(globalState, i) == 0) { @@ -608,7 +608,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { } if (!indexes.empty()) { - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__)) { bool plural = indexes.size() > 1; std::string warningString = "Argument"; @@ -637,7 +637,7 @@ int GlobalFunctions::luaAddEvent(lua_State* L) { reportErrorFunc(warningString); } - if (g_configManager().getBoolean(CONVERT_UNSAFE_SCRIPTS)) { + if (g_configManager().getBoolean(CONVERT_UNSAFE_SCRIPTS, __FUNCTION__)) { for (const auto &entry : indexes) { switch (entry.second) { case LuaData_t::Item: @@ -741,16 +741,16 @@ int GlobalFunctions::luaDebugPrint(lua_State* L) { int GlobalFunctions::luaIsInWar(lua_State* L) { // isInWar(cid, target) - std::shared_ptr player = getPlayer(L, 1); + const auto &player = getPlayer(L, 1); if (!player) { - reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + reportErrorFunc(fmt::format("{} - Player", getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND))); pushBoolean(L, false); return 1; } - std::shared_ptr targetPlayer = getPlayer(L, 2); + const auto &targetPlayer = getPlayer(L, 2); if (!targetPlayer) { - reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + reportErrorFunc(fmt::format("{} - TargetPlayer", getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND))); pushBoolean(L, false); return 1; } diff --git a/src/lua/functions/core/game/lua_enums.cpp b/src/lua/functions/core/game/lua_enums.cpp index f462aaae2..5d566920c 100644 --- a/src/lua/functions/core/game/lua_enums.cpp +++ b/src/lua/functions/core/game/lua_enums.cpp @@ -18,7 +18,7 @@ #include "declarations.hpp" #include "game/functions/game_reload.hpp" -#define registerEnumClass(luaState, enumClassType) \ +#define registerMagicEnum(luaState, enumClassType) \ { \ auto number = magic_enum::enum_integer(enumClassType); \ auto name = magic_enum::enum_name(enumClassType).data(); \ @@ -26,7 +26,7 @@ } \ void(0) -#define registerEnumClassNamespace(luaState, luaNamespace, enumClassType) \ +#define registerMagicEnumNamespace(luaState, luaNamespace, enumClassType) \ { \ auto number = magic_enum::enum_integer(enumClassType); \ auto name = std::string(luaNamespace) + magic_enum::enum_name(enumClassType).data(); \ @@ -277,7 +277,7 @@ void LuaEnums::initCombatEnums(lua_State* L) { void LuaEnums::initCombatParamEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } @@ -443,7 +443,7 @@ void LuaEnums::initConditionParamEnums(lua_State* L) { void LuaEnums::initAttributeConditionSubIdEnums(lua_State* L) { std::string luaNamespace = "AttrSubId_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, luaNamespace, value); + registerMagicEnumNamespace(L, luaNamespace, value); } } @@ -849,7 +849,7 @@ void LuaEnums::initItemTypeEnums(lua_State* L) { void LuaEnums::initFluidEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } @@ -920,22 +920,22 @@ void LuaEnums::initItemIdEnums(lua_State* L) { void LuaEnums::initPlayerFlagEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } void LuaEnums::initCreatureIconEnums(lua_State* L) { std::string luaNamespace = "CreatureIconCategory_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, luaNamespace, value); + registerMagicEnumNamespace(L, luaNamespace, value); } luaNamespace = "CreatureIconModifications_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, luaNamespace, value); + registerMagicEnumNamespace(L, luaNamespace, value); } luaNamespace = "CreatureIconQuests_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, luaNamespace, value); + registerMagicEnumNamespace(L, luaNamespace, value); } } @@ -1205,7 +1205,7 @@ void LuaEnums::initReturnValueEnums(lua_State* L) { // Reload void LuaEnums::initReloadTypeEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } @@ -1231,7 +1231,7 @@ void LuaEnums::initCreaturesEventEnums(lua_State* L) { void LuaEnums::initForgeEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } @@ -1245,7 +1245,7 @@ void LuaEnums::initWebhookEnums(lua_State* L) { void LuaEnums::initBosstiaryEnums(lua_State* L) { for (auto value : magic_enum::enum_values()) { - registerEnumClass(L, value); + registerMagicEnum(L, value); } } @@ -1769,30 +1769,30 @@ void LuaEnums::initSoundEnums(lua_State* L) { void LuaEnums::initWheelEnums(lua_State* L) { std::string wheelNamespace = "WHEEL_INSTANT_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_STAGE_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_GRADE_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_AVATAR_SKILL_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_STAT_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } wheelNamespace = "WHEEL_BOOST_"; for (auto value : magic_enum::enum_values()) { - registerEnumClassNamespace(L, wheelNamespace, value); + registerMagicEnumNamespace(L, wheelNamespace, value); } } diff --git a/src/lua/functions/core/game/modal_window_functions.cpp b/src/lua/functions/core/game/modal_window_functions.cpp index 11441993f..ee2cb7bd8 100644 --- a/src/lua/functions/core/game/modal_window_functions.cpp +++ b/src/lua/functions/core/game/modal_window_functions.cpp @@ -204,9 +204,9 @@ int ModalWindowFunctions::luaModalWindowSetPriority(lua_State* L) { int ModalWindowFunctions::luaModalWindowSendToPlayer(lua_State* L) { // modalWindow:sendToPlayer(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { - lua_pushnil(L); + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; } diff --git a/src/lua/functions/core/network/network_message_functions.cpp b/src/lua/functions/core/network/network_message_functions.cpp index a0f02631a..61567b1e1 100644 --- a/src/lua/functions/core/network/network_message_functions.cpp +++ b/src/lua/functions/core/network/network_message_functions.cpp @@ -289,12 +289,12 @@ int NetworkMessageFunctions::luaNetworkMessageSendToPlayer(lua_State* L) { } const auto &player = getPlayer(L, 2); - if (player) { - player->sendNetworkMessage(*message); - pushBoolean(L, true); - } else { + if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); - lua_pushnil(L); + return 1; } + + player->sendNetworkMessage(*message); + pushBoolean(L, true); return 1; } diff --git a/src/lua/functions/creatures/creature_functions.cpp b/src/lua/functions/creatures/creature_functions.cpp index c5221a9c3..5965adb7f 100644 --- a/src/lua/functions/creatures/creature_functions.cpp +++ b/src/lua/functions/creatures/creature_functions.cpp @@ -620,7 +620,7 @@ int CreatureFunctions::luaCreatureSetOutfit(lua_State* L) { std::shared_ptr creature = getUserdataShared(L, 1); if (creature) { Outfit_t outfit = getOutfit(L, 2); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { g_logger().warn("[CreatureFunctions::luaCreatureSetOutfit] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); return 1; } diff --git a/src/lua/functions/creatures/monster/monster_functions.cpp b/src/lua/functions/creatures/monster/monster_functions.cpp index e0f702f24..5e32115a2 100644 --- a/src/lua/functions/creatures/monster/monster_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_functions.cpp @@ -15,6 +15,7 @@ #include "creatures/monsters/monsters.hpp" #include "lua/functions/creatures/monster/monster_functions.hpp" #include "map/spectators.hpp" +#include "game/scheduling/events_scheduler.hpp" int MonsterFunctions::luaMonsterCreate(lua_State* L) { // Monster(id or userdata) @@ -350,19 +351,22 @@ int MonsterFunctions::luaMonsterSearchTarget(lua_State* L) { } int MonsterFunctions::luaMonsterSetSpawnPosition(lua_State* L) { - // monster:setSpawnPosition() + // monster:setSpawnPosition(interval) std::shared_ptr monster = getUserdataShared(L, 1); if (!monster) { lua_pushnil(L); return 1; } + uint32_t eventschedule = g_eventsScheduler().getSpawnMonsterSchedule(); + const Position &pos = monster->getPosition(); monster->setMasterPos(pos); g_game().map.spawnsMonster.getspawnMonsterList().emplace_front(pos, 5); SpawnMonster &spawnMonster = g_game().map.spawnsMonster.getspawnMonsterList().front(); - spawnMonster.addMonster(monster->mType->name, pos, DIRECTION_NORTH, 60000); + uint32_t interval = getNumber(L, 2, 90) * 1000 * 100 / std::max((uint32_t)1, (g_configManager().getNumber(RATE_SPAWN, __FUNCTION__) * eventschedule)); + spawnMonster.addMonster(monster->mType->typeName, pos, DIRECTION_NORTH, static_cast(interval)); spawnMonster.startSpawnMonsterCheck(); pushBoolean(L, true); diff --git a/src/lua/functions/creatures/monster/monster_type_functions.cpp b/src/lua/functions/creatures/monster/monster_type_functions.cpp index 146ee7b1a..edaa77b28 100644 --- a/src/lua/functions/creatures/monster/monster_type_functions.cpp +++ b/src/lua/functions/creatures/monster/monster_type_functions.cpp @@ -1159,7 +1159,7 @@ int MonsterTypeFunctions::luaMonsterTypeOutfit(lua_State* L) { pushOutfit(L, monsterType->info.outfit); } else { Outfit_t outfit = getOutfit(L, 2); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { g_logger().warn("[MonsterTypeFunctions::luaMonsterTypeOutfit] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); lua_pushnil(L); } else { diff --git a/src/lua/functions/creatures/npc/npc_functions.cpp b/src/lua/functions/creatures/npc/npc_functions.cpp index e0ae3c2bf..0df0b5504 100644 --- a/src/lua/functions/creatures/npc/npc_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_functions.cpp @@ -347,20 +347,74 @@ int NpcFunctions::luaNpcOpenShopWindow(lua_State* L) { return 1; } - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); return 1; } + npc->addShopPlayer(player); + pushBoolean(L, player->openShopWindow(npc)); + return 1; +} + +int NpcFunctions::luaNpcOpenShopWindowTable(lua_State* L) { + // npc:openShopWindowTable(player, items) + const auto &npc = getUserdataShared(L, 1); + if (!npc) { + reportErrorFunc(getErrorDesc(LUA_ERROR_NPC_NOT_FOUND)); + pushBoolean(L, false); + return 1; + } + + const auto &player = getUserdataShared(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + + if (lua_istable(L, 3) == 0) { + reportError(__FUNCTION__, "item list is not a table."); + pushBoolean(L, false); + return 1; + } + + std::vector items; + lua_pushnil(L); + while (lua_next(L, 3) != 0) { + const auto tableIndex = lua_gettop(L); + ShopBlock item; + + auto itemId = getField(L, tableIndex, "clientId"); + auto subType = getField(L, tableIndex, "subType"); + if (subType == 0) { + subType = getField(L, tableIndex, "subtype"); + lua_pop(L, 1); + } + + auto buyPrice = getField(L, tableIndex, "buy"); + auto sellPrice = getField(L, tableIndex, "sell"); + auto storageKey = getField(L, tableIndex, "storageKey"); + auto storageValue = getField(L, tableIndex, "storageValue"); + auto realName = getFieldString(L, tableIndex, "name"); + g_logger().debug("[{}] item '{}' sell price '{}', buyprice '{}'", __FUNCTION__, realName, sellPrice, buyPrice); + + items.emplace_back(itemId, subType, buyPrice, sellPrice, storageKey, storageValue, std::move(realName)); + lua_pop(L, 8); + } + lua_pop(L, 3); + + // Close any eventual other shop window currently open. + player->closeShopWindow(true); + npc->addShopPlayer(player, items); pushBoolean(L, player->openShopWindow(npc)); return 1; } int NpcFunctions::luaNpcCloseShopWindow(lua_State* L) { // npc:closeShopWindow(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -391,8 +445,8 @@ int NpcFunctions::luaNpcIsMerchant(lua_State* L) { return 1; } - const std::vector shopItems = npc->getShopItemVector(); - + auto playerGUID = getNumber(L, 2, 0); + const auto &shopItems = npc->getShopItemVector(playerGUID); if (shopItems.empty()) { pushBoolean(L, false); return 1; @@ -411,8 +465,9 @@ int NpcFunctions::luaNpcGetShopItem(lua_State* L) { return 1; } - const std::vector &shopVector = npc->getShopItemVector(); - for (ShopBlock shopBlock : shopVector) { + auto playerGUID = getNumber(L, 2, 0); + const auto &shopItems = npc->getShopItemVector(playerGUID); + for (ShopBlock shopBlock : shopItems) { setField(L, "id", shopBlock.itemId); setField(L, "name", shopBlock.itemName); setField(L, "subType", shopBlock.itemSubType); @@ -452,7 +507,13 @@ int NpcFunctions::luaNpcFollow(lua_State* L) { return 1; } - pushBoolean(L, npc->setFollowCreature(getPlayer(L, 2))); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + + pushBoolean(L, npc->setFollowCreature(player)); return 1; } @@ -478,7 +539,7 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { return 1; } - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); pushBoolean(L, false); @@ -516,7 +577,7 @@ int NpcFunctions::luaNpcSellItem(lua_State* L) { } uint64_t pricePerUnit = 0; - const std::vector &shopVector = npc->getShopItemVector(); + const std::vector &shopVector = npc->getShopItemVector(player->getGUID()); for (ShopBlock shopBlock : shopVector) { if (itemId == shopBlock.itemId && shopBlock.itemBuyPrice != 0) { pricePerUnit = shopBlock.itemBuyPrice; diff --git a/src/lua/functions/creatures/npc/npc_functions.hpp b/src/lua/functions/creatures/npc/npc_functions.hpp index 7671780e7..ef3371a54 100644 --- a/src/lua/functions/creatures/npc/npc_functions.hpp +++ b/src/lua/functions/creatures/npc/npc_functions.hpp @@ -36,6 +36,7 @@ class NpcFunctions final : LuaScriptInterface { registerMethod(L, "Npc", "isInTalkRange", NpcFunctions::luaNpcIsInTalkRange); registerMethod(L, "Npc", "isPlayerInteractingOnTopic", NpcFunctions::luaNpcIsPlayerInteractingOnTopic); registerMethod(L, "Npc", "openShopWindow", NpcFunctions::luaNpcOpenShopWindow); + registerMethod(L, "Npc", "openShopWindowTable", NpcFunctions::luaNpcOpenShopWindowTable); registerMethod(L, "Npc", "closeShopWindow", NpcFunctions::luaNpcCloseShopWindow); registerMethod(L, "Npc", "getShopItem", NpcFunctions::luaNpcGetShopItem); registerMethod(L, "Npc", "isMerchant", NpcFunctions::luaNpcIsMerchant); @@ -73,6 +74,7 @@ class NpcFunctions final : LuaScriptInterface { static int luaNpcIsInTalkRange(lua_State* L); static int luaNpcIsPlayerInteractingOnTopic(lua_State* L); static int luaNpcOpenShopWindow(lua_State* L); + static int luaNpcOpenShopWindowTable(lua_State* L); static int luaNpcCloseShopWindow(lua_State* L); static int luaNpcGetShopItem(lua_State* L); static int luaNpcIsMerchant(lua_State* L); diff --git a/src/lua/functions/creatures/npc/npc_type_functions.cpp b/src/lua/functions/creatures/npc/npc_type_functions.cpp index f38032e4a..8c2fb604f 100644 --- a/src/lua/functions/creatures/npc/npc_type_functions.cpp +++ b/src/lua/functions/creatures/npc/npc_type_functions.cpp @@ -308,7 +308,7 @@ int NpcTypeFunctions::luaNpcTypeOutfit(lua_State* L) { pushOutfit(L, npcType->info.outfit); } else { Outfit_t outfit = getOutfit(L, 2); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && outfit.lookType != 0 && !g_game().isLookTypeRegistered(outfit.lookType)) { g_logger().warn("[NpcTypeFunctions::luaNpcTypeOutfit] An unregistered creature looktype type with id '{}' was blocked to prevent client crash.", outfit.lookType); lua_pushnil(L); } else { diff --git a/src/lua/functions/creatures/player/party_functions.cpp b/src/lua/functions/creatures/player/party_functions.cpp index 6b5872d83..e16499870 100644 --- a/src/lua/functions/creatures/player/party_functions.cpp +++ b/src/lua/functions/creatures/player/party_functions.cpp @@ -69,9 +69,14 @@ int PartyFunctions::luaPartyGetLeader(lua_State* L) { int PartyFunctions::luaPartySetLeader(lua_State* L) { // party:setLeader(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + std::shared_ptr party = getUserdataShared(L, 1); - if (party && player) { + if (party) { pushBoolean(L, party->passPartyLeadership(player)); } else { lua_pushnil(L); @@ -139,7 +144,12 @@ int PartyFunctions::luaPartyGetInviteeCount(lua_State* L) { int PartyFunctions::luaPartyAddInvite(lua_State* L) { // party:addInvite(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + std::shared_ptr party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->invitePlayer(player)); @@ -151,7 +161,12 @@ int PartyFunctions::luaPartyAddInvite(lua_State* L) { int PartyFunctions::luaPartyRemoveInvite(lua_State* L) { // party:removeInvite(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + std::shared_ptr party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->removeInvite(player)); @@ -163,7 +178,12 @@ int PartyFunctions::luaPartyRemoveInvite(lua_State* L) { int PartyFunctions::luaPartyAddMember(lua_State* L) { // party:addMember(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + std::shared_ptr party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->joinParty(player)); @@ -175,7 +195,12 @@ int PartyFunctions::luaPartyAddMember(lua_State* L) { int PartyFunctions::luaPartyRemoveMember(lua_State* L) { // party:removeMember(player) - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } + std::shared_ptr party = getUserdataShared(L, 1); if (party && player) { pushBoolean(L, party->leaveParty(player)); diff --git a/src/lua/functions/creatures/player/player_functions.cpp b/src/lua/functions/creatures/player/player_functions.cpp index 7c8934b45..5b646264d 100644 --- a/src/lua/functions/creatures/player/player_functions.cpp +++ b/src/lua/functions/creatures/player/player_functions.cpp @@ -983,16 +983,17 @@ int PlayerFunctions::luaPlayerGetMaxMana(lua_State* L) { int PlayerFunctions::luaPlayerSetMaxMana(lua_State* L) { // player:setMaxMana(maxMana) - std::shared_ptr player = getPlayer(L, 1); - if (player) { - player->manaMax = getNumber(L, 2); - player->mana = std::min(player->mana, player->manaMax); - g_game().addPlayerMana(player); - player->sendStats(); - pushBoolean(L, true); - } else { - lua_pushnil(L); + const auto &player = getPlayer(L, 1); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; } + + player->manaMax = getNumber(L, 2); + player->mana = std::min(player->mana, player->manaMax); + g_game().addPlayerMana(player); + player->sendStats(); + pushBoolean(L, true); return 1; } @@ -3877,7 +3878,7 @@ int PlayerFunctions::luaPlayerUpgradeSpellWOD(lua_State* L) { } int PlayerFunctions::luaPlayerRevelationStageWOD(lua_State* L) { - // player:revelationStagesWOD([name[, set]]) + // player:revelationStageWOD([name[, set]]) std::shared_ptr player = getUserdataShared(L, 1); if (!player) { lua_pushnil(L); diff --git a/src/lua/functions/lua_functions_loader.cpp b/src/lua/functions/lua_functions_loader.cpp index bdf7dbb37..ae812e2cc 100644 --- a/src/lua/functions/lua_functions_loader.cpp +++ b/src/lua/functions/lua_functions_loader.cpp @@ -111,9 +111,35 @@ void LuaFunctionsLoader::reportError(const char* function, const std::string &er LuaScriptInterface* scriptInterface; getScriptEnv()->getEventInfo(scriptId, scriptInterface, callbackId, timerEvent); - g_logger().error("Lua script error: \nscriptInterface: [{}]\nscriptId: [{}]" - "\ntimerEvent: [{}]\n callbackId:[{}]\nfunction: [{}]\nerror [{}]", - scriptInterface ? scriptInterface->getInterfaceName() : "", scriptId ? scriptInterface->getFileById(scriptId) : "", timerEvent ? "in a timer event called from:" : "", callbackId ? scriptInterface->getFileById(callbackId) : "", function ? scriptInterface->getInterfaceName() : "", (stack_trace && scriptInterface) ? scriptInterface->getStackTrace(error_desc) : error_desc); + std::stringstream logMsg; + logMsg << "Lua Script Error Detected\n"; + logMsg << "---------------------------------------\n"; + if (scriptInterface) { + logMsg << "Interface: " << scriptInterface->getInterfaceName() << "\n"; + if (scriptId) { + logMsg << "Script ID: " << scriptInterface->getFileById(scriptId) << "\n"; + } + if (timerEvent) { + logMsg << "Timer Event: Yes\n"; + } + if (callbackId) { + logMsg << "Callback ID: " << scriptInterface->getFileById(callbackId) << "\n"; + } + } + if (function && strcmp(function, "N/A") != 0) { + logMsg << "Function: " << function << "\n"; + } + logMsg << "Error Description: " << error_desc << "\n"; + if (stack_trace && scriptInterface) { + std::string stackTrace = scriptInterface->getStackTrace(error_desc); + if (!stackTrace.empty() && stackTrace != "N/A") { + logMsg << "Stack Trace:\n" + << stackTrace << "\n"; + } + } + logMsg << "---------------------------------------\n"; + + g_logger().error(logMsg.str()); } int LuaFunctionsLoader::luaErrorHandler(lua_State* L) { @@ -347,7 +373,8 @@ std::string LuaFunctionsLoader::getFormatedLoggerMessage(lua_State* L) { try { return fmt::vformat(format, args); } catch (const fmt::format_error &e) { - g_logger().error("[{}] format error: {}", __FUNCTION__, e.what()); + g_logger().debug("[{}] format error: {}", __FUNCTION__, e.what()); + reportErrorFunc(fmt::format("Format error, {}", e.what())); } return {}; diff --git a/src/lua/functions/lua_functions_loader.hpp b/src/lua/functions/lua_functions_loader.hpp index 89baf958e..17495cd2e 100644 --- a/src/lua/functions/lua_functions_loader.hpp +++ b/src/lua/functions/lua_functions_loader.hpp @@ -63,9 +63,17 @@ class LuaFunctionsLoader { return static_cast(static_cast(lua_tonumber(L, arg))); } template - static typename std::enable_if::value || std::is_floating_point::value, T>::type - getNumber(lua_State* L, int32_t arg) { - return static_cast(lua_tonumber(L, arg)); + static typename std::enable_if::value || std::is_floating_point::value, T>::type getNumber(lua_State* L, int32_t arg) { + auto number = lua_tonumber(L, arg); + // If there is overflow, we return the value 0 + if constexpr (std::is_integral_v && std::is_unsigned_v) { + if (number < 0) { + g_logger().debug("[{}] overflow, setting to default signed value (0)", __FUNCTION__); + number = T(0); + } + } + + return static_cast(number); } template static T getNumber(lua_State* L, int32_t arg, T defaultValue) { diff --git a/src/lua/functions/map/house_functions.cpp b/src/lua/functions/map/house_functions.cpp index b012a367d..834382ae4 100644 --- a/src/lua/functions/map/house_functions.cpp +++ b/src/lua/functions/map/house_functions.cpp @@ -127,7 +127,7 @@ int HouseFunctions::luaHouseSetNewOwnerGuid(lua_State* L) { // house:setNewOwnerGuid(guid[, updateDatabase = true]) auto house = getUserdataShared(L, 1); if (house) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && house->hasNewOwnership()) { const auto player = g_game().getPlayerByGUID(house->getOwner()); if (player) { @@ -168,7 +168,7 @@ int HouseFunctions::luaHouseHasNewOwnership(lua_State* L) { return 1; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); pushBoolean(L, isTransferOnRestart && house->hasNewOwnership()); return 1; } @@ -210,7 +210,7 @@ int HouseFunctions::luaHouseStartTrade(lua_State* L) { return 1; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart && house->hasNewOwnership()) { tradePartner->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You cannot buy this house. Ownership is already scheduled to be transferred upon the next server restart."); player->sendTextMessage(MESSAGE_EVENT_ADVANCE, "You cannot sell this house. Ownership is already scheduled to be transferred upon the next server restart."); @@ -368,7 +368,12 @@ int HouseFunctions::luaHouseCanEditAccessList(lua_State* L) { } uint32_t listId = getNumber(L, 2); - std::shared_ptr player = getPlayer(L, 3); + + const auto &player = getPlayer(L, 3); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; + } pushBoolean(L, house->canEditAccessList(listId, player)); return 1; @@ -415,7 +420,19 @@ int HouseFunctions::luaHouseKickPlayer(lua_State* L) { return 1; } - pushBoolean(L, house->kickPlayer(getPlayer(L, 2), getPlayer(L, 3))); + const auto &player = getPlayer(L, 2); + if (!player) { + reportErrorFunc("Player is nullptr"); + return 1; + } + + auto targetPlayer = getPlayer(L, 3); + if (!targetPlayer) { + reportErrorFunc("Target player is nullptr"); + return 1; + } + + pushBoolean(L, house->kickPlayer(player, targetPlayer)); return 1; } @@ -427,9 +444,9 @@ int HouseFunctions::luaHouseIsInvited(lua_State* L) { return 1; } - std::shared_ptr player = getPlayer(L, 2); + const auto &player = getPlayer(L, 2); if (!player) { - lua_pushnil(L); + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); return 1; } diff --git a/src/lua/functions/map/position_functions.cpp b/src/lua/functions/map/position_functions.cpp index 3e5582a1c..b68d85015 100644 --- a/src/lua/functions/map/position_functions.cpp +++ b/src/lua/functions/map/position_functions.cpp @@ -150,13 +150,17 @@ int PositionFunctions::luaPositionSendMagicEffect(lua_State* L) { // position:sendMagicEffect(magicEffect[, player = nullptr]) CreatureVector spectators; if (lua_gettop(L) >= 3) { - if (const auto &player = getPlayer(L, 3)) { - spectators.emplace_back(player); + const auto &player = getPlayer(L, 3); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; } + + spectators.emplace_back(player); } MagicEffectClasses magicEffect = getNumber(L, 2); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && !g_game().isMagicEffectRegistered(magicEffect)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isMagicEffectRegistered(magicEffect)) { g_logger().warn("[PositionFunctions::luaPositionSendMagicEffect] An unregistered magic effect type with id '{}' was blocked to prevent client crash.", fmt::underlying(magicEffect)); pushBoolean(L, false); return 1; @@ -177,13 +181,17 @@ int PositionFunctions::luaPositionRemoveMagicEffect(lua_State* L) { // position:removeMagicEffect(magicEffect[, player = nullptr]) CreatureVector spectators; if (lua_gettop(L) >= 3) { - if (const auto &player = getPlayer(L, 3)) { - spectators.emplace_back(player); + const auto &player = getPlayer(L, 3); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; } + + spectators.emplace_back(player); } MagicEffectClasses magicEffect = getNumber(L, 2); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && !g_game().isMagicEffectRegistered(magicEffect)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isMagicEffectRegistered(magicEffect)) { g_logger().warn("[PositionFunctions::luaPositionRemoveMagicEffect] An unregistered magic effect type with id '{}' was blocked to prevent client crash.", fmt::underlying(magicEffect)); pushBoolean(L, false); return 1; @@ -204,15 +212,19 @@ int PositionFunctions::luaPositionSendDistanceEffect(lua_State* L) { // position:sendDistanceEffect(positionEx, distanceEffect[, player = nullptr]) CreatureVector spectators; if (lua_gettop(L) >= 4) { - if (const auto &player = getPlayer(L, 4)) { - spectators.emplace_back(player); + const auto &player = getPlayer(L, 4); + if (!player) { + reportErrorFunc(getErrorDesc(LUA_ERROR_PLAYER_NOT_FOUND)); + return 1; } + + spectators.emplace_back(player); } ShootType_t distanceEffect = getNumber(L, 3); const Position &positionEx = getPosition(L, 2); const Position &position = getPosition(L, 1); - if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS) && !g_game().isDistanceEffectRegistered(distanceEffect)) { + if (g_configManager().getBoolean(WARN_UNSAFE_SCRIPTS, __FUNCTION__) && !g_game().isDistanceEffectRegistered(distanceEffect)) { g_logger().warn("[PositionFunctions::luaPositionSendDistanceEffect] An unregistered distance effect type with id '{}' was blocked to prevent client crash.", fmt::underlying(distanceEffect)); return 1; } diff --git a/src/lua/global/baseevents.cpp b/src/lua/global/baseevents.cpp index 90b47e22c..7347c898c 100644 --- a/src/lua/global/baseevents.cpp +++ b/src/lua/global/baseevents.cpp @@ -20,7 +20,7 @@ bool BaseEvents::loadFromXml() { } std::string scriptsName = getScriptBaseName(); - std::string basePath = g_configManager().getString(CORE_DIRECTORY) + "/" + scriptsName + "/"; + std::string basePath = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/" + scriptsName + "/"; if (getScriptInterface().loadFile( basePath + "lib/" + scriptsName + ".lua", scriptsName + ".lua" diff --git a/src/lua/scripts/luascript.cpp b/src/lua/scripts/luascript.cpp index d7d12dfe2..e4f230a5d 100644 --- a/src/lua/scripts/luascript.cpp +++ b/src/lua/scripts/luascript.cpp @@ -169,19 +169,29 @@ std::string LuaScriptInterface::getStackTrace(const std::string &error_desc) { lua_getglobal(luaState, "debug"); if (!isTable(luaState, -1)) { lua_pop(luaState, 1); + g_logger().error("Lua debug table not found."); return error_desc; } lua_getfield(luaState, -1, "traceback"); if (!isFunction(luaState, -1)) { lua_pop(luaState, 2); + g_logger().error("Lua traceback function not found."); return error_desc; } lua_replace(luaState, -2); pushString(luaState, error_desc); - lua_call(luaState, 1, 1); - return popString(luaState); + if (lua_pcall(luaState, 1, 1, 0) != LUA_OK) { + std::string luaError = lua_tostring(luaState, -1); + lua_pop(luaState, 1); + g_logger().error("Error running Lua traceback: {}", luaError); + return "Lua traceback failed: " + luaError; + } + + std::string stackTrace = popString(luaState); + + return stackTrace; } bool LuaScriptInterface::pushFunction(int32_t functionId) { diff --git a/src/lua/scripts/scripts.cpp b/src/lua/scripts/scripts.cpp index bb7c5a6a6..14c9b8c26 100644 --- a/src/lua/scripts/scripts.cpp +++ b/src/lua/scripts/scripts.cpp @@ -35,7 +35,7 @@ void Scripts::clearAllScripts() const { } bool Scripts::loadEventSchedulerScripts(const std::string &fileName) { - auto coreFolder = g_configManager().getString(CORE_DIRECTORY); + auto coreFolder = g_configManager().getString(CORE_DIRECTORY, __FUNCTION__); const auto dir = std::filesystem::current_path() / coreFolder / "events" / "scripts" / "scheduler"; if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) { g_logger().warn("{} - Can not load folder 'scheduler' on {}/events/scripts'", __FUNCTION__, coreFolder); @@ -90,7 +90,7 @@ bool Scripts::loadScripts(std::string loadPath, bool isLib, bool reload) { if (std::string disable("#"); file.front() == disable.front()) { // Send log of disabled script - if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) { + if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS, __FUNCTION__)) { g_logger().info("[script]: {} [disabled]", realPath.filename().string()); } // Skip for next loop and ignore disabled file @@ -100,7 +100,7 @@ bool Scripts::loadScripts(std::string loadPath, bool isLib, bool reload) { // If the file is a library file or if the file's parent directory is not "lib" or "events" if (isLib || (fileFolderView != "lib" && fileFolderView != "events")) { // If console logs are enabled and the file is not a library file - if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) { + if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS, __FUNCTION__)) { // If the current directory is different from the last directory that was logged if (lastDirectory.empty() || lastDirectory != scriptFolderView) { // Update the last directory variable and log the directory name @@ -118,7 +118,7 @@ bool Scripts::loadScripts(std::string loadPath, bool isLib, bool reload) { } } - if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS)) { + if (g_configManager().getBoolean(SCRIPTS_CONSOLE_LOGS, __FUNCTION__)) { if (!reload) { g_logger().info("[script loaded]: {}", realPath.filename().string()); } else { diff --git a/src/map/house/house.cpp b/src/map/house/house.cpp index 828753b8c..c4bf34c95 100644 --- a/src/map/house/house.cpp +++ b/src/map/house/house.cpp @@ -26,7 +26,7 @@ void House::addTile(std::shared_ptr tile) { } void House::setNewOwnerGuid(int32_t newOwnerGuid, bool serverStartup) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (!isTransferOnRestart) { setOwner(newOwnerGuid, true); return; @@ -99,7 +99,7 @@ void House::setOwner(uint32_t guid, bool updateDatabase /* = true*/, std::shared if (owner != 0) { tryTransferOwnership(player, false); } else { - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD)); + std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); time_t currentTime = time(nullptr); if (strRentPeriod == "yearly") { currentTime += 24 * 60 * 60 * 365; @@ -149,10 +149,10 @@ void House::updateDoorDescription() const { ss << " It is " << getSize() << " square meters."; const int32_t housePrice = getPrice(); if (housePrice != -1) { - if (g_configManager().getBoolean(HOUSE_PURSHASED_SHOW_PRICE) || owner == 0) { + if (g_configManager().getBoolean(HOUSE_PURSHASED_SHOW_PRICE, __FUNCTION__) || owner == 0) { ss << " It costs " << formatNumber(getPrice()) << " gold coins."; } - std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD)); + std::string strRentPeriod = asLowerCaseString(g_configManager().getString(HOUSE_RENT_PERIOD, __FUNCTION__)); if (strRentPeriod != "never") { ss << " The rent cost is " << formatNumber(getRent()) << " gold coins and it is billed " << strRentPeriod << "."; } @@ -168,7 +168,7 @@ AccessHouseLevel_t House::getHouseAccessLevel(std::shared_ptr player) co return HOUSE_OWNER; } - if (g_configManager().getBoolean(HOUSE_OWNED_BY_ACCOUNT)) { + if (g_configManager().getBoolean(HOUSE_OWNED_BY_ACCOUNT, __FUNCTION__)) { if (ownerAccountId == player->getAccountId()) { return HOUSE_OWNER; } @@ -456,7 +456,7 @@ std::shared_ptr HouseTransferItem::createHouseTransferItem(st void HouseTransferItem::onTradeEvent(TradeEvents_t event, std::shared_ptr owner) { if (event == ON_TRADE_TRANSFER) { if (house) { - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); auto ownershipTransferMessage = " The ownership will be transferred upon server restart."; auto boughtMessage = fmt::format("You have successfully bought the house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); auto soldMessage = fmt::format("You have successfully sold your house.{}", isTransferOnRestart ? ownershipTransferMessage : ""); @@ -483,7 +483,7 @@ bool House::executeTransfer(std::shared_ptr item, std::shared return false; } - auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART); + auto isTransferOnRestart = g_configManager().getBoolean(TOGGLE_HOUSE_TRANSFER_ON_SERVER_RESTART, __FUNCTION__); if (isTransferOnRestart) { if (hasNewOwnerOnStartup) { return false; @@ -766,10 +766,10 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { } // Player hasn't logged in for a while, reset house owner - auto daysToReset = g_configManager().getNumber(HOUSE_LOSE_AFTER_INACTIVITY); + auto daysToReset = g_configManager().getNumber(HOUSE_LOSE_AFTER_INACTIVITY, __FUNCTION__); if (daysToReset > 0) { auto daysSinceLastLogin = (currentTime - player->getLastLoginSaved()) / (60 * 60 * 24); - bool vipKeep = g_configManager().getBoolean(VIP_KEEP_HOUSE) && player->isVip(); + bool vipKeep = g_configManager().getBoolean(VIP_KEEP_HOUSE, __FUNCTION__) && player->isVip(); bool activityKeep = daysSinceLastLogin < daysToReset; if (vipKeep && !activityKeep) { g_logger().info("Player {} has not logged in for {} days, but is a VIP, so the house will not be reset.", player->getName(), daysToReset); @@ -851,11 +851,11 @@ void Houses::payHouses(RentPeriod_t rentPeriod) const { } uint32_t House::getRent() const { - return static_cast(g_configManager().getFloat(HOUSE_RENT_RATE) * static_cast(rent)); + return static_cast(g_configManager().getFloat(HOUSE_RENT_RATE, __FUNCTION__) * static_cast(rent)); } uint32_t House::getPrice() const { - auto sqmPrice = static_cast(g_configManager().getNumber(HOUSE_PRICE_PER_SQM)) * getSize(); - auto rentPrice = static_cast(static_cast(getRent()) * g_configManager().getFloat(HOUSE_PRICE_RENT_MULTIPLIER)); + auto sqmPrice = static_cast(g_configManager().getNumber(HOUSE_PRICE_PER_SQM, __FUNCTION__)) * getSize(); + auto rentPrice = static_cast(static_cast(getRent()) * g_configManager().getFloat(HOUSE_PRICE_RENT_MULTIPLIER, __FUNCTION__)); return sqmPrice + rentPrice; } diff --git a/src/map/house/housetile.cpp b/src/map/house/housetile.cpp index f67e16868..386b06a08 100644 --- a/src/map/house/housetile.cpp +++ b/src/map/house/housetile.cpp @@ -80,7 +80,7 @@ ReturnValue HouseTile::queryAdd(int32_t index, const std::shared_ptr &thi } } else if (thing->getItem() && actor) { std::shared_ptr actorPlayer = actor->getPlayer(); - if (house && (!house->isInvited(actorPlayer) || house->getHouseAccessLevel(actorPlayer) == HOUSE_GUEST) && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { + if (house && (!house->isInvited(actorPlayer) || house->getHouseAccessLevel(actorPlayer) == HOUSE_GUEST) && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { return RETURNVALUE_CANNOTTHROW; } } @@ -120,7 +120,7 @@ ReturnValue HouseTile::queryRemove(const std::shared_ptr &thing, uint32_t return RETURNVALUE_NOTPOSSIBLE; } - if (actor && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS)) { + if (actor && g_configManager().getBoolean(ONLY_INVITED_CAN_MOVE_HOUSE_ITEMS, __FUNCTION__)) { std::shared_ptr actorPlayer = actor->getPlayer(); if (house && !house->isInvited(actorPlayer)) { return RETURNVALUE_NOTPOSSIBLE; diff --git a/src/map/map.cpp b/src/map/map.cpp index 3771f5662..662e85f18 100644 --- a/src/map/map.cpp +++ b/src/map/map.cpp @@ -35,14 +35,14 @@ void Map::load(const std::string &identifier, const Position &pos) { void Map::loadMap(const std::string &identifier, bool mainMap /*= false*/, bool loadHouses /*= false*/, bool loadMonsters /*= false*/, bool loadNpcs /*= false*/, bool loadZones /*= false*/, const Position &pos /*= Position()*/) { // Only download map if is loading the main map and it is not already downloaded - if (mainMap && g_configManager().getBoolean(TOGGLE_DOWNLOAD_MAP) && !std::filesystem::exists(identifier)) { - const auto mapDownloadUrl = g_configManager().getString(MAP_DOWNLOAD_URL); + if (mainMap && g_configManager().getBoolean(TOGGLE_DOWNLOAD_MAP, __FUNCTION__) && !std::filesystem::exists(identifier)) { + const auto mapDownloadUrl = g_configManager().getString(MAP_DOWNLOAD_URL, __FUNCTION__); if (mapDownloadUrl.empty()) { g_logger().warn("Map download URL in config.lua is empty, download disabled"); } if (CURL* curl = curl_easy_init(); curl && !mapDownloadUrl.empty()) { - g_logger().info("Downloading " + g_configManager().getString(MAP_NAME) + ".otbm to world folder"); + g_logger().info("Downloading " + g_configManager().getString(MAP_NAME, __FUNCTION__) + ".otbm to world folder"); FILE* otbm = fopen(identifier.c_str(), "wb"); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(curl, CURLOPT_URL, mapDownloadUrl.c_str()); @@ -77,7 +77,7 @@ void Map::loadMap(const std::string &identifier, bool mainMap /*= false*/, bool * If map custom is enabled, then it is load in loadMapCustom function * NOTE: This will ensure that the information is not duplicated */ - if (!g_configManager().getBoolean(TOGGLE_MAP_CUSTOM)) { + if (!g_configManager().getBoolean(TOGGLE_MAP_CUSTOM, __FUNCTION__)) { IOMapSerialize::loadHouseInfo(); IOMapSerialize::loadHouseItems(this); } @@ -92,7 +92,7 @@ void Map::loadMap(const std::string &identifier, bool mainMap /*= false*/, bool } // Files need to be cleaned up if custom map is enabled to open, or will try to load main map files - if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM)) { + if (g_configManager().getBoolean(TOGGLE_MAP_CUSTOM, __FUNCTION__)) { monsterfile.clear(); housefile.clear(); npcfile.clear(); @@ -101,7 +101,7 @@ void Map::loadMap(const std::string &identifier, bool mainMap /*= false*/, bool void Map::loadMapCustom(const std::string &mapName, bool loadHouses, bool loadMonsters, bool loadNpcs, bool loadZones, int customMapIndex) { // Load the map - load(g_configManager().getString(DATA_DIRECTORY) + "/world/custom/" + mapName + ".otbm"); + load(g_configManager().getString(DATA_DIRECTORY, __FUNCTION__) + "/world/custom/" + mapName + ".otbm"); if (loadMonsters && !IOMap::loadMonstersCustom(this, mapName, customMapIndex)) { g_logger().warn("Failed to load monster custom data"); diff --git a/src/pch.hpp b/src/pch.hpp index 0f5775b73..04f692a0b 100644 --- a/src/pch.hpp +++ b/src/pch.hpp @@ -95,7 +95,18 @@ #include "lua/global/shared_object.hpp" -// Magic Enum +/** + * @brief Magic Enum is a C++ library that facilitates easy conversion between enums and strings. + * By default, the range of supported enum values is from -128 to 128. We need extends that range. + * + * @def MAGIC_ENUM_RANGE_MIN + * @note Sets the lower limit of the enum value range to -500. + * + * @def MAGIC_ENUM_RANGE_MAX + * @note Sets the upper limit of the enum value range to 500. + */ +#define MAGIC_ENUM_RANGE_MIN -500 +#define MAGIC_ENUM_RANGE_MAX 500 #include // Memory Mapped File diff --git a/src/security/argon.cpp b/src/security/argon.cpp index 606e1d2b7..aa3d188b0 100644 --- a/src/security/argon.cpp +++ b/src/security/argon.cpp @@ -21,10 +21,10 @@ Argon2::Argon2() { } void Argon2::updateConstants() { - m_const_str = g_configManager().getString(M_CONST); + m_const_str = g_configManager().getString(M_CONST, __FUNCTION__); m_cost = parseBitShift(m_const_str); - t_cost = g_configManager().getNumber(T_CONST); - parallelism = g_configManager().getNumber(PARALLELISM); + t_cost = g_configManager().getNumber(T_CONST, __FUNCTION__); + parallelism = g_configManager().getNumber(PARALLELISM, __FUNCTION__); } uint32_t Argon2::parseBitShift(const std::string &bitShiftStr) const { diff --git a/src/server/network/connection/connection.cpp b/src/server/network/connection/connection.cpp index d2937756c..8508052c3 100644 --- a/src/server/network/connection/connection.cpp +++ b/src/server/network/connection/connection.cpp @@ -126,7 +126,7 @@ void Connection::parseProxyIdentification(const std::error_code &error) { uint8_t* msgBuffer = msg.getBuffer(); auto charData = static_cast(static_cast(msgBuffer)); - std::string serverName = g_configManager().getString(SERVER_NAME) + "\n"; + std::string serverName = g_configManager().getString(SERVER_NAME, __FUNCTION__) + "\n"; if (connectionState == CONNECTION_STATE_IDENTIFYING) { if (msgBuffer[1] == 0x00 || strncasecmp(charData, &serverName[0], 2) != 0) { // Probably not proxy identification so let's try standard parsing method @@ -178,7 +178,7 @@ void Connection::parseHeader(const std::error_code &error) { } uint32_t timePassed = std::max(1, (time(nullptr) - timeConnected) + 1); - if ((++packetsSent / timePassed) > static_cast(g_configManager().getNumber(MAX_PACKETS_PER_SECOND))) { + if ((++packetsSent / timePassed) > static_cast(g_configManager().getNumber(MAX_PACKETS_PER_SECOND, __FUNCTION__))) { g_logger().warn("{} disconnected for exceeding packet per second limit.", convertIPToString(getIP())); close(); return; diff --git a/src/server/network/protocol/protocol.hpp b/src/server/network/protocol/protocol.hpp index 6f9252285..6e4b09c46 100644 --- a/src/server/network/protocol/protocol.hpp +++ b/src/server/network/protocol/protocol.hpp @@ -83,7 +83,7 @@ class Protocol : public std::enable_shared_from_this { private: struct ZStream { ZStream() noexcept { - const int32_t compressionLevel = g_configManager().getNumber(COMPRESSION_LEVEL); + const int32_t compressionLevel = g_configManager().getNumber(COMPRESSION_LEVEL, __FUNCTION__); if (compressionLevel <= 0) { return; } diff --git a/src/server/network/protocol/protocolgame.cpp b/src/server/network/protocol/protocolgame.cpp index b9e6e673c..958d19f2a 100644 --- a/src/server/network/protocol/protocolgame.cpp +++ b/src/server/network/protocol/protocolgame.cpp @@ -194,7 +194,7 @@ namespace { for (size_t i = 0; i < COMBAT_COUNT; ++i) { damageReduction[i] -= player->getAbsorbPercent(indexToCombatType(i)); - if (g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { damageReduction[i] -= static_cast(player->wheel()->getResistance(indexToCombatType(i))) / 100.f; } @@ -500,7 +500,7 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS if (g_game().getGameState() == GAME_STATE_CLOSED && !player->hasFlag(PlayerFlags_t::CanAlwaysLogin)) { g_game().removePlayerUniqueLogin(player); - auto maintainMessage = g_configManager().getString(MAINTAIN_MODE_MESSAGE); + auto maintainMessage = g_configManager().getString(MAINTAIN_MODE_MESSAGE, __FUNCTION__); if (!maintainMessage.empty()) { disconnectClient(maintainMessage); } else { @@ -509,13 +509,13 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS return; } - if (g_configManager().getBoolean(ONLY_PREMIUM_ACCOUNT) && !player->isPremium() && (player->getGroup()->id < account::GROUP_TYPE_GAMEMASTER || player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER)) { + if (g_configManager().getBoolean(ONLY_PREMIUM_ACCOUNT, __FUNCTION__) && !player->isPremium() && (player->getGroup()->id < account::GROUP_TYPE_GAMEMASTER || player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER)) { g_game().removePlayerUniqueLogin(player); disconnectClient("Your premium time for this account is out.\n\nTo play please buy additional premium time from our website"); return; } - if (g_configManager().getBoolean(ONE_PLAYER_ON_ACCOUNT) && player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER && g_game().getPlayerByAccount(player->getAccountId())) { + if (g_configManager().getBoolean(ONE_PLAYER_ON_ACCOUNT, __FUNCTION__) && player->getAccountType() < account::ACCOUNT_TYPE_GAMEMASTER && g_game().getPlayerByAccount(player->getAccountId())) { g_game().removePlayerUniqueLogin(player); disconnectClient("You may only login with one character\nof your account at the same time."); return; @@ -581,7 +581,7 @@ void ProtocolGame::login(const std::string &name, uint32_t accountId, OperatingS player->lastLoginSaved = std::max(time(nullptr), player->lastLoginSaved + 1); acceptPackets = true; } else { - if (eventConnect != 0 || !g_configManager().getBoolean(REPLACE_KICK_ON_LOGIN)) { + if (eventConnect != 0 || !g_configManager().getBoolean(REPLACE_KICK_ON_LOGIN, __FUNCTION__)) { // Already trying to connect disconnectClient("You are already logged in."); return; @@ -675,7 +675,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { version = msg.get(); // Protocol version // Old protocol support - oldProtocol = g_configManager().getBoolean(OLD_PROTOCOL) && version <= 1100; + oldProtocol = g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__) && version <= 1100; if (oldProtocol) { setChecksumMethod(CHECKSUM_METHOD_ADLER32); @@ -703,7 +703,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { msg.skipBytes(1); // gamemaster flag - std::string authType = g_configManager().getString(AUTH_TYPE); + std::string authType = g_configManager().getString(AUTH_TYPE, __FUNCTION__); std::ostringstream ss; std::string sessionKey = msg.getString(); std::string accountDescriptor = sessionKey; @@ -760,7 +760,7 @@ void ProtocolGame::onRecvFirstMessage(NetworkMessage &msg) { if (!oldProtocol && clientVersion != CLIENT_VERSION) { ss.str(std::string()); ss << "Only clients with protocol " << CLIENT_VERSION_UPPER << "." << CLIENT_VERSION_LOWER; - if (g_configManager().getBoolean(OLD_PROTOCOL)) { + if (g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__)) { ss << " or 11.00"; } ss << " allowed!"; @@ -931,7 +931,7 @@ void ProtocolGame::addBless() { std::ostringstream lostBlesses; (bless.length() == 0) ? lostBlesses << "You lost all your blessings." : lostBlesses << "You are still blessed with " << bless; player->sendTextMessage(MESSAGE_EVENT_ADVANCE, lostBlesses.str()); - if (player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL) && player->getVocationId() > VOCATION_NONE) { + if (player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL, __FUNCTION__) && player->getVocationId() > VOCATION_NONE) { for (uint8_t i = 2; i <= 6; i++) { if (!player->hasBlessing(i)) { player->addBlessing(i, 1); @@ -2060,7 +2060,7 @@ void ProtocolGame::parseTaskHuntingAction(NetworkMessage &msg) { bool upgrade = msg.getByte() != 0; uint16_t raceId = msg.get(); - if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED)) { + if (!g_configManager().getBoolean(TASK_HUNTING_ENABLED, __FUNCTION__)) { return; } @@ -2088,8 +2088,8 @@ void ProtocolGame::sendHighscores(const std::vector &charact msg.addByte(0x00); // No data available msg.addByte(1); // Worlds - msg.addString(g_configManager().getString(SERVER_NAME)); // First World - msg.addString(g_configManager().getString(SERVER_NAME)); // Selected World + msg.addString(g_configManager().getString(SERVER_NAME, __FUNCTION__)); // First World + msg.addString(g_configManager().getString(SERVER_NAME, __FUNCTION__)); // Selected World msg.addByte(0); // Game World Category: 0xFF(-1) - Selected World msg.addByte(0); // BattlEye World Type @@ -2148,7 +2148,7 @@ void ProtocolGame::sendHighscores(const std::vector &charact msg.addString(character.name); // Character Name msg.addString(""); // Probably Character Title(not visible in window) msg.addByte(character.vocation); // Vocation Id - msg.addString(g_configManager().getString(SERVER_NAME)); // World + msg.addString(g_configManager().getString(SERVER_NAME, __FUNCTION__)); // World msg.add(character.level); // Level msg.addByte((player->getGUID() == character.id)); // Player Indicator Boolean msg.add(character.points); // Points @@ -2945,7 +2945,7 @@ void ProtocolGame::parsePreyAction(NetworkMessage &msg) { raceId = msg.get(); } - if (!g_configManager().getBoolean(PREY_ENABLED)) { + if (!g_configManager().getBoolean(PREY_ENABLED, __FUNCTION__)) { return; } @@ -3067,12 +3067,12 @@ void ProtocolGame::parseRewardChestCollect(NetworkMessage &msg) { auto stackPosition = msg.getByte(); // Block collect reward - auto useCollect = g_configManager().getBoolean(REWARD_CHEST_COLLECT_ENABLED); + auto useCollect = g_configManager().getBoolean(REWARD_CHEST_COLLECT_ENABLED, __FUNCTION__); if (!useCollect) { return; } - auto maxCollectItems = g_configManager().getNumber(REWARD_CHEST_MAX_COLLECT_ITEMS); + auto maxCollectItems = g_configManager().getNumber(REWARD_CHEST_MAX_COLLECT_ITEMS, __FUNCTION__); addGameTask(&Game::playerRewardChestCollect, player->getID(), position, itemId, stackPosition, maxCollectItems); } @@ -3523,7 +3523,7 @@ void ProtocolGame::sendCyclopediaCharacterCombatStats() { msg.add(player->getArmor()); msg.add(player->getDefense()); // Wheel of destiny mitigation - if (g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { msg.addDouble(player->getMitigation()); } else { msg.addDouble(0); @@ -3983,7 +3983,7 @@ void ProtocolGame::sendBlessStatus() { if (oldProtocol) { msg.add(blessCount >= 5 ? 0x01 : 0x00); } else { - bool glow = player->getVocationId() > VOCATION_NONE && ((g_configManager().getBoolean(INVENTORY_GLOW) && blessCount >= 5) || player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL)); + bool glow = player->getVocationId() > VOCATION_NONE && ((g_configManager().getBoolean(INVENTORY_GLOW, __FUNCTION__) && blessCount >= 5) || player->getLevel() < g_configManager().getNumber(ADVENTURERSBLESSING_LEVEL, __FUNCTION__)); msg.add(glow ? 1 : 0); // Show up the glowing effect in items if you have all blesses or adventurer's blessing msg.addByte((blessCount >= 7) ? 3 : ((blessCount >= 5) ? 2 : 1)); // 1 = Disabled | 2 = normal | 3 = green } @@ -3992,7 +3992,7 @@ void ProtocolGame::sendBlessStatus() { } void ProtocolGame::sendPremiumTrigger() { - if (!g_configManager().getBoolean(FREE_PREMIUM) && !g_configManager().getBoolean(VIP_SYSTEM_ENABLED)) { + if (!g_configManager().getBoolean(FREE_PREMIUM, __FUNCTION__) && !g_configManager().getBoolean(VIP_SYSTEM_ENABLED, __FUNCTION__)) { NetworkMessage msg; msg.addByte(0x9E); msg.addByte(16); @@ -4360,7 +4360,7 @@ void ProtocolGame::sendShop(std::shared_ptr npc) { msg.addString(std::string()); // Currency name } - std::vector shoplist = npc->getShopItemVector(); + std::vector shoplist = npc->getShopItemVector(player->getGUID()); uint16_t itemsToSend = std::min(shoplist.size(), std::numeric_limits::max()); msg.add(itemsToSend); @@ -4854,27 +4854,27 @@ void ProtocolGame::sendForgingData() { } // (conversion) (left column top) Cost to make 1 bottom item - 20 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_COST_ONE_SLIVER))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_COST_ONE_SLIVER, __FUNCTION__))); // (conversion) (left column bottom) How many items to make - 3 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_SLIVER_AMOUNT, __FUNCTION__))); // (conversion) (middle column top) Cost to make 1 - 50 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_CORE_COST))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_CORE_COST, __FUNCTION__))); // (conversion) (right column top) Current stored dust limit minus this number = cost to increase stored dust limit - 75 msg.addByte(75); // (conversion) (right column bottom) Starting stored dust limit msg.add(player->getForgeDustLevel()); // (conversion) (right column bottom) Max stored dust limit - 225 - msg.add(g_configManager().getNumber(FORGE_MAX_DUST)); + msg.add(g_configManager().getNumber(FORGE_MAX_DUST, __FUNCTION__)); // (fusion) Dust cost - 100 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_FUSION_DUST_COST))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_FUSION_DUST_COST, __FUNCTION__))); // (transfer) Dust cost - 100 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_TRANSFER_DUST_COST))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_TRANSFER_DUST_COST, __FUNCTION__))); // (fusion) Base success rate - 50 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_BASE_SUCCESS_RATE, __FUNCTION__))); // (fusion) Bonus success rate - 15 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_BONUS_SUCCESS_RATE, __FUNCTION__))); // (fusion) Tier loss chance after reduction - 50 - msg.addByte(static_cast(g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION))); + msg.addByte(static_cast(g_configManager().getNumber(FORGE_TIER_LOSS_REDUCTION, __FUNCTION__))); // Update player resources parseSendResourceBalance(); @@ -4898,7 +4898,7 @@ void ProtocolGame::sendOpenForge() { auto itemClassification = item->getClassification(); auto itemTier = item->getTier(); - auto maxConfigTier = g_configManager().getNumber(FORGE_MAX_ITEM_TIER); + auto maxConfigTier = g_configManager().getNumber(FORGE_MAX_ITEM_TIER, __FUNCTION__); auto maxTier = (itemClassification == 4 ? maxConfigTier : itemClassification); // Save fusion items on map if (itemClassification != 0 && itemTier < maxTier) { @@ -6108,8 +6108,8 @@ void ProtocolGame::sendAddCreature(std::shared_ptr creature, const Pos msg.addByte(0x00); // can change pvp framing option msg.addByte(0x00); // expert mode button enabled - msg.addString(g_configManager().getString(STORE_IMAGES_URL)); - msg.add(static_cast(g_configManager().getNumber(STORE_COIN_PACKET))); + msg.addString(g_configManager().getString(STORE_IMAGES_URL, __FUNCTION__)); + msg.add(static_cast(g_configManager().getNumber(STORE_COIN_PACKET, __FUNCTION__))); if (!oldProtocol) { msg.addByte(shouldAddExivaRestrictions ? 0x01 : 0x00); // exiva button enabled @@ -6194,7 +6194,7 @@ void ProtocolGame::sendAddCreature(std::shared_ptr creature, const Pos sendLootContainers(); sendBasicData(); // Wheel of destiny cooldown - if (!oldProtocol && g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (!oldProtocol && g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { player->wheel()->sendGiftOfLifeCooldown(); } @@ -6928,12 +6928,12 @@ void ProtocolGame::sendPreyPrices() { msg.addByte(0xE9); msg.add(player->getPreyRerollPrice()); if (!oldProtocol) { - msg.addByte(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE))); - msg.addByte(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE))); + msg.addByte(static_cast(g_configManager().getNumber(PREY_BONUS_REROLL_PRICE, __FUNCTION__))); + msg.addByte(static_cast(g_configManager().getNumber(PREY_SELECTION_LIST_PRICE, __FUNCTION__))); msg.add(player->getTaskHuntingRerollPrice()); msg.add(player->getTaskHuntingRerollPrice()); - msg.addByte(static_cast(g_configManager().getNumber(TASK_HUNTING_SELECTION_LIST_PRICE))); - msg.addByte(static_cast(g_configManager().getNumber(TASK_HUNTING_BONUS_REROLL_PRICE))); + msg.addByte(static_cast(g_configManager().getNumber(TASK_HUNTING_SELECTION_LIST_PRICE, __FUNCTION__))); + msg.addByte(static_cast(g_configManager().getNumber(TASK_HUNTING_BONUS_REROLL_PRICE, __FUNCTION__))); } writeToOutputBuffer(msg); @@ -7655,6 +7655,18 @@ void ProtocolGame::AddShopItem(NetworkMessage &msg, const ShopBlock &shopBlock) return; } + // Hidden sell items from the shop if they are not in the player's inventory + auto talkactionHidden = player->kv()->get("npc-shop-hidden-sell-item"); + if (talkactionHidden && talkactionHidden->get() == true) { + std::map inventoryMap; + player->getAllSaleItemIdAndCount(inventoryMap); + auto inventoryItems = inventoryMap.find(shopBlock.itemId); + if (inventoryItems == inventoryMap.end() && shopBlock.itemSellPrice > 0 && shopBlock.itemBuyPrice == 0) { + AddHiddenShopItem(msg); + return; + } + } + const ItemType &it = Item::items[shopBlock.itemId]; msg.add(shopBlock.itemId); if (it.isSplash() || it.isFluidContainer()) { @@ -7847,7 +7859,7 @@ void ProtocolGame::sendOpenStash() { msg.add(item.first); msg.add(item.second); } - msg.add(static_cast(g_configManager().getNumber(STASH_ITEMS) - getStashSize(list))); + msg.add(static_cast(g_configManager().getNumber(STASH_ITEMS, __FUNCTION__) - getStashSize(list))); writeToOutputBuffer(msg); } @@ -8265,14 +8277,14 @@ void ProtocolGame::parseSendBosstiarySlots() { bossesUnlockedSize--; } - bool isTodaySlotUnlocked = g_configManager().getBoolean(BOOSTED_BOSS_SLOT); + bool isTodaySlotUnlocked = g_configManager().getBoolean(BOOSTED_BOSS_SLOT, __FUNCTION__); msg.addByte(isTodaySlotUnlocked ? 1 : 0); msg.add(boostedBossId); if (isTodaySlotUnlocked && boostedBossId != 0) { auto boostedBossKillCount = player->getBestiaryKillCount(static_cast(boostedBossId)); - auto boostedLootBonus = static_cast(g_configManager().getNumber(BOOSTED_BOSS_LOOT_BONUS)); - auto bosstiaryMultiplier = static_cast(g_configManager().getNumber(BOSSTIARY_KILL_MULTIPLIER)); - auto boostedKillBonus = static_cast(g_configManager().getNumber(BOOSTED_BOSS_KILL_BONUS)); + auto boostedLootBonus = static_cast(g_configManager().getNumber(BOOSTED_BOSS_LOOT_BONUS, __FUNCTION__)); + auto bosstiaryMultiplier = static_cast(g_configManager().getNumber(BOSSTIARY_KILL_MULTIPLIER, __FUNCTION__)); + auto boostedKillBonus = static_cast(g_configManager().getNumber(BOOSTED_BOSS_KILL_BONUS, __FUNCTION__)); sendBosstiarySlotsBytes(msg, static_cast(boostedBossRace), boostedBossKillCount, boostedLootBonus, bosstiaryMultiplier + boostedKillBonus, 0, 0); } @@ -8528,7 +8540,7 @@ void ProtocolGame::sendDoubleSoundEffect( } void ProtocolGame::parseOpenWheel(NetworkMessage &msg) { - if (oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { return; } @@ -8537,7 +8549,7 @@ void ProtocolGame::parseOpenWheel(NetworkMessage &msg) { } void ProtocolGame::sendOpenWheelWindow(uint32_t ownerId) { - if (!player || oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (!player || oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { return; } @@ -8547,7 +8559,7 @@ void ProtocolGame::sendOpenWheelWindow(uint32_t ownerId) { } void ProtocolGame::parseSaveWheel(NetworkMessage &msg) { - if (oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM)) { + if (oldProtocol || !g_configManager().getBoolean(TOGGLE_WHEELSYSTEM, __FUNCTION__)) { return; } diff --git a/src/server/network/protocol/protocollogin.cpp b/src/server/network/protocol/protocollogin.cpp index 1f0a3b57a..1b8753b01 100644 --- a/src/server/network/protocol/protocollogin.cpp +++ b/src/server/network/protocol/protocollogin.cpp @@ -32,7 +32,7 @@ void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const account::Account account(accountDescriptor); account.setProtocolCompat(oldProtocol); - if (oldProtocol && !g_configManager().getBoolean(OLD_PROTOCOL)) { + if (oldProtocol && !g_configManager().getBoolean(OLD_PROTOCOL, __FUNCTION__)) { disconnectClient(fmt::format("Only protocol version {}.{} is allowed.", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER)); return; } else if (!oldProtocol) { @@ -48,7 +48,7 @@ void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const } auto output = OutputMessagePool::getOutputMessage(); - const std::string &motd = g_configManager().getString(SERVER_MOTD); + const std::string &motd = g_configManager().getString(SERVER_MOTD, __FUNCTION__); if (!motd.empty()) { // Add MOTD output->addByte(0x14); @@ -74,10 +74,10 @@ void ProtocolLogin::getCharacterList(const std::string &accountDescriptor, const output->addByte(1); // number of worlds output->addByte(0); // world id - output->addString(g_configManager().getString(SERVER_NAME)); - output->addString(g_configManager().getString(IP)); + output->addString(g_configManager().getString(SERVER_NAME, __FUNCTION__)); + output->addString(g_configManager().getString(IP, __FUNCTION__)); - output->add(g_configManager().getShortNumber(GAME_PORT)); + output->add(g_configManager().getNumber(GAME_PORT, __FUNCTION__)); output->addByte(0); diff --git a/src/server/network/protocol/protocolstatus.cpp b/src/server/network/protocol/protocolstatus.cpp index fbea86e1a..8f4a6e8de 100644 --- a/src/server/network/protocol/protocolstatus.cpp +++ b/src/server/network/protocol/protocolstatus.cpp @@ -18,7 +18,7 @@ std::string ProtocolStatus::SERVER_NAME = "OTX Server"; std::string ProtocolStatus::SERVER_VERSION = "6.2"; -std::string ProtocolStatus::SERVER_DEVELOPERS = "OpenTibiaBR Organization. Based on: Canary (3.1.1). And data edited by: Mattyx14"; +std::string ProtocolStatus::SERVER_DEVELOPERS = "OpenTibiaBR Organization. Based on: Canary (3.1.2). And data edited by: Mattyx14"; std::map ProtocolStatus::ipConnectMap; const uint64_t ProtocolStatus::start = OTSYS_TIME(); @@ -27,9 +27,9 @@ void ProtocolStatus::onRecvFirstMessage(NetworkMessage &msg) { uint32_t ip = getIP(); if (ip != 0x0100007F) { std::string ipStr = convertIPToString(ip); - if (ipStr != g_configManager().getString(IP)) { + if (ipStr != g_configManager().getString(IP, __FUNCTION__)) { std::map::const_iterator it = ipConnectMap.find(ip); - if (it != ipConnectMap.end() && (OTSYS_TIME() < (it->second + g_configManager().getNumber(STATUSQUERY_TIMEOUT)))) { + if (it != ipConnectMap.end() && (OTSYS_TIME() < (it->second + g_configManager().getNumber(STATUSQUERY_TIMEOUT, __FUNCTION__)))) { disconnect(); return; } @@ -81,18 +81,18 @@ void ProtocolStatus::sendStatusString() { pugi::xml_node serverinfo = tsqp.append_child("serverinfo"); uint64_t uptime = (OTSYS_TIME() - ProtocolStatus::start) / 1000; serverinfo.append_attribute("uptime") = std::to_string(uptime).c_str(); - serverinfo.append_attribute("ip") = g_configManager().getString(IP).c_str(); - serverinfo.append_attribute("servername") = g_configManager().getString(stringConfig_t::SERVER_NAME).c_str(); - serverinfo.append_attribute("port") = std::to_string(g_configManager().getNumber(LOGIN_PORT)).c_str(); - serverinfo.append_attribute("location") = g_configManager().getString(LOCATION).c_str(); - serverinfo.append_attribute("url") = g_configManager().getString(URL).c_str(); + serverinfo.append_attribute("ip") = g_configManager().getString(IP, __FUNCTION__).c_str(); + serverinfo.append_attribute("servername") = g_configManager().getString(ConfigKey_t::SERVER_NAME, __FUNCTION__).c_str(); + serverinfo.append_attribute("port") = std::to_string(g_configManager().getNumber(LOGIN_PORT, __FUNCTION__)).c_str(); + serverinfo.append_attribute("location") = g_configManager().getString(LOCATION, __FUNCTION__).c_str(); + serverinfo.append_attribute("url") = g_configManager().getString(URL, __FUNCTION__).c_str(); serverinfo.append_attribute("server") = ProtocolStatus::SERVER_NAME.c_str(); serverinfo.append_attribute("version") = ProtocolStatus::SERVER_VERSION.c_str(); serverinfo.append_attribute("client") = fmt::format("{}.{}", CLIENT_VERSION_UPPER, CLIENT_VERSION_LOWER).c_str(); pugi::xml_node owner = tsqp.append_child("owner"); - owner.append_attribute("name") = g_configManager().getString(OWNER_NAME).c_str(); - owner.append_attribute("email") = g_configManager().getString(OWNER_EMAIL).c_str(); + owner.append_attribute("name") = g_configManager().getString(OWNER_NAME, __FUNCTION__).c_str(); + owner.append_attribute("email") = g_configManager().getString(OWNER_EMAIL, __FUNCTION__).c_str(); pugi::xml_node players = tsqp.append_child("players"); uint32_t real = 0; @@ -112,7 +112,7 @@ void ProtocolStatus::sendStatusString() { } } players.append_attribute("online") = std::to_string(real).c_str(); - players.append_attribute("max") = std::to_string(g_configManager().getNumber(MAX_PLAYERS)).c_str(); + players.append_attribute("max") = std::to_string(g_configManager().getNumber(MAX_PLAYERS, __FUNCTION__)).c_str(); players.append_attribute("peak") = std::to_string(g_game().getPlayersRecord()).c_str(); pugi::xml_node monsters = tsqp.append_child("monsters"); @@ -122,15 +122,15 @@ void ProtocolStatus::sendStatusString() { npcs.append_attribute("total") = std::to_string(g_game().getNpcsOnline()).c_str(); pugi::xml_node rates = tsqp.append_child("rates"); - rates.append_attribute("experience") = std::to_string(g_configManager().getNumber(RATE_EXPERIENCE)).c_str(); - rates.append_attribute("skill") = std::to_string(g_configManager().getNumber(RATE_SKILL)).c_str(); - rates.append_attribute("loot") = std::to_string(g_configManager().getNumber(RATE_LOOT)).c_str(); - rates.append_attribute("magic") = std::to_string(g_configManager().getNumber(RATE_MAGIC)).c_str(); - rates.append_attribute("spawn") = std::to_string(g_configManager().getNumber(RATE_SPAWN)).c_str(); + rates.append_attribute("experience") = std::to_string(g_configManager().getNumber(RATE_EXPERIENCE, __FUNCTION__)).c_str(); + rates.append_attribute("skill") = std::to_string(g_configManager().getNumber(RATE_SKILL, __FUNCTION__)).c_str(); + rates.append_attribute("loot") = std::to_string(g_configManager().getNumber(RATE_LOOT, __FUNCTION__)).c_str(); + rates.append_attribute("magic") = std::to_string(g_configManager().getNumber(RATE_MAGIC, __FUNCTION__)).c_str(); + rates.append_attribute("spawn") = std::to_string(g_configManager().getNumber(RATE_SPAWN, __FUNCTION__)).c_str(); pugi::xml_node map = tsqp.append_child("map"); - map.append_attribute("name") = g_configManager().getString(MAP_NAME).c_str(); - map.append_attribute("author") = g_configManager().getString(MAP_AUTHOR).c_str(); + map.append_attribute("name") = g_configManager().getString(MAP_NAME, __FUNCTION__).c_str(); + map.append_attribute("author") = g_configManager().getString(MAP_AUTHOR, __FUNCTION__).c_str(); uint32_t mapWidth, mapHeight; g_game().getMapDimensions(mapWidth, mapHeight); @@ -138,7 +138,7 @@ void ProtocolStatus::sendStatusString() { map.append_attribute("height") = std::to_string(mapHeight).c_str(); pugi::xml_node motd = tsqp.append_child("motd"); - motd.text() = g_configManager().getString(SERVER_MOTD).c_str(); + motd.text() = g_configManager().getString(SERVER_MOTD, __FUNCTION__).c_str(); std::ostringstream ss; doc.save(ss, "", pugi::format_raw); @@ -154,36 +154,36 @@ void ProtocolStatus::sendInfo(uint16_t requestedInfo, const std::string &charact if (requestedInfo & REQUEST_BASIC_SERVER_INFO) { output->addByte(0x10); - output->addString(g_configManager().getString(stringConfig_t::SERVER_NAME)); - output->addString(g_configManager().getString(IP)); - output->addString(std::to_string(g_configManager().getNumber(LOGIN_PORT))); + output->addString(g_configManager().getString(ConfigKey_t::SERVER_NAME, __FUNCTION__)); + output->addString(g_configManager().getString(IP, __FUNCTION__)); + output->addString(std::to_string(g_configManager().getNumber(LOGIN_PORT, __FUNCTION__))); } if (requestedInfo & REQUEST_OWNER_SERVER_INFO) { output->addByte(0x11); - output->addString(g_configManager().getString(OWNER_NAME)); - output->addString(g_configManager().getString(OWNER_EMAIL)); + output->addString(g_configManager().getString(OWNER_NAME, __FUNCTION__)); + output->addString(g_configManager().getString(OWNER_EMAIL, __FUNCTION__)); } if (requestedInfo & REQUEST_MISC_SERVER_INFO) { output->addByte(0x12); - output->addString(g_configManager().getString(SERVER_MOTD)); - output->addString(g_configManager().getString(LOCATION)); - output->addString(g_configManager().getString(URL)); + output->addString(g_configManager().getString(SERVER_MOTD, __FUNCTION__)); + output->addString(g_configManager().getString(LOCATION, __FUNCTION__)); + output->addString(g_configManager().getString(URL, __FUNCTION__)); output->add((OTSYS_TIME() - ProtocolStatus::start) / 1000); } if (requestedInfo & REQUEST_PLAYERS_INFO) { output->addByte(0x20); output->add(static_cast(g_game().getPlayersOnline())); - output->add(g_configManager().getNumber(MAX_PLAYERS)); + output->add(g_configManager().getNumber(MAX_PLAYERS, __FUNCTION__)); output->add(g_game().getPlayersRecord()); } if (requestedInfo & REQUEST_MAP_INFO) { output->addByte(0x30); - output->addString(g_configManager().getString(MAP_NAME)); - output->addString(g_configManager().getString(MAP_AUTHOR)); + output->addString(g_configManager().getString(MAP_NAME, __FUNCTION__)); + output->addString(g_configManager().getString(MAP_AUTHOR, __FUNCTION__)); uint32_t mapWidth, mapHeight; g_game().getMapDimensions(mapWidth, mapHeight); output->add(mapWidth); diff --git a/src/server/network/webhook/webhook.cpp b/src/server/network/webhook/webhook.cpp index 69d05070a..b761210cc 100644 --- a/src/server/network/webhook/webhook.cpp +++ b/src/server/network/webhook/webhook.cpp @@ -39,7 +39,7 @@ Webhook &Webhook::getInstance() { void Webhook::run() { threadPool.addLoad([this] { sendWebhook(); }); g_dispatcher().scheduleEvent( - g_configManager().getNumber(DISCORD_WEBHOOK_DELAY_MS), [this] { run(); }, "Webhook::run" + g_configManager().getNumber(DISCORD_WEBHOOK_DELAY_MS, __FUNCTION__), [this] { run(); }, "Webhook::run" ); } @@ -50,7 +50,7 @@ void Webhook::sendMessage(const std::string payload, std::string url) { void Webhook::sendMessage(const std::string title, const std::string message, int color, std::string url) { if (url.empty()) { - url = g_configManager().getString(DISCORD_WEBHOOK_URL); + url = g_configManager().getString(DISCORD_WEBHOOK_URL, __FUNCTION__); } if (url.empty() || title.empty() || message.empty()) { @@ -106,7 +106,7 @@ std::string Webhook::getPayload(const std::string title, const std::string messa std::stringstream footer_text; footer_text - << g_configManager().getString(SERVER_NAME) << " | " + << g_configManager().getString(SERVER_NAME, __FUNCTION__) << " | " << time_buf; std::stringstream payload; diff --git a/src/server/server.cpp b/src/server/server.cpp index dc6fa3bd9..00f9d79e7 100644 --- a/src/server/server.cpp +++ b/src/server/server.cpp @@ -144,8 +144,8 @@ void ServicePort::open(uint16_t port) { pendingStart = false; try { - if (g_configManager().getBoolean(BIND_ONLY_GLOBAL_ADDRESS)) { - acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4::from_string(g_configManager().getString(IP))), serverPort))); + if (g_configManager().getBoolean(BIND_ONLY_GLOBAL_ADDRESS, __FUNCTION__)) { + acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4::from_string(g_configManager().getString(IP, __FUNCTION__))), serverPort))); } else { acceptor.reset(new asio::ip::tcp::acceptor(io_service, asio::ip::tcp::endpoint(asio::ip::address(asio::ip::address_v4(INADDR_ANY)), serverPort))); } diff --git a/src/server/signals.cpp b/src/server/signals.cpp index bb40bbcd8..149554d3b 100644 --- a/src/server/signals.cpp +++ b/src/server/signals.cpp @@ -118,7 +118,7 @@ void Signals::sighupHandler() { g_chat().load(); g_logger().info("Reloaded chatchannels"); - g_luaEnvironment().loadFile(g_configManager().getString(CORE_DIRECTORY) + "/core.lua", "core.lua"); + g_luaEnvironment().loadFile(g_configManager().getString(CORE_DIRECTORY, __FUNCTION__) + "/core.lua", "core.lua"); g_logger().info("Reloaded core.lua"); lua_gc(g_luaEnvironment().getLuaState(), LUA_GCCOLLECT, 0); diff --git a/src/utils/tools.cpp b/src/utils/tools.cpp index a4b9f8d31..ce42c04ad 100644 --- a/src/utils/tools.cpp +++ b/src/utils/tools.cpp @@ -1454,8 +1454,13 @@ const char* getReturnMessage(ReturnValue value) { } } +int64_t OTSYSTIME = 0; +void UPDATE_OTSYS_TIME() { + OTSYSTIME = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); +} + int64_t OTSYS_TIME() { - return std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + return OTSYSTIME; } SpellGroup_t stringToSpellGroup(const std::string &value) { diff --git a/src/utils/tools.hpp b/src/utils/tools.hpp index 099f77afc..580a962c9 100644 --- a/src/utils/tools.hpp +++ b/src/utils/tools.hpp @@ -135,6 +135,7 @@ bool isCaskItem(uint16_t itemId); std::string getObjectCategoryName(ObjectCategory_t category); int64_t OTSYS_TIME(); +void UPDATE_OTSYS_TIME(); SpellGroup_t stringToSpellGroup(const std::string &value);