diff --git a/CMakeLists.txt b/CMakeLists.txt index 1b6a775e5..e085bfe71 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -245,6 +245,7 @@ set(INCLUDED_DIRECTORIES "thirdparty/SQLite" "thirdparty/cpplinq" "thirdparty/cpp-httplib" + "thirdparty/MD5" "tests" "tests/dCommonTests" @@ -320,7 +321,7 @@ add_subdirectory(dPhysics) add_subdirectory(dServer) # Create a list of common libraries shared between all binaries -set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum") +set(COMMON_LIBRARIES "dCommon" "dDatabase" "dNet" "raknet" "mariadbConnCpp" "magic_enum" "MD5") # Add platform specific common libraries if(UNIX) diff --git a/dAuthServer/AuthServer.cpp b/dAuthServer/AuthServer.cpp index 5593f0e19..476e1a689 100644 --- a/dAuthServer/AuthServer.cpp +++ b/dAuthServer/AuthServer.cpp @@ -82,11 +82,11 @@ int main(int argc, char** argv) { Game::randomEngine = std::mt19937(time(0)); //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1001; //LU client is hardcoded to use this for auth port, so I'm making it the default. std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("auth_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + + //LU client is hardcoded to use this for auth port, so I'm making it the default. + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("auth_server_port")).value_or(1001); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; diff --git a/dChatServer/ChatServer.cpp b/dChatServer/ChatServer.cpp index d04cbd010..449570421 100644 --- a/dChatServer/ChatServer.cpp +++ b/dChatServer/ChatServer.cpp @@ -99,18 +99,15 @@ int main(int argc, char** argv) { masterPort = masterInfo->port; } //It's safe to pass 'localhost' here, as the IP is only used as the external IP. - uint32_t maxClients = 999; - uint32_t ourPort = 1501; std::string ourIP = "localhost"; - GeneralUtils::TryParse(Game::config->GetValue("max_clients"), maxClients); - GeneralUtils::TryParse(Game::config->GetValue("chat_server_port"), ourPort); + const uint32_t maxClients = GeneralUtils::TryParse(Game::config->GetValue("max_clients")).value_or(999); + const uint32_t ourPort = GeneralUtils::TryParse(Game::config->GetValue("chat_server_port")).value_or(1501); const auto externalIPString = Game::config->GetValue("external_ip"); if (!externalIPString.empty()) ourIP = externalIPString; Game::server = new dServer(ourIP, ourPort, 0, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::Chat, Game::config, &Game::lastSignal); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::randomEngine = std::mt19937(time(0)); diff --git a/dChatServer/PlayerContainer.cpp b/dChatServer/PlayerContainer.cpp index 95bafd8b9..7d8d7d974 100644 --- a/dChatServer/PlayerContainer.cpp +++ b/dChatServer/PlayerContainer.cpp @@ -15,8 +15,10 @@ #include "dConfig.h" void PlayerContainer::Initialize() { - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends"), m_MaxNumberOfBestFriends); - GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends"), m_MaxNumberOfFriends); + m_MaxNumberOfBestFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_best_friends")).value_or(m_MaxNumberOfBestFriends); + m_MaxNumberOfFriends = + GeneralUtils::TryParse(Game::config->GetValue("max_number_of_friends")).value_or(m_MaxNumberOfFriends); } PlayerContainer::~PlayerContainer() { diff --git a/dCommon/CMakeLists.txt b/dCommon/CMakeLists.txt index 32f240280..c5fff63a9 100644 --- a/dCommon/CMakeLists.txt +++ b/dCommon/CMakeLists.txt @@ -8,11 +8,9 @@ set(DCOMMON_SOURCES "Game.cpp" "GeneralUtils.cpp" "LDFFormat.cpp" - "MD5.cpp" "Metrics.cpp" "NiPoint3.cpp" "NiQuaternion.cpp" - "SHA512.cpp" "Demangler.cpp" "ZCompression.cpp" "BrickByBrickFix.cpp" @@ -68,8 +66,3 @@ else () endif () target_link_libraries(dCommon ZLIB::ZLIB) - -# Disable deprecation warnings on MD5.cpp and SHA512.cpp for Apple Clang -if (APPLE) - set_source_files_properties("MD5.cpp" "SHA512.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") -endif() diff --git a/dCommon/GeneralUtils.cpp b/dCommon/GeneralUtils.cpp index b45165fa2..78cf4f485 100644 --- a/dCommon/GeneralUtils.cpp +++ b/dCommon/GeneralUtils.cpp @@ -319,7 +319,3 @@ std::vector GeneralUtils::GetSqlFileNamesFromFolder(const std::stri return sortedFiles; } - -bool GeneralUtils::TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst) { - return TryParse(x.c_str(), dst.x) && TryParse(y.c_str(), dst.y) && TryParse(z.c_str(), dst.z); -} diff --git a/dCommon/GeneralUtils.h b/dCommon/GeneralUtils.h index 37291ab80..15659912b 100644 --- a/dCommon/GeneralUtils.h +++ b/dCommon/GeneralUtils.h @@ -1,17 +1,20 @@ #pragma once // C++ -#include +#include +#include #include -#include +#include #include -#include +#include +#include #include #include #include #include "BitStream.h" #include "NiPoint3.h" +#include "dPlatforms.h" #include "Game.h" #include "Logger.h" @@ -123,90 +126,125 @@ namespace GeneralUtils { std::vector GetSqlFileNamesFromFolder(const std::string& folder); + // Concept constraining to enum types template - T Parse(const char* value); + concept Enum = std::is_enum_v; - template <> - inline bool Parse(const char* value) { - return std::stoi(value); - } + // Concept constraining to numeric types + template + concept Numeric = std::integral || Enum || std::floating_point; - template <> - inline int32_t Parse(const char* value) { - return std::stoi(value); - } + // Concept trickery to enable parsing underlying numeric types + template + struct numeric_parse { using type = T; }; - template <> - inline int64_t Parse(const char* value) { - return std::stoll(value); - } + // If an enum, present an alias to its underlying type for parsing + template requires Enum + struct numeric_parse { using type = std::underlying_type_t; }; - template <> - inline float Parse(const char* value) { - return std::stof(value); - } + // If a boolean, present an alias to an intermediate integral type for parsing + template requires std::same_as + struct numeric_parse { using type = uint32_t; }; - template <> - inline double Parse(const char* value) { - return std::stod(value); - } + // Shorthand type alias + template + using numeric_parse_t = numeric_parse::type; - template <> - inline uint16_t Parse(const char* value) { - return std::stoul(value); - } + /** + * For numeric values: Parses a string_view and returns an optional variable depending on the result. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) { + numeric_parse_t result; - template <> - inline uint32_t Parse(const char* value) { - return std::stoul(value); - } + const char* const strEnd = str.data() + str.size(); + const auto [parseEnd, ec] = std::from_chars(str.data(), strEnd, result); + const bool isParsed = parseEnd == strEnd && ec == std::errc{}; - template <> - inline uint64_t Parse(const char* value) { - return std::stoull(value); + return isParsed ? static_cast(result) : std::optional{}; } - template <> - inline eInventoryType Parse(const char* value) { - return static_cast(std::stoul(value)); - } +#ifdef DARKFLAME_PLATFORM_MACOS - template <> - inline eReplicaComponentType Parse(const char* value) { - return static_cast(std::stoul(value)); - } + // Anonymous namespace containing MacOS floating-point parse function specializations + namespace { + template + [[nodiscard]] T Parse(const std::string_view str, size_t* parseNum); - template - bool TryParse(const char* value, T& dst) { - try { - dst = Parse(value); + template <> + [[nodiscard]] float Parse(const std::string_view str, size_t* parseNum) { + return std::stof(std::string{ str }, parseNum); + } - return true; - } catch (...) { - return false; + template <> + [[nodiscard]] double Parse(const std::string_view str, size_t* parseNum) { + return std::stod(std::string{ str }, parseNum); + } + + template <> + [[nodiscard]] long double Parse(const std::string_view str, size_t* parseNum) { + return std::stold(std::string{ str }, parseNum); } } - template - T Parse(const std::string& value) { - return Parse(value.c_str()); + /** + * For floating-point values: Parses a string_view and returns an optional variable depending on the result. + * Note that this function overload is only included for MacOS, as from_chars will fulfill its purpose otherwise. + * @param str The string_view to be evaluated + * @returns An std::optional containing the desired value if it is equivalent to the string + */ + template + [[nodiscard]] std::optional TryParse(const std::string_view str) noexcept try { + size_t parseNum; + const T result = Parse(str, &parseNum); + const bool isParsed = str.length() == parseNum; + + return isParsed ? result : std::optional{}; + } catch (...) { + return std::nullopt; } +#endif + + /** + * The TryParse overload for handling NiPoint3 by passing 3 seperate string references + * @param strX The string representing the X coordinate + * @param strY The string representing the Y coordinate + * @param strZ The string representing the Z coordinate + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ template - bool TryParse(const std::string& value, T& dst) { - return TryParse(value.c_str(), dst); + [[nodiscard]] std::optional TryParse(const std::string& strX, const std::string& strY, const std::string& strZ) { + const auto x = TryParse(strX); + if (!x) return std::nullopt; + + const auto y = TryParse(strY); + if (!y) return std::nullopt; + + const auto z = TryParse(strZ); + return z ? std::make_optional(x.value(), y.value(), z.value()) : std::nullopt; } - bool TryParse(const std::string& x, const std::string& y, const std::string& z, NiPoint3& dst); + /** + * The TryParse overload for handling NiPoint3 by passingn a reference to a vector of three strings + * @param str The string vector representing the X, Y, and Xcoordinates + * @returns An std::optional containing the desired NiPoint3 if it can be constructed from the string parameters + */ + template + [[nodiscard]] std::optional TryParse(const std::vector& str) { + return (str.size() == 3) ? TryParse(str[0], str[1], str[2]) : std::nullopt; + } - template + template std::u16string to_u16string(T value) { return GeneralUtils::ASCIIToUTF16(std::to_string(value)); } // From boost::hash_combine template - void hash_combine(std::size_t& s, const T& v) { + constexpr void hash_combine(std::size_t& s, const T& v) { std::hash h; s ^= h(v) + 0x9e3779b9 + (s << 6) + (s >> 2); } @@ -239,10 +277,8 @@ namespace GeneralUtils { * @param entry Enum entry to cast * @returns The enum entry's value in its underlying type */ - template - inline constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) { - static_assert(std::is_enum_v, "Not an enum"); - + template + constexpr typename std::underlying_type_t CastUnderlyingType(const eType entry) noexcept { return static_cast>(entry); } diff --git a/dCommon/LDFFormat.cpp b/dCommon/LDFFormat.cpp index 67f6a6300..da28ae6e0 100644 --- a/dCommon/LDFFormat.cpp +++ b/dCommon/LDFFormat.cpp @@ -61,33 +61,33 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_S32: { - int32_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid int32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_FLOAT: { - float data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid float value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_DOUBLE: { - double data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid double value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } @@ -100,10 +100,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = 0; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid uint32 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -118,10 +120,12 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } else if (ldfTypeAndValue.second == "false") { data = false; } else { - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto dataOptional = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!dataOptional) { LOG("Warning: Attempted to process invalid bool value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } + data = dataOptional.value(); } returnValue = new LDFData(key, data); @@ -129,22 +133,22 @@ LDFBaseData* LDFBaseData::DataFromString(const std::string_view& format) { } case LDF_TYPE_U64: { - uint64_t data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid uint64 value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } case LDF_TYPE_OBJID: { - LWOOBJID data; - if (!GeneralUtils::TryParse(ldfTypeAndValue.second.data(), data)) { + const auto data = GeneralUtils::TryParse(ldfTypeAndValue.second); + if (!data) { LOG("Warning: Attempted to process invalid LWOOBJID value (%s) from string (%s)", ldfTypeAndValue.second.data(), format.data()); return nullptr; } - returnValue = new LDFData(key, data); + returnValue = new LDFData(key, data.value()); break; } diff --git a/dCommon/SHA512.cpp b/dCommon/SHA512.cpp deleted file mode 100644 index e3c2d9f79..000000000 --- a/dCommon/SHA512.cpp +++ /dev/null @@ -1,154 +0,0 @@ -// Source: http://www.zedwood.com/article/cpp-sha512-function - -#include "SHA512.h" - -#include -#include - -const unsigned long long SHA512::sha512_k[80] = //ULL = uint64 -{ 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL }; - -void SHA512::transform(const unsigned char* message, unsigned int block_nb) { - uint64 w[80]; - uint64 wv[8]; - uint64 t1, t2; - const unsigned char* sub_block; - int i, j; - for (i = 0; i < (int)block_nb; i++) { - sub_block = message + (i << 7); - for (j = 0; j < 16; j++) { - SHA2_PACK64(&sub_block[j << 3], &w[j]); - } - for (j = 16; j < 80; j++) { - w[j] = SHA512_F4(w[j - 2]) + w[j - 7] + SHA512_F3(w[j - 15]) + w[j - 16]; - } - for (j = 0; j < 8; j++) { - wv[j] = m_h[j]; - } - for (j = 0; j < 80; j++) { - t1 = wv[7] + SHA512_F2(wv[4]) + SHA2_CH(wv[4], wv[5], wv[6]) - + sha512_k[j] + w[j]; - t2 = SHA512_F1(wv[0]) + SHA2_MAJ(wv[0], wv[1], wv[2]); - wv[7] = wv[6]; - wv[6] = wv[5]; - wv[5] = wv[4]; - wv[4] = wv[3] + t1; - wv[3] = wv[2]; - wv[2] = wv[1]; - wv[1] = wv[0]; - wv[0] = t1 + t2; - } - for (j = 0; j < 8; j++) { - m_h[j] += wv[j]; - } - - } -} - -void SHA512::init() { - m_h[0] = 0x6a09e667f3bcc908ULL; - m_h[1] = 0xbb67ae8584caa73bULL; - m_h[2] = 0x3c6ef372fe94f82bULL; - m_h[3] = 0xa54ff53a5f1d36f1ULL; - m_h[4] = 0x510e527fade682d1ULL; - m_h[5] = 0x9b05688c2b3e6c1fULL; - m_h[6] = 0x1f83d9abfb41bd6bULL; - m_h[7] = 0x5be0cd19137e2179ULL; - m_len = 0; - m_tot_len = 0; -} - -void SHA512::update(const unsigned char* message, unsigned int len) { - unsigned int block_nb; - unsigned int new_len, rem_len, tmp_len; - const unsigned char* shifted_message; - tmp_len = SHA384_512_BLOCK_SIZE - m_len; - rem_len = len < tmp_len ? len : tmp_len; - memcpy(&m_block[m_len], message, rem_len); - if (m_len + len < SHA384_512_BLOCK_SIZE) { - m_len += len; - return; - } - new_len = len - rem_len; - block_nb = new_len / SHA384_512_BLOCK_SIZE; - shifted_message = message + rem_len; - transform(m_block, 1); - transform(shifted_message, block_nb); - rem_len = new_len % SHA384_512_BLOCK_SIZE; - memcpy(m_block, &shifted_message[block_nb << 7], rem_len); - m_len = rem_len; - m_tot_len += (block_nb + 1) << 7; -} - -void SHA512::final(unsigned char* digest) { - unsigned int block_nb; - unsigned int pm_len; - unsigned int len_b; - int i; - block_nb = 1 + ((SHA384_512_BLOCK_SIZE - 17) - < (m_len % SHA384_512_BLOCK_SIZE)); - len_b = (m_tot_len + m_len) << 3; - pm_len = block_nb << 7; - memset(m_block + m_len, 0, pm_len - m_len); - m_block[m_len] = 0x80; - SHA2_UNPACK32(len_b, m_block + pm_len - 4); - transform(m_block, block_nb); - for (i = 0; i < 8; i++) { - SHA2_UNPACK64(m_h[i], &digest[i << 3]); - } -} - -std::string sha512(std::string input) { - unsigned char digest[SHA512::DIGEST_SIZE]; - memset(digest, 0, SHA512::DIGEST_SIZE); - class SHA512 ctx; - ctx.init(); - ctx.update((unsigned char*)input.c_str(), input.length()); - ctx.final(digest); - - char buf[2 * SHA512::DIGEST_SIZE + 1]; - buf[2 * SHA512::DIGEST_SIZE] = 0; - for (int i = 0; i < SHA512::DIGEST_SIZE; i++) - sprintf(buf + i * 2, "%02x", digest[i]); - - return std::string(buf); -} diff --git a/dCommon/SHA512.h b/dCommon/SHA512.h deleted file mode 100644 index 512fa645c..000000000 --- a/dCommon/SHA512.h +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -// C++ -#include - -class SHA512 { -protected: - typedef unsigned char uint8; - typedef unsigned int uint32; - typedef unsigned long long uint64; - - const static uint64 sha512_k[]; - static const unsigned int SHA384_512_BLOCK_SIZE = (1024 / 8); - -public: - void init(); - void update(const unsigned char* message, unsigned int len); - void final(unsigned char* digest); - static const unsigned int DIGEST_SIZE = (512 / 8); - -protected: - void transform(const unsigned char* message, unsigned int block_nb); - unsigned int m_tot_len; - unsigned int m_len; - unsigned char m_block[2 * SHA384_512_BLOCK_SIZE]; - uint64 m_h[8]; -}; - -std::string sha512(std::string input); - -#define SHA2_SHFR(x, n) (x >> n) -#define SHA2_ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n))) -#define SHA2_ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n))) -#define SHA2_CH(x, y, z) ((x & y) ^ (~x & z)) -#define SHA2_MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) -#define SHA512_F1(x) (SHA2_ROTR(x, 28) ^ SHA2_ROTR(x, 34) ^ SHA2_ROTR(x, 39)) -#define SHA512_F2(x) (SHA2_ROTR(x, 14) ^ SHA2_ROTR(x, 18) ^ SHA2_ROTR(x, 41)) -#define SHA512_F3(x) (SHA2_ROTR(x, 1) ^ SHA2_ROTR(x, 8) ^ SHA2_SHFR(x, 7)) -#define SHA512_F4(x) (SHA2_ROTR(x, 19) ^ SHA2_ROTR(x, 61) ^ SHA2_SHFR(x, 6)) -#define SHA2_UNPACK32(x, str) \ -{ \ -*((str) + 3) = (uint8) ((x) ); \ -*((str) + 2) = (uint8) ((x) >> 8); \ -*((str) + 1) = (uint8) ((x) >> 16); \ -*((str) + 0) = (uint8) ((x) >> 24); \ -} -#define SHA2_UNPACK64(x, str) \ -{ \ -*((str) + 7) = (uint8) ((x) ); \ -*((str) + 6) = (uint8) ((x) >> 8); \ -*((str) + 5) = (uint8) ((x) >> 16); \ -*((str) + 4) = (uint8) ((x) >> 24); \ -*((str) + 3) = (uint8) ((x) >> 32); \ -*((str) + 2) = (uint8) ((x) >> 40); \ -*((str) + 1) = (uint8) ((x) >> 48); \ -*((str) + 0) = (uint8) ((x) >> 56); \ -} -#define SHA2_PACK64(str, x) \ -{ \ -*(x) = ((uint64) *((str) + 7) ) \ -| ((uint64) *((str) + 6) << 8) \ -| ((uint64) *((str) + 5) << 16) \ -| ((uint64) *((str) + 4) << 24) \ -| ((uint64) *((str) + 3) << 32) \ -| ((uint64) *((str) + 2) << 40) \ -| ((uint64) *((str) + 1) << 48) \ -| ((uint64) *((str) + 0) << 56); \ -} diff --git a/dCommon/dClient/CMakeLists.txt b/dCommon/dClient/CMakeLists.txt index 69bb17127..017a22a52 100644 --- a/dCommon/dClient/CMakeLists.txt +++ b/dCommon/dClient/CMakeLists.txt @@ -1,6 +1,6 @@ set(DCOMMON_DCLIENT_SOURCES + "AssetManager.cpp" "PackIndex.cpp" "Pack.cpp" - "AssetManager.cpp" PARENT_SCOPE ) diff --git a/dCommon/dClient/ClientVersion.h b/dCommon/dClient/ClientVersion.h new file mode 100644 index 000000000..393103ab4 --- /dev/null +++ b/dCommon/dClient/ClientVersion.h @@ -0,0 +1,12 @@ +#ifndef __CLIENTVERSION_H__ +#define __CLIENTVERSION_H__ + +#include + +namespace ClientVersion { + constexpr uint16_t major = 1; + constexpr uint16_t current = 10; + constexpr uint16_t minor = 64; +} + +#endif // !__CLIENTVERSION_H__ diff --git a/dDatabase/CDClientDatabase/CDClientManager.cpp b/dDatabase/CDClientDatabase/CDClientManager.cpp index f270d8493..0e05c0b83 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.cpp +++ b/dDatabase/CDClientDatabase/CDClientManager.cpp @@ -39,6 +39,7 @@ #include "CDFeatureGatingTable.h" #include "CDRailActivatorComponent.h" #include "CDRewardCodesTable.h" +#include "CDPetComponentTable.h" #include @@ -61,6 +62,55 @@ class CDClientConnectionException : public std::exception { } }; +// Using a macro to reduce repetitive code and issues from copy and paste. +// As a note, ## in a macro is used to concatenate two tokens together. + +#define SPECIALIZE_TABLE_STORAGE(table) \ + template<> typename table::StorageType& CDClientManager::GetEntriesMutable() { return table##Entries; }; + +#define DEFINE_TABLE_STORAGE(table) namespace { table::StorageType table##Entries; }; SPECIALIZE_TABLE_STORAGE(table) + +DEFINE_TABLE_STORAGE(CDActivityRewardsTable); +DEFINE_TABLE_STORAGE(CDActivitiesTable); +DEFINE_TABLE_STORAGE(CDAnimationsTable); +DEFINE_TABLE_STORAGE(CDBehaviorParameterTable); +DEFINE_TABLE_STORAGE(CDBehaviorTemplateTable); +DEFINE_TABLE_STORAGE(CDBrickIDTableTable); +DEFINE_TABLE_STORAGE(CDComponentsRegistryTable); +DEFINE_TABLE_STORAGE(CDCurrencyTableTable); +DEFINE_TABLE_STORAGE(CDDestructibleComponentTable); +DEFINE_TABLE_STORAGE(CDEmoteTableTable); +DEFINE_TABLE_STORAGE(CDFeatureGatingTable); +DEFINE_TABLE_STORAGE(CDInventoryComponentTable); +DEFINE_TABLE_STORAGE(CDItemComponentTable); +DEFINE_TABLE_STORAGE(CDItemSetSkillsTable); +DEFINE_TABLE_STORAGE(CDItemSetsTable); +DEFINE_TABLE_STORAGE(CDLevelProgressionLookupTable); +DEFINE_TABLE_STORAGE(CDLootMatrixTable); +DEFINE_TABLE_STORAGE(CDLootTableTable); +DEFINE_TABLE_STORAGE(CDMissionEmailTable); +DEFINE_TABLE_STORAGE(CDMissionNPCComponentTable); +DEFINE_TABLE_STORAGE(CDMissionTasksTable); +DEFINE_TABLE_STORAGE(CDMissionsTable); +DEFINE_TABLE_STORAGE(CDMovementAIComponentTable); +DEFINE_TABLE_STORAGE(CDObjectSkillsTable); +DEFINE_TABLE_STORAGE(CDObjectsTable); +DEFINE_TABLE_STORAGE(CDPhysicsComponentTable); +DEFINE_TABLE_STORAGE(CDPackageComponentTable); +DEFINE_TABLE_STORAGE(CDPetComponentTable); +DEFINE_TABLE_STORAGE(CDProximityMonitorComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyEntranceComponentTable); +DEFINE_TABLE_STORAGE(CDPropertyTemplateTable); +DEFINE_TABLE_STORAGE(CDRailActivatorComponentTable); +DEFINE_TABLE_STORAGE(CDRarityTableTable); +DEFINE_TABLE_STORAGE(CDRebuildComponentTable); +DEFINE_TABLE_STORAGE(CDRewardCodesTable); +DEFINE_TABLE_STORAGE(CDRewardsTable); +DEFINE_TABLE_STORAGE(CDScriptComponentTable); +DEFINE_TABLE_STORAGE(CDSkillBehaviorTable); +DEFINE_TABLE_STORAGE(CDVendorComponentTable); +DEFINE_TABLE_STORAGE(CDZoneTableTable); + void CDClientManager::LoadValuesFromDatabase() { if (!CDClientDatabase::isConnected) throw CDClientConnectionException(); diff --git a/dDatabase/CDClientDatabase/CDClientManager.h b/dDatabase/CDClientDatabase/CDClientManager.h index ae628a369..c1c4443d7 100644 --- a/dDatabase/CDClientDatabase/CDClientManager.h +++ b/dDatabase/CDClientDatabase/CDClientManager.h @@ -1,18 +1,12 @@ -#pragma once - -#include "CDTable.h" - -#include "Singleton.h" +#ifndef __CDCLIENTMANAGER__H__ +#define __CDCLIENTMANAGER__H__ #define UNUSED_TABLE(v) /** * Initialize the CDClient tables so they are all loaded into memory. */ -class CDClientManager : public Singleton { -public: - CDClientManager() = default; - +namespace CDClientManager { void LoadValuesFromDatabase(); void LoadValuesFromDefaults(); @@ -23,7 +17,28 @@ class CDClientManager : public Singleton { * @return A pointer to the requested table. */ template - T* GetTable() { - return &T::Instance(); - } + T* GetTable(); + + /** + * Fetch a table from CDClient + * Note: Calling this function without a template specialization in CDClientManager.cpp will cause a linker error. + * + * @tparam Table type to fetch + * @return A pointer to the requested table. + */ + template + typename T::StorageType& GetEntriesMutable(); +}; + + +// These are included after the CDClientManager namespace declaration as CDTable as of Jan 29 2024 relies on CDClientManager in Templated code. +#include "CDTable.h" + +#include "Singleton.h" + +template +T* CDClientManager::GetTable() { + return &T::Instance(); }; + +#endif //!__CDCLIENTMANAGER__H__ diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp index 998c40955..191114902 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.cpp @@ -1,5 +1,6 @@ #include "CDActivitiesTable.h" + void CDActivitiesTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -13,7 +14,8 @@ void CDActivitiesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Activities"); @@ -39,7 +41,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { entry.noTeamLootOnDeath = tableData.getIntField("noTeamLootOnDeath", -1); entry.optionalPercentage = tableData.getFloatField("optionalPercentage", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -48,7 +50,7 @@ void CDActivitiesTable::LoadValuesFromDatabase() { std::vector CDActivitiesTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h index 75fc602e0..3e1d4c370 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivitiesTable.h @@ -25,15 +25,10 @@ struct CDActivities { float optionalPercentage; }; -class CDActivitiesTable : public CDTable { -private: - std::vector entries; - +class CDActivitiesTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const { return this->entries; } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp index 7795a1774..abe0c50ca 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.cpp @@ -1,5 +1,6 @@ #include "CDActivityRewardsTable.h" + void CDActivityRewardsTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -14,7 +15,8 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ActivityRewards"); @@ -28,7 +30,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { entry.ChallengeRating = tableData.getIntField("ChallengeRating", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -37,7 +39,7 @@ void CDActivityRewardsTable::LoadValuesFromDatabase() { std::vector CDActivityRewardsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h index 40ab17e77..8d07a7186 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDActivityRewardsTable.h @@ -13,15 +13,9 @@ struct CDActivityRewards { std::string description; //!< The description }; -class CDActivityRewardsTable : public CDTable { -private: - std::vector entries; - +class CDActivityRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - std::vector GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp index 7244ddeee..cf461fc91 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.cpp @@ -5,6 +5,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Animations"); + auto& animations = GetEntriesMutable(); while (!tableData.eof()) { std::string animation_type = tableData.getStringField("animation_type", ""); DluAssert(!animation_type.empty()); @@ -24,7 +25,7 @@ void CDAnimationsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } @@ -35,6 +36,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { auto tableData = queryToCache.execQuery(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (tableData.eof()) return false; + auto& animations = GetEntriesMutable(); do { std::string animation_type = tableData.getStringField("animation_type", ""); @@ -55,7 +57,7 @@ bool CDAnimationsTable::CacheData(CppSQLite3Statement& queryToCache) { UNUSED_COLUMN(entry.priority = tableData.getFloatField("priority", 0.0f);) UNUSED_COLUMN(entry.blendTime = tableData.getFloatField("blendTime", 0.0f);) - this->animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); + animations[CDAnimationKey(animation_type, animationGroupID)].push_back(entry); tableData.nextRow(); } while (!tableData.eof()); @@ -68,15 +70,17 @@ void CDAnimationsTable::CacheAnimations(const CDAnimationKey animationKey) { auto query = CDClientDatabase::CreatePreppedStmt("SELECT * FROM Animations WHERE animationGroupID = ? and animation_type = ?"); query.bind(1, static_cast(animationKey.second)); query.bind(2, animationKey.first.c_str()); + auto& animations = GetEntriesMutable(); // If we received a bad lookup, cache it anyways so we do not run the query again. if (!CacheData(query)) { - this->animations[animationKey]; + animations[animationKey]; } } void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { - auto animationEntryCached = this->animations.find(CDAnimationKey("", animationGroupID)); - if (animationEntryCached != this->animations.end()) { + auto& animations = GetEntriesMutable(); + auto animationEntryCached = animations.find(CDAnimationKey("", animationGroupID)); + if (animationEntryCached != animations.end()) { return; } @@ -85,28 +89,29 @@ void CDAnimationsTable::CacheAnimationGroup(AnimationGroupID animationGroupID) { // Cache the query so we don't run the query again. CacheData(query); - this->animations[CDAnimationKey("", animationGroupID)]; + animations[CDAnimationKey("", animationGroupID)]; } -CDAnimationLookupResult CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { +std::optional CDAnimationsTable::GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID) { + auto& animations = GetEntriesMutable(); CDAnimationKey animationKey(animationType, animationGroupID); - auto animationEntryCached = this->animations.find(animationKey); - if (animationEntryCached == this->animations.end()) { + auto animationEntryCached = animations.find(animationKey); + if (animationEntryCached == animations.end()) { this->CacheAnimations(animationKey); } - auto animationEntry = this->animations.find(animationKey); + auto animationEntry = animations.find(animationKey); // If we have only one animation, return it regardless of the chance to play. if (animationEntry->second.size() == 1) { - return CDAnimationLookupResult(animationEntry->second.front()); + return animationEntry->second.front(); } auto randomAnimation = GeneralUtils::GenerateRandomNumber(0, 1); for (auto& animationEntry : animationEntry->second) { randomAnimation -= animationEntry.chance_to_play; // This is how the client gets the random animation. - if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return CDAnimationLookupResult(animationEntry); + if (animationEntry.animation_name != previousAnimationName && randomAnimation <= 0.0f) return animationEntry; } - return CDAnimationLookupResult(); + return std::nullopt; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h index 1b6280ca2..643ef98fb 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDAnimationsTable.h @@ -2,6 +2,11 @@ #include "CDTable.h" #include +#include + +typedef int32_t AnimationGroupID; +typedef std::string AnimationID; +typedef std::pair CDAnimationKey; struct CDAnimation { // uint32_t animationGroupID; @@ -20,12 +25,7 @@ struct CDAnimation { UNUSED_COLUMN(float blendTime;) //!< The blend time }; -typedef LookupResult CDAnimationLookupResult; - -class CDAnimationsTable : public CDTable { - typedef int32_t AnimationGroupID; - typedef std::string AnimationID; - typedef std::pair CDAnimationKey; +class CDAnimationsTable : public CDTable>> { public: void LoadValuesFromDatabase(); /** @@ -38,7 +38,7 @@ class CDAnimationsTable : public CDTable { * @param animationGroupID The animationGroupID to lookup * @return CDAnimationLookupResult */ - [[nodiscard]] CDAnimationLookupResult GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); + [[nodiscard]] std::optional GetAnimation(const AnimationID& animationType, const std::string& previousAnimationName, const AnimationGroupID animationGroupID); /** * Cache a full AnimationGroup by its ID. @@ -58,10 +58,4 @@ class CDAnimationsTable : public CDTable { * @return false */ bool CacheData(CppSQLite3Statement& queryToCache); - - /** - * Each animation is key'd by its animationName and its animationGroupID. Each - * animation has a possible list of animations. This is because there can be animations have a percent chance to play so one is selected at random. - */ - std::map> animations; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp index 708bec4c0..57187c7c1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.cpp @@ -1,6 +1,10 @@ #include "CDBehaviorParameterTable.h" #include "GeneralUtils.h" +namespace { + std::unordered_map m_ParametersList; +}; + uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { uint64_t key = behaviorID; key <<= 31U; @@ -11,6 +15,7 @@ uint64_t GetKey(const uint32_t behaviorID, const uint32_t parameterID) { void CDBehaviorParameterTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorParameter"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { uint32_t behaviorID = tableData.getIntField("behaviorID", -1); auto candidateStringToAdd = std::string(tableData.getStringField("parameterID", "")); @@ -24,7 +29,7 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { uint64_t hash = GetKey(behaviorID, parameterId); float value = tableData.getFloatField("value", -1.0f); - m_Entries.insert(std::make_pair(hash, value)); + entries.insert(std::make_pair(hash, value)); tableData.nextRow(); } @@ -32,22 +37,24 @@ void CDBehaviorParameterTable::LoadValuesFromDatabase() { } float CDBehaviorParameterTable::GetValue(const uint32_t behaviorID, const std::string& name, const float defaultValue) { - auto parameterID = this->m_ParametersList.find(name); - if (parameterID == this->m_ParametersList.end()) return defaultValue; + auto parameterID = m_ParametersList.find(name); + if (parameterID == m_ParametersList.end()) return defaultValue; auto hash = GetKey(behaviorID, parameterID->second); // Search for specific parameter - auto it = m_Entries.find(hash); - return it != m_Entries.end() ? it->second : defaultValue; + auto& entries = GetEntriesMutable(); + auto it = entries.find(hash); + return it != entries.end() ? it->second : defaultValue; } std::map CDBehaviorParameterTable::GetParametersByBehaviorID(uint32_t behaviorID) { + auto& entries = GetEntriesMutable(); uint64_t hashBase = behaviorID; std::map returnInfo; for (auto& [parameterString, parameterId] : m_ParametersList) { uint64_t hash = GetKey(hashBase, parameterId); - auto infoCandidate = m_Entries.find(hash); - if (infoCandidate != m_Entries.end()) { + auto infoCandidate = entries.find(hash); + if (infoCandidate != entries.end()) { returnInfo.insert(std::make_pair(parameterString, infoCandidate->second)); } } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h index 3daa3aa32..ba6ad6c18 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorParameterTable.h @@ -5,12 +5,10 @@ #include #include -class CDBehaviorParameterTable : public CDTable { -private: - typedef uint64_t BehaviorParameterHash; - typedef float BehaviorParameterValue; - std::unordered_map m_Entries; - std::unordered_map m_ParametersList; +typedef uint64_t BehaviorParameterHash; +typedef float BehaviorParameterValue; + +class CDBehaviorParameterTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp index a67398a90..983156e36 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDBehaviorTemplateTable.h" +namespace { + std::unordered_set m_EffectHandles; +}; + void CDBehaviorTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -13,11 +17,9 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); - // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BehaviorTemplate"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDBehaviorTemplate entry; entry.behaviorID = tableData.getIntField("behaviorID", -1); @@ -31,30 +33,17 @@ void CDBehaviorTemplateTable::LoadValuesFromDatabase() { entry.effectHandle = m_EffectHandles.insert(candidateToAdd).first; } - this->entries.push_back(entry); - this->entriesMappedByBehaviorID.insert(std::make_pair(entry.behaviorID, entry)); + entries.insert(std::make_pair(entry.behaviorID, entry)); tableData.nextRow(); } tableData.finalize(); } -std::vector CDBehaviorTemplateTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) - >> cpplinq::where(predicate) - >> cpplinq::to_vector(); - - return data; -} - -const std::vector& CDBehaviorTemplateTable::GetEntries() const { - return this->entries; -} - const CDBehaviorTemplate CDBehaviorTemplateTable::GetByBehaviorID(uint32_t behaviorID) { - auto entry = this->entriesMappedByBehaviorID.find(behaviorID); - if (entry == this->entriesMappedByBehaviorID.end()) { + auto& entries = GetEntriesMutable(); + auto entry = entries.find(behaviorID); + if (entry == entries.end()) { CDBehaviorTemplate entryToReturn; entryToReturn.behaviorID = 0; entryToReturn.effectHandle = m_EffectHandles.end(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h index cbc494a2a..367f5f0a9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBehaviorTemplateTable.h @@ -12,19 +12,9 @@ struct CDBehaviorTemplate { std::unordered_set::iterator effectHandle; //!< The effect handle }; - -class CDBehaviorTemplateTable : public CDTable { -private: - std::vector entries; - std::unordered_map entriesMappedByBehaviorID; - std::unordered_set m_EffectHandles; +class CDBehaviorTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - // Queries the table with a custom "where" clause - std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; - const CDBehaviorTemplate GetByBehaviorID(uint32_t behaviorID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp index abc917b50..c2714396b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.cpp @@ -14,7 +14,8 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM BrickIDTable"); @@ -23,7 +24,7 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { entry.NDObjectID = tableData.getIntField("NDObjectID", -1); entry.LEGOBrickID = tableData.getIntField("LEGOBrickID", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,15 +32,9 @@ void CDBrickIDTableTable::LoadValuesFromDatabase() { } std::vector CDBrickIDTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDBrickIDTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h index 1a9f9a941..9a2c25236 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDBrickIDTableTable.h @@ -16,14 +16,9 @@ struct CDBrickIDTable { //! BrickIDTable table -class CDBrickIDTableTable : public CDTable { -private: - std::vector entries; - +class CDBrickIDTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp index 3cf7ac621..4944c13ba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.cpp @@ -4,14 +4,15 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ComponentsRegistry"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDComponentsRegistry entry; entry.id = tableData.getIntField("id", -1); entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); - this->mappedEntries.insert_or_assign(entry.id, 0); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(entry.id, 0); tableData.nextRow(); } @@ -20,10 +21,11 @@ void CDComponentsRegistryTable::LoadValuesFromDatabase() { } int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue) { - auto exists = mappedEntries.find(id); - if (exists != mappedEntries.end()) { - auto iter = mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == mappedEntries.end() ? defaultValue : iter->second; + auto& entries = GetEntriesMutable(); + auto exists = entries.find(id); + if (exists != entries.end()) { + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); + return iter == entries.end() ? defaultValue : iter->second; } // Now get the data. Get all components of this entity so we dont do a query for each component @@ -38,14 +40,14 @@ int32_t CDComponentsRegistryTable::GetByIDAndType(uint32_t id, eReplicaComponent entry.component_type = static_cast(tableData.getIntField("component_type", 0)); entry.component_id = tableData.getIntField("component_id", -1); - this->mappedEntries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); + entries.insert_or_assign(static_cast(entry.component_type) << 32 | static_cast(entry.id), entry.component_id); tableData.nextRow(); } - mappedEntries.insert_or_assign(id, 0); + entries.insert_or_assign(id, 0); - auto iter = this->mappedEntries.find(static_cast(componentType) << 32 | static_cast(id)); + auto iter = entries.find(static_cast(componentType) << 32 | static_cast(id)); - return iter == this->mappedEntries.end() ? defaultValue : iter->second; + return iter == entries.end() ? defaultValue : iter->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h index 45da7614c..2165f907b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDComponentsRegistryTable.h @@ -13,10 +13,7 @@ struct CDComponentsRegistry { }; -class CDComponentsRegistryTable : public CDTable { -private: - std::unordered_map mappedEntries; //id, component_type, component_id - +class CDComponentsRegistryTable : public CDTable> { public: void LoadValuesFromDatabase(); int32_t GetByIDAndType(uint32_t id, eReplicaComponentType componentType, int32_t defaultValue = 0); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp index deb2b1680..19ac7da09 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.cpp @@ -15,7 +15,8 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM CurrencyTable"); @@ -27,7 +28,7 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { entry.maxvalue = tableData.getIntField("maxvalue", -1); entry.id = tableData.getIntField("id", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,15 +36,9 @@ void CDCurrencyTableTable::LoadValuesFromDatabase() { } std::vector CDCurrencyTableTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDCurrencyTableTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h index 9c68c277b..1cd6c1424 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDCurrencyTableTable.h @@ -18,14 +18,9 @@ struct CDCurrencyTable { }; //! CurrencyTable table -class CDCurrencyTableTable : public CDTable { -private: - std::vector entries; - +class CDCurrencyTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp index 4939a50e5..b1a6f699f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.cpp @@ -13,7 +13,8 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM DestructibleComponent"); @@ -34,7 +35,7 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { entry.isSmashable = tableData.getIntField("isSmashable", -1) == 1 ? true : false; entry.difficultyLevel = tableData.getIntField("difficultyLevel", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -42,15 +43,9 @@ void CDDestructibleComponentTable::LoadValuesFromDatabase() { } std::vector CDDestructibleComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDDestructibleComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h index 0871d9ead..3319907b1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDDestructibleComponentTable.h @@ -20,14 +20,9 @@ struct CDDestructibleComponent { int32_t difficultyLevel; //!< ??? }; -class CDDestructibleComponentTable : public CDTable { -private: - std::vector entries; - +class CDDestructibleComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp index a7f39705a..280528198 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.cpp @@ -2,6 +2,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Emotes"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDEmoteTable entry; entry.ID = tableData.getIntField("id", -1); @@ -21,6 +22,7 @@ void CDEmoteTableTable::LoadValuesFromDatabase() { } CDEmoteTable* CDEmoteTableTable::GetEmote(int32_t id) { + auto& entries = GetEntriesMutable(); auto itr = entries.find(id); return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h index 360cfc38f..ff0b28d13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDEmoteTable.h @@ -26,10 +26,7 @@ struct CDEmoteTable { std::string gateVersion; }; -class CDEmoteTableTable : public CDTable { -private: - std::map entries; - +class CDEmoteTableTable : public CDTable> { public: void LoadValuesFromDatabase(); // Returns an emote by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp index 1a146bf13..407efff7c 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.cpp @@ -14,7 +14,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM FeatureGating"); @@ -26,7 +27,7 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { entry.minor = tableData.getIntField("minor", -1); entry.description = tableData.getStringField("description", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -35,7 +36,8 @@ void CDFeatureGatingTable::LoadValuesFromDatabase() { std::vector CDFeatureGatingTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + auto& entries = GetEntriesMutable(); + std::vector data = cpplinq::from(entries) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -43,6 +45,7 @@ std::vector CDFeatureGatingTable::Query(std::function= entry) { return true; @@ -51,8 +54,3 @@ bool CDFeatureGatingTable::FeatureUnlocked(const CDFeatureGating& feature) const return false; } - -const std::vector& CDFeatureGatingTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h index 5df202e3f..65f333959 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDFeatureGatingTable.h @@ -17,10 +17,7 @@ struct CDFeatureGating { } }; -class CDFeatureGatingTable : public CDTable { -private: - std::vector entries; - +class CDFeatureGatingTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -28,6 +25,4 @@ class CDFeatureGatingTable : public CDTable { std::vector Query(std::function predicate); bool FeatureUnlocked(const CDFeatureGating& feature) const; - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp index 1a21a8999..8cf3d8da3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.cpp @@ -14,7 +14,8 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM InventoryComponent"); @@ -25,7 +26,7 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { entry.count = tableData.getIntField("count", -1); entry.equip = tableData.getIntField("equip", -1) == 1 ? true : false; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,15 +34,9 @@ void CDInventoryComponentTable::LoadValuesFromDatabase() { } std::vector CDInventoryComponentTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDInventoryComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h index 1f5a525df..361e1a90d 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDInventoryComponentTable.h @@ -10,14 +10,9 @@ struct CDInventoryComponent { bool equip; //!< Whether or not to equip the item }; -class CDInventoryComponentTable : public CDTable { -private: - std::vector entries; - +class CDInventoryComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp index 9f7609e9c..0d8b1ad98 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.cpp @@ -17,6 +17,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDItemComponent entry; entry.id = tableData.getIntField("id", -1); @@ -62,7 +63,7 @@ void CDItemComponentTable::LoadValuesFromDatabase() { entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -70,8 +71,9 @@ void CDItemComponentTable::LoadValuesFromDatabase() { } const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skillID) { - const auto& it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(skillID); + if (it != entries.end()) { return it->second; } @@ -129,12 +131,12 @@ const CDItemComponent& CDItemComponentTable::GetItemComponentByID(uint32_t skill entry.forgeType = tableData.getIntField("forgeType", -1); entry.SellMultiplier = tableData.getFloatField("SellMultiplier", -1.0f); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } - const auto& it2 = this->entries.find(skillID); - if (it2 != this->entries.end()) { + const auto& it2 = entries.find(skillID); + if (it2 != entries.end()) { return it2->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h index 014c98010..60a3e4129 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemComponentTable.h @@ -49,10 +49,7 @@ struct CDItemComponent { float SellMultiplier; //!< Something to do with early vendors perhaps (but replaced) }; -class CDItemComponentTable : public CDTable { -private: - std::map entries; - +class CDItemComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static std::map ParseCraftingCurrencies(const CDItemComponent& itemComponent); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp index 0376bad4d..79bd69aec 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSetSkills"); @@ -24,7 +25,7 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { entry.SkillID = tableData.getIntField("SkillID", -1); entry.SkillCastType = tableData.getIntField("SkillCastType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,22 +33,17 @@ void CDItemSetSkillsTable::LoadValuesFromDatabase() { } std::vector CDItemSetSkillsTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDItemSetSkillsTable::GetEntries() const { - return this->entries; -} - std::vector CDItemSetSkillsTable::GetBySkillID(uint32_t SkillSetID) { std::vector toReturn; - for (CDItemSetSkills entry : this->entries) { + for (const auto& entry : GetEntries()) { if (entry.SkillSetID == SkillSetID) toReturn.push_back(entry); if (entry.SkillSetID > SkillSetID) return toReturn; //stop seeking in the db if it's not needed. } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h index ee5fda05e..78e708ae3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetSkillsTable.h @@ -9,16 +9,11 @@ struct CDItemSetSkills { uint32_t SkillCastType; //!< The skill cast type }; -class CDItemSetSkillsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - const std::vector& GetEntries() const; - std::vector GetBySkillID(uint32_t SkillSetID); }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp index f3859ae22..77b3b1e79 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.cpp @@ -14,7 +14,8 @@ void CDItemSetsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ItemSets"); @@ -36,7 +37,7 @@ void CDItemSetsTable::LoadValuesFromDatabase() { entry.kitID = tableData.getIntField("kitID", -1); entry.priority = tableData.getFloatField("priority", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -45,14 +46,9 @@ void CDItemSetsTable::LoadValuesFromDatabase() { std::vector CDItemSetsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDItemSetsTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h index 77cc0c351..45b915905 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDItemSetsTable.h @@ -21,15 +21,10 @@ struct CDItemSets { float priority; //!< The priority }; -class CDItemSetsTable : public CDTable { -private: - std::vector entries; - +class CDItemSetsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp index 930f3a852..284cf4843 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.cpp @@ -14,7 +14,8 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LevelProgressionLookup"); @@ -24,7 +25,7 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { entry.requiredUScore = tableData.getIntField("requiredUScore", -1); entry.BehaviorEffect = tableData.getStringField("BehaviorEffect", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -33,14 +34,9 @@ void CDLevelProgressionLookupTable::LoadValuesFromDatabase() { std::vector CDLevelProgressionLookupTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDLevelProgressionLookupTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h index fa1bb4ccd..050d910e9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLevelProgressionLookupTable.h @@ -9,15 +9,10 @@ struct CDLevelProgressionLookup { std::string BehaviorEffect; //!< The behavior effect attached to this }; -class CDLevelProgressionLookupTable : public CDTable { -private: - std::vector entries; - +class CDLevelProgressionLookupTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp index 36bebb69e..cd8ae5c42 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.cpp @@ -25,7 +25,8 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootMatrix"); @@ -33,14 +34,15 @@ void CDLootMatrixTable::LoadValuesFromDatabase() { CDLootMatrix entry; uint32_t lootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries[lootMatrixIndex].push_back(ReadRow(tableData)); + entries[lootMatrixIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } } const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { - auto itr = this->entries.find(matrixId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(matrixId); + if (itr != entries.end()) { return itr->second; } @@ -49,10 +51,10 @@ const LootMatrixEntries& CDLootMatrixTable::GetMatrix(uint32_t matrixId) { auto tableData = query.execQuery(); while (!tableData.eof()) { - this->entries[matrixId].push_back(ReadRow(tableData)); + entries[matrixId].push_back(ReadRow(tableData)); tableData.nextRow(); } - return this->entries[matrixId]; + return entries[matrixId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h index c7157e07b..b0ce7e0fa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootMatrixTable.h @@ -16,7 +16,7 @@ struct CDLootMatrix { typedef uint32_t LootMatrixIndex; typedef std::vector LootMatrixEntries; -class CDLootMatrixTable : public CDTable { +class CDLootMatrixTable : public CDTable> { public: void LoadValuesFromDatabase(); @@ -24,6 +24,5 @@ class CDLootMatrixTable : public CDTable { const LootMatrixEntries& GetMatrix(uint32_t matrixId); private: CDLootMatrix ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp index a90f81088..d5e9d4dc6 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.cpp @@ -6,8 +6,8 @@ // Sort the tables by their rarity so the highest rarity items are first. void SortTable(LootTableEntries& table) { - auto* componentsRegistryTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); + auto* componentsRegistryTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); // We modify the table in place so the outer loop keeps track of what is sorted // and the inner loop finds the highest rarity item and swaps it with the current position // of the outer loop. @@ -49,7 +49,8 @@ void CDLootTableTable::LoadValuesFromDatabase() { } // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM LootTable"); @@ -57,17 +58,18 @@ void CDLootTableTable::LoadValuesFromDatabase() { CDLootTable entry; uint32_t lootTableIndex = tableData.getIntField("LootTableIndex", -1); - this->entries[lootTableIndex].push_back(ReadRow(tableData)); + entries[lootTableIndex].push_back(ReadRow(tableData)); tableData.nextRow(); } - for (auto& [id, table] : this->entries) { + for (auto& [id, table] : entries) { SortTable(table); } } const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { - auto itr = this->entries.find(tableId); - if (itr != this->entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(tableId); + if (itr != entries.end()) { return itr->second; } @@ -77,10 +79,10 @@ const LootTableEntries& CDLootTableTable::GetTable(uint32_t tableId) { while (!tableData.eof()) { CDLootTable entry; - this->entries[tableId].push_back(ReadRow(tableData)); + entries[tableId].push_back(ReadRow(tableData)); tableData.nextRow(); } - SortTable(this->entries[tableId]); + SortTable(entries[tableId]); - return this->entries[tableId]; + return entries[tableId]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h index e432d621f..416bd87ae 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDLootTableTable.h @@ -13,10 +13,9 @@ struct CDLootTable { typedef uint32_t LootTableIndex; typedef std::vector LootTableEntries; -class CDLootTableTable : public CDTable { +class CDLootTableTable : public CDTable> { private: CDLootTable ReadRow(CppSQLite3Query& tableData) const; - std::unordered_map entries; public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp index c7e884c2d..1123bfec2 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.cpp @@ -1,7 +1,7 @@ #include "CDMissionEmailTable.h" -void CDMissionEmailTable::LoadValuesFromDatabase() { +void CDMissionEmailTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM MissionEmail"); @@ -14,7 +14,8 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionEmail"); @@ -29,7 +30,7 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { entry.locStatus = tableData.getIntField("locStatus", -1); entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,15 +39,9 @@ void CDMissionEmailTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionEmailTable::Query(std::function predicate) { - - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionEmailTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h index 06c15e719..ac2dba811 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionEmailTable.h @@ -15,14 +15,9 @@ struct CDMissionEmail { }; -class CDMissionEmailTable : public CDTable { -private: - std::vector entries; - +class CDMissionEmailTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp index 87d2bd61c..efe284d45 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.cpp @@ -14,7 +14,8 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionNPCComponent"); @@ -26,7 +27,7 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { entry.acceptsMission = tableData.getIntField("acceptsMission", -1) == 1 ? true : false; entry.gate_version = tableData.getStringField("gate_version", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDMissionNPCComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDMissionNPCComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDMissionNPCComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h index 8c4b790d6..1eba2fad0 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionNPCComponentTable.h @@ -11,17 +11,10 @@ struct CDMissionNPCComponent { std::string gate_version; //!< The gate version }; -class CDMissionNPCComponentTable : public CDTable { -private: - std::vector entries; - +class CDMissionNPCComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp index b2cb9e21a..c5b6620fe 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.cpp @@ -14,7 +14,8 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MissionTasks"); @@ -34,7 +35,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { UNUSED(entry.localize = tableData.getIntField("localize", -1) == 1 ? true : false); UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -43,7 +44,7 @@ void CDMissionTasksTable::LoadValuesFromDatabase() { std::vector CDMissionTasksTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); @@ -53,7 +54,8 @@ std::vector CDMissionTasksTable::Query(std::function CDMissionTasksTable::GetByMissionID(uint32_t missionID) { std::vector tasks; - for (auto& entry : this->entries) { + // TODO: this should not be linear(?) and also shouldnt need to be a pointer + for (auto& entry : GetEntriesMutable()) { if (entry.id == missionID) { tasks.push_back(&entry); } @@ -62,7 +64,6 @@ std::vector CDMissionTasksTable::GetByMissionID(uint32_t missio return tasks; } -const std::vector& CDMissionTasksTable::GetEntries() const { - return this->entries; +const typename CDMissionTasksTable::StorageType& CDMissionTasksTable::GetEntries() const { + return CDTable::GetEntries(); } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h index 420dbfbec..975533591 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionTasksTable.h @@ -19,10 +19,7 @@ struct CDMissionTasks { UNUSED(std::string gate_version); //!< ??? }; -class CDMissionTasksTable : public CDTable { -private: - std::vector entries; - +class CDMissionTasksTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause @@ -30,6 +27,7 @@ class CDMissionTasksTable : public CDTable { std::vector GetByMissionID(uint32_t missionID); - const std::vector& GetEntries() const; + // TODO: Remove this and replace it with a proper lookup function. + const CDTable::StorageType& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp index bc9eb76c4..8862b1dba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.cpp @@ -16,7 +16,8 @@ void CDMissionsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Missions"); @@ -75,7 +76,7 @@ void CDMissionsTable::LoadValuesFromDatabase() { UNUSED(entry.locStatus = tableData.getIntField("locStatus", -1)); entry.reward_bankinventory = tableData.getIntField("reward_bankinventory", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -86,19 +87,15 @@ void CDMissionsTable::LoadValuesFromDatabase() { std::vector CDMissionsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } -const std::vector& CDMissionsTable::GetEntries(void) const { - return this->entries; -} - const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { return const_cast(&entry); } @@ -108,7 +105,7 @@ const CDMissions* CDMissionsTable::GetPtrByMissionID(uint32_t missionID) const { } const CDMissions& CDMissionsTable::GetByMissionID(uint32_t missionID, bool& found) const { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == missionID) { found = true; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h index de4b21c3c..6ba7b19e9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMissionsTable.h @@ -60,18 +60,12 @@ struct CDMissions { int32_t reward_bankinventory; //!< The amount of bank space this mission rewards }; -class CDMissionsTable : public CDTable { -private: - std::vector entries; - +class CDMissionsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - // Gets all the entries in the table - const std::vector& GetEntries() const; - const CDMissions* GetPtrByMissionID(uint32_t missionID) const; const CDMissions& GetByMissionID(uint32_t missionID, bool& found) const; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp index be1c3d966..48964a590 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.cpp @@ -14,7 +14,8 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM MovementAIComponent"); @@ -29,7 +30,7 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { entry.WanderRadius = tableData.getFloatField("WanderRadius", -1.0f); entry.attachedPath = tableData.getStringField("attachedPath", ""); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -38,14 +39,9 @@ void CDMovementAIComponentTable::LoadValuesFromDatabase() { std::vector CDMovementAIComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDMovementAIComponentTable::GetEntries(void) const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h index 8b415f3aa..34d01e3dc 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDMovementAIComponentTable.h @@ -14,15 +14,9 @@ struct CDMovementAIComponent { std::string attachedPath; }; -class CDMovementAIComponentTable : public CDTable { -private: - std::vector entries; - +class CDMovementAIComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp index 958c6cc8a..9933fe7f3 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.cpp @@ -14,7 +14,8 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ObjectSkills"); @@ -25,7 +26,7 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { entry.castOnType = tableData.getIntField("castOnType", -1); entry.AICombatWeight = tableData.getIntField("AICombatWeight", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,13 +35,9 @@ void CDObjectSkillsTable::LoadValuesFromDatabase() { std::vector CDObjectSkillsTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDObjectSkillsTable::GetEntries() const { - return this->entries; -} diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h index 0b88fb6fd..a2a8d4407 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectSkillsTable.h @@ -10,17 +10,10 @@ struct CDObjectSkills { uint32_t AICombatWeight; //!< ??? }; -class CDObjectSkillsTable : public CDTable { -private: - std::vector entries; - +class CDObjectSkillsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - // Gets all the entries in the table - const std::vector& GetEntries() const; - }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp index 3282e14c7..d1f6771e9 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.cpp @@ -1,5 +1,9 @@ #include "CDObjectsTable.h" +namespace { + CDObjects m_default; +}; + void CDObjectsTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; @@ -14,6 +18,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Objects"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDObjects entry; entry.id = tableData.getIntField("id", -1); @@ -31,7 +36,7 @@ void CDObjectsTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "");) UNUSED_COLUMN(entry.HQ_valid = tableData.getIntField("HQ_valid", -1);) - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -41,8 +46,9 @@ void CDObjectsTable::LoadValuesFromDatabase() { } const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { - const auto& it = this->entries.find(LOT); - if (it != this->entries.end()) { + auto& entries = GetEntriesMutable(); + const auto& it = entries.find(LOT); + if (it != entries.end()) { return it->second; } @@ -51,7 +57,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { auto tableData = query.execQuery(); if (tableData.eof()) { - this->entries.insert(std::make_pair(LOT, m_default)); + entries.insert(std::make_pair(LOT, m_default)); return m_default; } @@ -73,7 +79,7 @@ const CDObjects& CDObjectsTable::GetByID(uint32_t LOT) { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.HQ_valid = tableData.getIntField("HQ_valid", -1)); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h index 2ef47727a..add21c8f1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDObjectsTable.h @@ -20,11 +20,7 @@ struct CDObjects { UNUSED(uint32_t HQ_valid); //!< Probably used for the Nexus HQ database on LEGOUniverse.com }; -class CDObjectsTable : public CDTable { -private: - std::map entries; - CDObjects m_default; - +class CDObjectsTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by ID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp index 8038c7797..da1000269 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.cpp @@ -13,8 +13,8 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PackageComponent"); @@ -24,7 +24,7 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); entry.packageType = tableData.getIntField("packageType", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,15 +34,9 @@ void CDPackageComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDPackageComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDPackageComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h index cc8b06367..ad7003dfd 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPackageComponentTable.h @@ -9,14 +9,9 @@ struct CDPackageComponent { uint32_t packageType; }; -class CDPackageComponentTable : public CDTable { -private: - std::vector entries; - +class CDPackageComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp index c3dd5d508..f3371ecb8 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.cpp @@ -23,10 +23,12 @@ namespace { void CDPetComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PetComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { const uint32_t componentID = tableData.getIntField("id", defaultEntry.id); - auto& entry = m_Entries[componentID]; + auto& entry = entries[componentID]; + entry.id = componentID; UNUSED_COLUMN(entry.minTameUpdateTime = tableData.getFloatField("minTameUpdateTime", defaultEntry.minTameUpdateTime)); UNUSED_COLUMN(entry.maxTameUpdateTime = tableData.getFloatField("maxTameUpdateTime", defaultEntry.maxTameUpdateTime)); @@ -48,12 +50,13 @@ void CDPetComponentTable::LoadValuesFromDatabase() { } void CDPetComponentTable::LoadValuesFromDefaults() { - m_Entries.insert(std::make_pair(defaultEntry.id, defaultEntry)); + GetEntriesMutable().insert(std::make_pair(defaultEntry.id, defaultEntry)); } CDPetComponent& CDPetComponentTable::GetByID(const uint32_t componentID) { - auto itr = m_Entries.find(componentID); - if (itr == m_Entries.end()) { + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + if (itr == entries.end()) { LOG("Unable to load pet component (ID %i) values from database! Using default values instead.", componentID); return defaultEntry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h index fa54e4573..428902534 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPetComponentTable.h @@ -21,7 +21,7 @@ struct CDPetComponent { UNUSED_COLUMN(std::string buffIDs;) }; -class CDPetComponentTable : public CDTable { +class CDPetComponentTable : public CDTable> { public: /** @@ -39,7 +39,4 @@ class CDPetComponentTable : public CDTable { * @returns A reference to the corresponding table, or the default if one could not be found */ CDPetComponent& GetByID(const uint32_t componentID); - -private: - std::map m_Entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp index ebc5327b9..34671f3c6 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.cpp @@ -2,6 +2,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PhysicsComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDPhysicsComponent entry; entry.id = tableData.getIntField("id", -1); @@ -21,7 +22,7 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { UNUSED(entry->friction = tableData.getFloatField("friction")); UNUSED(entry->gravityVolumeAsset = tableData.getStringField("gravityVolumeAsset")); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,7 +30,8 @@ void CDPhysicsComponentTable::LoadValuesFromDatabase() { } CDPhysicsComponent* CDPhysicsComponentTable::GetByID(uint32_t componentID) { - auto itr = m_entries.find(componentID); - return itr != m_entries.end() ? &itr->second : nullptr; + auto& entries = GetEntriesMutable(); + auto itr = entries.find(componentID); + return itr != entries.end() ? &itr->second : nullptr; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h index 5ed33cc9d..f0a621390 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPhysicsComponentTable.h @@ -21,13 +21,10 @@ struct CDPhysicsComponent { UNUSED(std::string gravityVolumeAsset); }; -class CDPhysicsComponentTable : public CDTable { +class CDPhysicsComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); static const std::string GetTableName() { return "PhysicsComponent"; }; CDPhysicsComponent* GetByID(uint32_t componentID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp index c1532c862..dfb591d13 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyEntranceComponentTable.h" +namespace { + CDPropertyEntranceComponent defaultEntry{}; +}; + void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyEntranceComponent;"); while (!tableData.eof()) { @@ -24,7 +29,7 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { tableData.getStringField("groupType", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -32,11 +37,10 @@ void CDPropertyEntranceComponentTable::LoadValuesFromDatabase() { } CDPropertyEntranceComponent CDPropertyEntranceComponentTable::GetByID(uint32_t id) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } return defaultEntry; } - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h index 5c7d0965f..f687b8815 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyEntranceComponentTable.h @@ -9,15 +9,9 @@ struct CDPropertyEntranceComponent { std::string groupType; }; -class CDPropertyEntranceComponentTable : public CDTable { +class CDPropertyEntranceComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause CDPropertyEntranceComponent GetByID(uint32_t id); - - // Gets all the entries in the table - [[nodiscard]] const std::vector& GetEntries() const { return entries; } -private: - std::vector entries{}; - CDPropertyEntranceComponent defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp index 4a1d666e9..4046b6faa 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.cpp @@ -1,5 +1,9 @@ #include "CDPropertyTemplateTable.h" +namespace { + CDPropertyTemplate defaultEntry{}; +}; + void CDPropertyTemplateTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -12,7 +16,8 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableSize.finalize(); - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM PropertyTemplate;"); while (!tableData.eof()) { @@ -23,7 +28,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { tableData.getStringField("spawnName", "") }; - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -31,7 +36,7 @@ void CDPropertyTemplateTable::LoadValuesFromDatabase() { } CDPropertyTemplate CDPropertyTemplateTable::GetByMapID(uint32_t mapID) { - for (const auto& entry : entries) { + for (const auto& entry : GetEntries()) { if (entry.mapID == mapID) return entry; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h index 7261bdf91..e0c6c4851 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDPropertyTemplateTable.h @@ -8,13 +8,9 @@ struct CDPropertyTemplate { std::string spawnName; }; -class CDPropertyTemplateTable : public CDTable { +class CDPropertyTemplateTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "PropertyTemplate"; }; CDPropertyTemplate GetByMapID(uint32_t mapID); -private: - std::vector entries{}; - CDPropertyTemplate defaultEntry{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp index 6edd00b28..279d6408b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.cpp @@ -14,7 +14,8 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ProximityMonitorComponent"); @@ -25,7 +26,7 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { entry.LoadOnClient = tableData.getIntField("LoadOnClient", -1); entry.LoadOnServer = tableData.getIntField("LoadOnServer", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -34,14 +35,9 @@ void CDProximityMonitorComponentTable::LoadValuesFromDatabase() { std::vector CDProximityMonitorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDProximityMonitorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h index 861c900e4..af2c385e1 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDProximityMonitorComponentTable.h @@ -10,14 +10,9 @@ struct CDProximityMonitorComponent { bool LoadOnServer; }; -class CDProximityMonitorComponentTable : public CDTable { -private: - std::vector entries; - +class CDProximityMonitorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); //! Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp index 34ec5826a..72a26beba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.cpp @@ -3,6 +3,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RailActivatorComponent;"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRailActivatorComponent entry; @@ -36,7 +37,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { entry.showNameBillboard = tableData.getIntField("ShowNameBillboard", 0); - m_Entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -44,7 +45,7 @@ void CDRailActivatorComponentTable::LoadValuesFromDatabase() { } CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) const { - for (const auto& entry : m_Entries) { + for (const auto& entry : GetEntries()) { if (entry.id == id) return entry; } @@ -52,10 +53,6 @@ CDRailActivatorComponent CDRailActivatorComponentTable::GetEntryByID(int32_t id) return {}; } -const std::vector& CDRailActivatorComponentTable::GetEntries() const { - return m_Entries; -} - std::pair CDRailActivatorComponentTable::EffectPairFromString(std::string& str) { const auto split = GeneralUtils::SplitString(str, ':'); if (split.size() == 2) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h index d06b2d36c..d9a94d372 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRailActivatorComponent.h @@ -20,13 +20,10 @@ struct CDRailActivatorComponent { bool showNameBillboard; }; -class CDRailActivatorComponentTable : public CDTable { +class CDRailActivatorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "RailActivatorComponent"; }; [[nodiscard]] CDRailActivatorComponent GetEntryByID(int32_t id) const; - [[nodiscard]] const std::vector& GetEntries() const; private: static std::pair EffectPairFromString(std::string& str); - std::vector m_Entries{}; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp index 6f086e345..def273391 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.cpp @@ -14,7 +14,8 @@ void CDRarityTableTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RarityTable order by randmax desc;"); @@ -30,5 +31,5 @@ void CDRarityTableTable::LoadValuesFromDatabase() { } const std::vector& CDRarityTableTable::GetRarityTable(uint32_t id) { - return entries[id]; + return GetEntriesMutable()[id]; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h index 1248350bf..006ac9862 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRarityTableTable.h @@ -6,15 +6,13 @@ struct CDRarityTable { float randmax; uint32_t rarity; + + typedef uint32_t Index; }; typedef std::vector RarityTable; -class CDRarityTableTable : public CDTable { -private: - typedef uint32_t RarityTableIndex; - std::unordered_map> entries; - +class CDRarityTableTable : public CDTable>> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp index 30534936d..8a07db883 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.cpp @@ -14,7 +14,8 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RebuildComponent"); @@ -31,7 +32,7 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { entry.post_imagination_cost = tableData.getIntField("post_imagination_cost", -1); entry.time_before_smash = tableData.getFloatField("time_before_smash", -1.0f); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -40,14 +41,9 @@ void CDRebuildComponentTable::LoadValuesFromDatabase() { std::vector CDRebuildComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -const std::vector& CDRebuildComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h index aed719058..0eeb62ae0 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRebuildComponentTable.h @@ -16,15 +16,10 @@ struct CDRebuildComponent { float time_before_smash; //!< The time before smash }; -class CDRebuildComponentTable : public CDTable { -private: - std::vector entries; - +class CDRebuildComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries() const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp index 4dab9ee95..8ade60a97 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.cpp @@ -14,7 +14,8 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM RewardCodes"); @@ -26,20 +27,20 @@ void CDRewardCodesTable::LoadValuesFromDatabase() { UNUSED_COLUMN(entry.locStatus = tableData.getIntField("locStatus", -1)); UNUSED_COLUMN(entry.gate_version = tableData.getStringField("gate_version", "")); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } } LOT CDRewardCodesTable::GetAttachmentLOT(uint32_t rewardCodeId) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (rewardCodeId == entry.id) return entry.attachmentLOT; } return LOT_NULL; } uint32_t CDRewardCodesTable::GetCodeID(std::string code) const { - for (auto const &entry : this->entries){ + for (auto const &entry : GetEntries()){ if (code == entry.code) return entry.id; } return -1; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h index 1010a572e..aa64c3bba 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardCodesTable.h @@ -13,13 +13,9 @@ struct CDRewardCode { }; -class CDRewardCodesTable : public CDTable { -private: - std::vector entries; - +class CDRewardCodesTable : public CDTable> { public: void LoadValuesFromDatabase(); - const std::vector& GetEntries() const; LOT GetAttachmentLOT(uint32_t rewardCodeId) const; uint32_t GetCodeID(std::string code) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp index 27c2344a5..4539e417b 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.cpp @@ -2,6 +2,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM Rewards"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDRewards entry; entry.id = tableData.getIntField("id", -1); @@ -11,7 +12,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { entry.value = tableData.getIntField("value", -1); entry.count = tableData.getIntField("count", -1); - m_entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -20,7 +21,7 @@ void CDRewardsTable::LoadValuesFromDatabase() { std::vector CDRewardsTable::GetByLevelID(uint32_t levelID) { std::vector result{}; - for (const auto& e : m_entries) { + for (const auto& e : GetEntries()) { if (e.second.levelID == levelID) result.push_back(e.second); } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h index 9c24397bb..cec787cfe 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDRewardsTable.h @@ -11,13 +11,9 @@ struct CDRewards { int32_t count; }; -class CDRewardsTable : public CDTable { +class CDRewardsTable : public CDTable> { public: void LoadValuesFromDatabase(); - static const std::string GetTableName() { return "Rewards"; }; std::vector GetByLevelID(uint32_t levelID); - -private: - std::map m_entries; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp index a2fe05142..02e3e29c6 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.cpp @@ -1,5 +1,9 @@ #include "CDScriptComponentTable.h" +namespace { + CDScriptComponent m_ToReturnWhenNoneFound; +}; + void CDScriptComponentTable::LoadValuesFromDatabase() { // First, get the size of the table @@ -15,13 +19,14 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ScriptComponent"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDScriptComponent entry; entry.id = tableData.getIntField("id", -1); entry.script_name = tableData.getStringField("script_name", ""); entry.client_script_name = tableData.getStringField("client_script_name", ""); - this->entries.insert(std::make_pair(entry.id, entry)); + entries.insert(std::make_pair(entry.id, entry)); tableData.nextRow(); } @@ -29,8 +34,9 @@ void CDScriptComponentTable::LoadValuesFromDatabase() { } const CDScriptComponent& CDScriptComponentTable::GetByID(uint32_t id) { - std::map::iterator it = this->entries.find(id); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(id); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h index 56296776a..96c1b5a5f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDScriptComponentTable.h @@ -9,11 +9,7 @@ struct CDScriptComponent { std::string client_script_name; //!< The client script name }; -class CDScriptComponentTable : public CDTable { -private: - std::map entries; - CDScriptComponent m_ToReturnWhenNoneFound; - +class CDScriptComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Gets an entry by scriptID diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp index 51ed7de3c..0df678844 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.cpp @@ -1,8 +1,10 @@ #include "CDSkillBehaviorTable.h" -void CDSkillBehaviorTable::LoadValuesFromDatabase() { - m_empty = CDSkillBehavior(); +namespace { + CDSkillBehavior m_empty = CDSkillBehavior(); +}; +void CDSkillBehaviorTable::LoadValuesFromDatabase() { // First, get the size of the table uint32_t size = 0; auto tableSize = CDClientDatabase::ExecuteQuery("SELECT COUNT(*) FROM SkillBehavior"); @@ -14,8 +16,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { tableSize.finalize(); - // Reserve the size - //this->entries.reserve(size); + auto& entries = GetEntriesMutable(); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM SkillBehavior"); @@ -41,7 +42,7 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); UNUSED(entry.cancelType = tableData.getIntField("cancelType", -1)); - this->entries.insert(std::make_pair(entry.skillID, entry)); + entries.insert(std::make_pair(entry.skillID, entry)); //this->entries.push_back(entry); tableData.nextRow(); } @@ -50,8 +51,9 @@ void CDSkillBehaviorTable::LoadValuesFromDatabase() { } const CDSkillBehavior& CDSkillBehaviorTable::GetSkillByID(uint32_t skillID) { - std::map::iterator it = this->entries.find(skillID); - if (it != this->entries.end()) { + auto& entries = GetEntries(); + auto it = entries.find(skillID); + if (it != entries.end()) { return it->second; } diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h index 0c970be63..19225d193 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDSkillBehaviorTable.h @@ -25,11 +25,7 @@ struct CDSkillBehavior { UNUSED(uint32_t cancelType); //!< The cancel type (?) }; -class CDSkillBehaviorTable : public CDTable { -private: - std::map entries; - CDSkillBehavior m_empty; - +class CDSkillBehaviorTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h index ab9651279..4e896dbb5 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDTable.h @@ -1,6 +1,7 @@ #pragma once #include "CDClientDatabase.h" +#include "CDClientManager.h" #include "Singleton.h" #include "DluAssert.h" @@ -27,22 +28,23 @@ #define UNUSED_ENTRY(v, x) #pragma warning (disable : 4244) //Disable double to float conversion warnings -#pragma warning (disable : 4715) //Disable "not all control paths return a value" +// #pragma warning (disable : 4715) //Disable "not all control paths return a value" -template +template class CDTable : public Singleton
{ +public: + typedef Storage StorageType; + protected: virtual ~CDTable() = default; -}; -template -class LookupResult { - typedef std::pair DataType; -public: - LookupResult() { m_data.first = T(); m_data.second = false; }; - LookupResult(T& data) { m_data.first = data; m_data.second = true; }; - inline const T& Data() { return m_data.first; }; - inline const bool& FoundData() { return m_data.second; }; -private: - DataType m_data; + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] StorageType& GetEntriesMutable() const { + return CDClientManager::GetEntriesMutable
(); + } + + // If you need these for a specific table, override it such that there is a public variant. + [[nodiscard]] const StorageType& GetEntries() const { + return GetEntriesMutable(); + } }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp index 990d0b323..f639a7e30 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.cpp @@ -14,7 +14,8 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { tableSize.finalize(); // Reserve the size - this->entries.reserve(size); + auto& entries = GetEntriesMutable(); + entries.reserve(size); // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM VendorComponent"); @@ -26,7 +27,7 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { entry.refreshTimeSeconds = tableData.getFloatField("refreshTimeSeconds", -1.0f); entry.LootMatrixIndex = tableData.getIntField("LootMatrixIndex", -1); - this->entries.push_back(entry); + entries.push_back(entry); tableData.nextRow(); } @@ -36,15 +37,9 @@ void CDVendorComponentTable::LoadValuesFromDatabase() { //! Queries the table with a custom "where" clause std::vector CDVendorComponentTable::Query(std::function predicate) { - std::vector data = cpplinq::from(this->entries) + std::vector data = cpplinq::from(GetEntries()) >> cpplinq::where(predicate) >> cpplinq::to_vector(); return data; } - -//! Gets all the entries in the table -const std::vector& CDVendorComponentTable::GetEntries() const { - return this->entries; -} - diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h index 133ce78f5..cbed2d132 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDVendorComponentTable.h @@ -11,15 +11,10 @@ struct CDVendorComponent { uint32_t LootMatrixIndex; //!< LootMatrixIndex of the vendor's items }; -class CDVendorComponentTable : public CDTable { -private: - std::vector entries; - +class CDVendorComponentTable : public CDTable> { public: void LoadValuesFromDatabase(); // Queries the table with a custom "where" clause std::vector Query(std::function predicate); - - const std::vector& GetEntries(void) const; }; diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp index b599c37f4..6aaeb854f 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.cpp @@ -15,6 +15,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { // Now get the data auto tableData = CDClientDatabase::ExecuteQuery("SELECT * FROM ZoneTable"); + auto& entries = GetEntriesMutable(); while (!tableData.eof()) { CDZoneTable entry; entry.zoneID = tableData.getIntField("zoneID", -1); @@ -45,7 +46,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { UNUSED(entry.gate_version = tableData.getStringField("gate_version", "")); entry.mountsAllowed = tableData.getIntField("mountsAllowed", -1) == 1 ? true : false; - this->m_Entries.insert(std::make_pair(entry.zoneID, entry)); + entries.insert(std::make_pair(entry.zoneID, entry)); tableData.nextRow(); } @@ -54,6 +55,7 @@ void CDZoneTableTable::LoadValuesFromDatabase() { //! Queries the table with a zoneID to find. const CDZoneTable* CDZoneTableTable::Query(uint32_t zoneID) { + auto& m_Entries = GetEntries(); const auto& iter = m_Entries.find(zoneID); if (iter != m_Entries.end()) { diff --git a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h index 5f5970ae5..b1e8b1bad 100644 --- a/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h +++ b/dDatabase/CDClientDatabase/CDClientTables/CDZoneTableTable.h @@ -33,10 +33,7 @@ struct CDZoneTable { bool mountsAllowed; //!< Whether or not mounts are allowed }; -class CDZoneTableTable : public CDTable { -private: - std::map m_Entries; - +class CDZoneTableTable : public CDTable> { public: void LoadValuesFromDatabase(); diff --git a/dGame/CMakeLists.txt b/dGame/CMakeLists.txt index 4d9a3e501..627f163a9 100644 --- a/dGame/CMakeLists.txt +++ b/dGame/CMakeLists.txt @@ -2,7 +2,6 @@ set(DGAME_SOURCES "Character.cpp" "Entity.cpp" "EntityManager.cpp" "LeaderboardManager.cpp" - "Player.cpp" "PlayerManager.cpp" "TeamManager.cpp" "TradingManager.cpp" diff --git a/dGame/Character.h b/dGame/Character.h index 6c8ead30b..b994fb61a 100644 --- a/dGame/Character.h +++ b/dGame/Character.h @@ -457,6 +457,8 @@ class Character { void SetBillboardVisible(bool visible); + User* GetParentUser() const { return m_ParentUser; } + private: void UpdateInfoFromDatabase(); /** diff --git a/dGame/Entity.cpp b/dGame/Entity.cpp index 89b925c62..161698878 100644 --- a/dGame/Entity.cpp +++ b/dGame/Entity.cpp @@ -15,7 +15,6 @@ #include "Spawner.h" #include "UserManager.h" #include "dpWorld.h" -#include "Player.h" #include "LUTriggers.h" #include "User.h" #include "EntityTimer.h" @@ -26,6 +25,7 @@ #include "eObjectBits.h" #include "PositionUpdate.h" #include "eChatMessageType.h" +#include "PlayerManager.h" //Component includes: #include "Component.h" @@ -95,7 +95,7 @@ #include "CDSkillBehaviorTable.h" #include "CDZoneTableTable.h" -Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) { +Entity::Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser, Entity* parentEntity) { m_ObjectID = objectID; m_TemplateID = info.lot; m_ParentEntity = parentEntity; @@ -124,9 +124,42 @@ Entity::Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity) m_SpawnerNodeID = info.spawnerNodeID; if (info.lot != 1) m_PlayerIsReadyForUpdates = true; + if (parentUser) { + m_Character = parentUser->GetLastUsedChar(); + parentUser->SetLoggedInChar(objectID); + m_GMLevel = m_Character->GetGMLevel(); + + m_Character->SetEntity(this); + + PlayerManager::AddPlayer(this); + } } Entity::~Entity() { + if (IsPlayer()) { + LOG("Deleted player"); + + // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. + if (!PlayerManager::RemovePlayer(this)) { + LOG("Unable to find player to remove from manager."); + return; + } + + Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); + for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { + script->OnPlayerExit(zoneControl, this); + } + + std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); + for (Entity* scriptEntity : scriptedActs) { + if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds + for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { + script->OnPlayerExit(scriptEntity, this); + } + } + } + } + if (m_Character) { m_Character->SaveXMLToDatabase(); } @@ -182,7 +215,7 @@ void Entity::Initialize() { } // Get the registry table - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); /** * Special case for BBB models. They have components not corresponding to the registry. @@ -212,7 +245,7 @@ void Entity::Initialize() { * Not all components are implemented. Some are represented by a nullptr, as they hold no data. */ - if (GetParentUser()) { + if (m_Character && m_Character->GetParentUser()) { AddComponent()->LoadFromXml(m_Character->GetXMLDoc()); } @@ -336,7 +369,7 @@ void Entity::Initialize() { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); bool isSmashable = GetVarAs(u"is_smashable") != 0; @@ -371,7 +404,7 @@ void Entity::Initialize() { uint32_t npcMinLevel = destCompData[0].level; uint32_t currencyIndex = destCompData[0].CurrencyIndex; - CDCurrencyTableTable* currencyTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTable = CDClientManager::GetTable(); std::vector currencyValues = currencyTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == currencyIndex && entry.npcminlevel == npcMinLevel); }); if (currencyValues.size() > 0) { @@ -419,10 +452,10 @@ void Entity::Initialize() { if (!setFaction.empty()) { // TODO also split on space here however we do not have a general util for splitting on multiple characters yet. std::vector factionsToAdd = GeneralUtils::SplitString(setFaction, ';'); - int32_t factionToAdd; for (const auto faction : factionsToAdd) { - if (GeneralUtils::TryParse(faction, factionToAdd)) { - comp->AddFaction(factionToAdd, true); + const auto factionToAdd = GeneralUtils::TryParse(faction); + if (factionToAdd) { + comp->AddFaction(factionToAdd.value(), true); } } } @@ -437,7 +470,8 @@ void Entity::Initialize() { AddComponent(); - AddComponent(m_Character)->LoadFromXml(m_Character->GetXMLDoc()); + auto& systemAddress = m_Character->GetParentUser() ? m_Character->GetParentUser()->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; + AddComponent(m_Character, systemAddress)->LoadFromXml(m_Character->GetXMLDoc()); AddComponent(); } @@ -455,7 +489,7 @@ void Entity::Initialize() { * This is a bit of a mess */ - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); int32_t scriptComponentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::SCRIPT, -1); std::string scriptName = ""; @@ -504,7 +538,7 @@ void Entity::Initialize() { // ZoneControl script if (m_TemplateID == 2365) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const auto zoneID = Game::zoneManager->GetZoneID(); const CDZoneTable* zoneData = zoneTable->Query(zoneID.GetMapID()); @@ -527,7 +561,7 @@ void Entity::Initialize() { if (int componentID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::QUICK_BUILD) > 0) { auto* quickBuildComponent = AddComponent(); - CDRebuildComponentTable* rebCompTable = CDClientManager::Instance().GetTable(); + CDRebuildComponentTable* rebCompTable = CDClientManager::GetTable(); std::vector rebCompData = rebCompTable->Query([=](CDRebuildComponent entry) { return (entry.id == quickBuildComponentID); }); if (rebCompData.size() > 0) { @@ -651,7 +685,7 @@ void Entity::Initialize() { int movementAIID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::MOVEMENT_AI); if (movementAIID > 0) { - CDMovementAIComponentTable* moveAITable = CDClientManager::Instance().GetTable(); + CDMovementAIComponentTable* moveAITable = CDClientManager::GetTable(); std::vector moveAIComp = moveAITable->Query([=](CDMovementAIComponent entry) {return (entry.id == movementAIID); }); if (moveAIComp.size() > 0) { @@ -715,7 +749,7 @@ void Entity::Initialize() { int proximityMonitorID = compRegistryTable->GetByIDAndType(m_TemplateID, eReplicaComponentType::PROXIMITY_MONITOR); if (proximityMonitorID > 0) { - CDProximityMonitorComponentTable* proxCompTable = CDClientManager::Instance().GetTable(); + CDProximityMonitorComponentTable* proxCompTable = CDClientManager::GetTable(); std::vector proxCompData = proxCompTable->Query([=](CDProximityMonitorComponent entry) { return (entry.id == proximityMonitorID); }); if (proxCompData.size() > 0) { std::vector proximityStr = GeneralUtils::SplitString(proxCompData[0].Proximities, ','); @@ -788,14 +822,6 @@ bool Entity::operator!=(const Entity& other) const { return other.m_ObjectID != m_ObjectID; } -User* Entity::GetParentUser() const { - if (!IsPlayer()) { - return nullptr; - } - - return static_cast(this)->GetParentUser(); -} - Component* Entity::GetComponent(eReplicaComponentType componentID) const { const auto& index = m_Components.find(componentID); @@ -850,17 +876,12 @@ void Entity::SetProximityRadius(dpEntity* entity, std::string name) { void Entity::SetGMLevel(eGameMasterLevel value) { m_GMLevel = value; - if (GetParentUser()) { - Character* character = GetParentUser()->GetLastUsedChar(); + if (m_Character) m_Character->SetGMLevel(value); - if (character) { - character->SetGMLevel(value); - } - } + auto* characterComponent = GetComponent(); + if (!characterComponent) return; - CharacterComponent* character = GetComponent(); - if (!character) return; - character->SetGMLevel(value); + characterComponent->SetGMLevel(value); GameMessages::SendGMLevelBroadcast(m_ObjectID, value); @@ -1630,18 +1651,23 @@ bool Entity::GetIsDead() const { void Entity::AddLootItem(const Loot::Info& info) { if (!IsPlayer()) return; - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto& droppedLoot = characterComponent->GetDroppedLoot(); droppedLoot.insert(std::make_pair(info.id, info)); } void Entity::PickupItem(const LWOOBJID& objectID) { if (!IsPlayer()) return; InventoryComponent* inv = GetComponent(); - if (!inv) return; + auto* characterComponent = GetComponent(); + if (!inv || !characterComponent) return; - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); - auto& droppedLoot = static_cast(this)->GetDroppedLoot(); + auto& droppedLoot = characterComponent->GetDroppedLoot(); for (const auto& p : droppedLoot) { if (p.first == objectID) { @@ -1652,10 +1678,10 @@ void Entity::PickupItem(const LWOOBJID& objectID) { const CDObjects& object = objectsTable->GetByID(p.second.lot); if (object.id != 0 && object.type == "Powerup") { - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == p.second.lot); }); for (CDObjectSkills skill : skills) { - CDSkillBehaviorTable* skillBehTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehTable->GetSkillByID(skill.skillID); SkillComponent::HandleUnmanaged(behaviorData.behaviorID, GetObjectID()); @@ -1677,22 +1703,28 @@ void Entity::PickupItem(const LWOOBJID& objectID) { bool Entity::CanPickupCoins(uint64_t count) { if (!IsPlayer()) return false; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return false; + + auto droppedCoins = characterComponent->GetDroppedCoins(); if (count > droppedCoins) { return false; } else { - player->SetDroppedCoins(droppedCoins - count); + characterComponent->SetDroppedCoins(droppedCoins - count); return true; } } void Entity::RegisterCoinDrop(uint64_t count) { if (!IsPlayer()) return; - auto* player = static_cast(this); - auto droppedCoins = player->GetDroppedCoins(); + + auto* characterComponent = GetComponent(); + if (!characterComponent) return; + + auto droppedCoins = characterComponent->GetDroppedCoins(); droppedCoins += count; - player->SetDroppedCoins(droppedCoins); + characterComponent->SetDroppedCoins(droppedCoins); } void Entity::AddChild(Entity* child) { @@ -1990,7 +2022,7 @@ std::vector Entity::GetTargetsInPhantom() { // Clean up invalid targets, like disconnected players m_TargetsInPhantom.erase(std::remove_if(m_TargetsInPhantom.begin(), m_TargetsInPhantom.end(), [](const LWOOBJID id) { return !Game::entityManager->GetEntity(id); - }), m_TargetsInPhantom.end()); + }), m_TargetsInPhantom.end()); std::vector enemies; for (const auto id : m_TargetsInPhantom) { @@ -2133,3 +2165,27 @@ void Entity::ProcessPositionUpdate(PositionUpdate& update) { if (updateChar) Game::entityManager->SerializeEntity(this); } + +const SystemAddress& Entity::GetSystemAddress() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetSystemAddress() : UNASSIGNED_SYSTEM_ADDRESS; +} + +const NiPoint3& Entity::GetRespawnPosition() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnPosition() : NiPoint3Constant::ZERO; +} + +const NiQuaternion& Entity::GetRespawnRotation() const { + auto* characterComponent = GetComponent(); + return characterComponent ? characterComponent->GetRespawnRotation() : NiQuaternionConstant::IDENTITY; +} + +void Entity::SetRespawnPos(const NiPoint3& position) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnPos(position); +} +void Entity::SetRespawnRot(const NiQuaternion& rotation) { + auto* characterComponent = GetComponent(); + if (characterComponent) characterComponent->SetRespawnRot(rotation); +} diff --git a/dGame/Entity.h b/dGame/Entity.h index 3074842af..6546e458f 100644 --- a/dGame/Entity.h +++ b/dGame/Entity.h @@ -47,10 +47,10 @@ namespace CppScripts { */ class Entity { public: - explicit Entity(const LWOOBJID& objectID, EntityInfo info, Entity* parentEntity = nullptr); - virtual ~Entity(); + explicit Entity(const LWOOBJID& objectID, EntityInfo info, User* parentUser = nullptr, Entity* parentEntity = nullptr); + ~Entity(); - virtual void Initialize(); + void Initialize(); bool operator==(const Entity& other) const; bool operator!=(const Entity& other) const; @@ -104,9 +104,7 @@ class Entity { const NiQuaternion& GetRotation() const; - virtual User* GetParentUser() const; - - virtual const SystemAddress& GetSystemAddress() const { return UNASSIGNED_SYSTEM_ADDRESS; }; + const SystemAddress& GetSystemAddress() const; /** * Setters @@ -128,11 +126,9 @@ class Entity { void SetRotation(const NiQuaternion& rotation); - virtual void SetRespawnPos(const NiPoint3& position) {} - - virtual void SetRespawnRot(const NiQuaternion& rotation) {} + void SetRespawnPos(const NiPoint3& position); - virtual void SetSystemAddress(const SystemAddress& value) {}; + void SetRespawnRot(const NiQuaternion& rotation); /** * Component management @@ -229,8 +225,8 @@ class Entity { void TriggerEvent(eTriggerEventType event, Entity* optionalTarget = nullptr); void ScheduleDestructionAfterUpdate() { m_ShouldDestroyAfterUpdate = true; } - virtual const NiPoint3& GetRespawnPosition() const { return NiPoint3Constant::ZERO; } - virtual const NiQuaternion& GetRespawnRotation() const { return NiQuaternionConstant::IDENTITY; } + const NiPoint3& GetRespawnPosition() const; + const NiQuaternion& GetRespawnRotation() const; void Sleep(); void Wake(); @@ -399,14 +395,8 @@ const T& Entity::GetVar(const std::u16string& name) const { template T Entity::GetVarAs(const std::u16string& name) const { const auto data = GetVarAsString(name); - - T value; - - if (!GeneralUtils::TryParse(data, value)) { - return LDFData::Default; - } - - return value; + + return GeneralUtils::TryParse(data).value_or(LDFData::Default); } template diff --git a/dGame/EntityManager.cpp b/dGame/EntityManager.cpp index 10655d250..e1f2f46e4 100644 --- a/dGame/EntityManager.cpp +++ b/dGame/EntityManager.cpp @@ -7,7 +7,6 @@ #include "GeneralUtils.h" #include "dServer.h" #include "Spawner.h" -#include "Player.h" #include "SkillComponent.h" #include "SwitchComponent.h" #include "UserManager.h" @@ -118,14 +117,7 @@ Entity* EntityManager::CreateEntity(EntityInfo info, User* user, Entity* parentE info.id = id; - Entity* entity; - - // Check if the entitty if a player, in case use the extended player entity class - if (user != nullptr) { - entity = new Player(id, info, user, parentEntity); - } else { - entity = new Entity(id, info, parentEntity); - } + Entity* entity = new Entity(id, info, user, parentEntity); // Initialize the entity entity->Initialize(); @@ -482,7 +474,7 @@ void EntityManager::UpdateGhosting() { m_PlayersToUpdateGhosting.clear(); } -void EntityManager::UpdateGhosting(Player* player) { +void EntityManager::UpdateGhosting(Entity* player) { if (player == nullptr) { return; } diff --git a/dGame/EntityManager.h b/dGame/EntityManager.h index 33d7aaff6..352b927b0 100644 --- a/dGame/EntityManager.h +++ b/dGame/EntityManager.h @@ -55,7 +55,7 @@ class EntityManager { float GetGhostDistanceMin() const; void QueueGhostUpdate(LWOOBJID playerID); void UpdateGhosting(); - void UpdateGhosting(Player* player); + void UpdateGhosting(Entity* player); void CheckGhosting(Entity* entity); Entity* GetGhostCandidate(int32_t id); bool GetGhostingEnabled() const; diff --git a/dGame/LeaderboardManager.cpp b/dGame/LeaderboardManager.cpp index 1fd49d261..ba9055a74 100644 --- a/dGame/LeaderboardManager.cpp +++ b/dGame/LeaderboardManager.cpp @@ -402,7 +402,7 @@ Leaderboard::Type LeaderboardManager::GetLeaderboardType(const GameID gameID) { auto lookup = leaderboardCache.find(gameID); if (lookup != leaderboardCache.end()) return lookup->second; - auto* activitiesTable = CDClientManager::Instance().GetTable(); + auto* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([gameID](const CDActivities& entry) { return entry.ActivityID == gameID; }); diff --git a/dGame/Player.cpp b/dGame/Player.cpp deleted file mode 100644 index 8f414b43c..000000000 --- a/dGame/Player.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include "Player.h" - -#include - -#include "Character.h" -#include "UserManager.h" -#include "EntityManager.h" -#include "Game.h" -#include "Logger.h" -#include "dZoneManager.h" -#include "User.h" -#include "CppScripts.h" -#include "Loot.h" -#include "eReplicaComponentType.h" -#include "PlayerManager.h" - -void Player::SetRespawnPos(const NiPoint3& position) { - if (!m_Character) return; - - m_respawnPos = position; - - m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); - -} - -void Player::SetRespawnRot(const NiQuaternion& rotation) { - m_respawnRot = rotation; -} - -void Player::SetSystemAddress(const SystemAddress& value) { - m_SystemAddress = value; -} - -Player::Player(const LWOOBJID& objectID, const EntityInfo info, User* user, Entity* parentEntity) : Entity(objectID, info, parentEntity) { - m_ParentUser = user; - m_Character = m_ParentUser->GetLastUsedChar(); - m_ParentUser->SetLoggedInChar(objectID); - m_GMLevel = m_Character->GetGMLevel(); - m_SystemAddress = m_ParentUser->GetSystemAddress(); - m_DroppedCoins = 0; - - m_Character->SetEntity(this); - - PlayerManager::AddPlayer(this); -} - -Player::~Player() { - LOG("Deleted player"); - - // Make sure the player exists first. Remove afterwards to prevent the OnPlayerExist functions from not being able to find the player. - if (!PlayerManager::RemovePlayer(this)) { - LOG("Unable to find player to remove from manager."); - return; - } - - if (IsPlayer()) { - Entity* zoneControl = Game::entityManager->GetZoneControlEntity(); - for (CppScripts::Script* script : CppScripts::GetEntityScripts(zoneControl)) { - script->OnPlayerExit(zoneControl, this); - } - - std::vector scriptedActs = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (Entity* scriptEntity : scriptedActs) { - if (scriptEntity->GetObjectID() != zoneControl->GetObjectID()) { // Don't want to trigger twice on instance worlds - for (CppScripts::Script* script : CppScripts::GetEntityScripts(scriptEntity)) { - script->OnPlayerExit(scriptEntity, this); - } - } - } - } -} diff --git a/dGame/Player.h b/dGame/Player.h deleted file mode 100644 index dd8efd9c1..000000000 --- a/dGame/Player.h +++ /dev/null @@ -1,62 +0,0 @@ -#pragma once - -#include "Entity.h" - -/** - * Extended Entity for player data and behavior. - * - * Contains properties only a player entity would require, like associated SystemAddress and User. - * - * Keeps track of which entities are observed by this user for ghosting. - */ -class Player final : public Entity -{ -public: - explicit Player(const LWOOBJID& objectID, EntityInfo info, User* user, Entity* parentEntity = nullptr); - - /** - * Getters - */ - - User* GetParentUser() const override { return m_ParentUser; }; - - const SystemAddress& GetSystemAddress() const override { return m_SystemAddress; }; - - const NiPoint3& GetRespawnPosition() const override { return m_respawnPos; }; - - const NiQuaternion& GetRespawnRotation() const override { return m_respawnRot; }; - - std::map& GetDroppedLoot() { return m_DroppedLoot; }; - - uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; - - /** - * Setters - */ - - void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; - - void SetSystemAddress(const SystemAddress& value) override; - - void SetRespawnPos(const NiPoint3& position) override; - - void SetRespawnRot(const NiQuaternion& rotation) override; - - /** - * Ghosting - */ - - ~Player() override; -private: - SystemAddress m_SystemAddress; - - NiPoint3 m_respawnPos; - - NiQuaternion m_respawnRot; - - User* m_ParentUser; - - std::map m_DroppedLoot; - - uint64_t m_DroppedCoins; -}; diff --git a/dGame/PlayerManager.cpp b/dGame/PlayerManager.cpp index e3017f05a..61e2568d7 100644 --- a/dGame/PlayerManager.cpp +++ b/dGame/PlayerManager.cpp @@ -1,20 +1,19 @@ #include "PlayerManager.h" #include "Character.h" -#include "Player.h" #include "User.h" #include "UserManager.h" #include "eReplicaComponentType.h" namespace { - std::vector m_Players; + std::vector m_Players; }; -const std::vector& PlayerManager::GetAllPlayers() { +const std::vector& PlayerManager::GetAllPlayers() { return m_Players; } -void PlayerManager::AddPlayer(Player* player) { +void PlayerManager::AddPlayer(Entity* player) { const auto& iter = std::find(m_Players.begin(), m_Players.end(), player); if (iter == m_Players.end()) { @@ -22,7 +21,7 @@ void PlayerManager::AddPlayer(Player* player) { } } -bool PlayerManager::RemovePlayer(Player* player) { +bool PlayerManager::RemovePlayer(Entity* player) { const auto iter = std::find(m_Players.begin(), m_Players.end(), player); const bool toReturn = iter != m_Players.end(); @@ -33,21 +32,21 @@ bool PlayerManager::RemovePlayer(Player* player) { return toReturn; } -Player* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { +Entity* PlayerManager::GetPlayer(const SystemAddress& sysAddr) { auto* entity = UserManager::Instance()->GetUser(sysAddr)->GetLastUsedChar()->GetEntity(); - return static_cast(entity); + return entity; } -Player* PlayerManager::GetPlayer(const std::string& name) { +Entity* PlayerManager::GetPlayer(const std::string& name) { const auto characters = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::CHARACTER); - Player* player = nullptr; + Entity* player = nullptr; for (auto* character : characters) { if (!character->IsPlayer()) continue; if (GeneralUtils::CaseInsensitiveStringCompare(name, character->GetCharacter()->GetName())) { - player = dynamic_cast(character); + player = character; break; } } @@ -55,8 +54,8 @@ Player* PlayerManager::GetPlayer(const std::string& name) { return player; } -Player* PlayerManager::GetPlayer(LWOOBJID playerID) { - Player* playerToReturn = nullptr; +Entity* PlayerManager::GetPlayer(LWOOBJID playerID) { + Entity* playerToReturn = nullptr; for (auto* player : m_Players) { if (player->GetObjectID() == playerID) { playerToReturn = player; diff --git a/dGame/PlayerManager.h b/dGame/PlayerManager.h index bb54f83b3..7f6be5ba9 100644 --- a/dGame/PlayerManager.h +++ b/dGame/PlayerManager.h @@ -5,21 +5,21 @@ #include -class Player; +class Entity; struct SystemAddress; namespace PlayerManager { - void AddPlayer(Player* player); + void AddPlayer(Entity* player); - bool RemovePlayer(Player* player); + bool RemovePlayer(Entity* player); - Player* GetPlayer(const SystemAddress& sysAddr); + Entity* GetPlayer(const SystemAddress& sysAddr); - Player* GetPlayer(const std::string& name); + Entity* GetPlayer(const std::string& name); - Player* GetPlayer(LWOOBJID playerID); + Entity* GetPlayer(LWOOBJID playerID); - const std::vector& GetAllPlayers(); + const std::vector& GetAllPlayers(); }; #endif //!__PLAYERMANAGER__H__ diff --git a/dGame/dBehaviors/Behavior.cpp b/dGame/dBehaviors/Behavior.cpp index c70b34c7b..64bb03f54 100644 --- a/dGame/dBehaviors/Behavior.cpp +++ b/dGame/dBehaviors/Behavior.cpp @@ -82,7 +82,7 @@ CDBehaviorParameterTable* Behavior::BehaviorParameterTable = nullptr; Behavior* Behavior::GetBehavior(const uint32_t behaviorId) { if (BehaviorParameterTable == nullptr) { - BehaviorParameterTable = CDClientManager::Instance().GetTable(); + BehaviorParameterTable = CDClientManager::GetTable(); } const auto pair = Cache.find(behaviorId); @@ -297,7 +297,7 @@ Behavior* Behavior::CreateBehavior(const uint32_t behaviorId) { } BehaviorTemplates Behavior::GetBehaviorTemplate(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); BehaviorTemplates templateID = BehaviorTemplates::BEHAVIOR_EMPTY; // Find behavior template by its behavior id. Default to 0. @@ -405,7 +405,7 @@ void Behavior::PlayFx(std::u16string type, const LWOOBJID target, const LWOOBJID } Behavior::Behavior(const uint32_t behaviorId) { - auto behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto behaviorTemplateTable = CDClientManager::GetTable(); CDBehaviorTemplate templateInDatabase{}; @@ -448,7 +448,7 @@ Behavior::Behavior(const uint32_t behaviorId) { float Behavior::GetFloat(const std::string& name, const float defaultValue) const { // Get the behavior parameter entry and return its value. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); return BehaviorParameterTable->GetValue(this->m_behaviorId, name, defaultValue); } @@ -476,7 +476,7 @@ Behavior* Behavior::GetAction(float value) const { std::map Behavior::GetParameterNames() const { std::map templatesInDatabase; // Find behavior template by its behavior id. - if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::Instance().GetTable(); + if (!BehaviorParameterTable) BehaviorParameterTable = CDClientManager::GetTable(); if (BehaviorParameterTable) { templatesInDatabase = BehaviorParameterTable->GetParametersByBehaviorID(this->m_behaviorId); } diff --git a/dGame/dBehaviors/OverTimeBehavior.cpp b/dGame/dBehaviors/OverTimeBehavior.cpp index bdef2eb61..f66a5253f 100644 --- a/dGame/dBehaviors/OverTimeBehavior.cpp +++ b/dGame/dBehaviors/OverTimeBehavior.cpp @@ -41,7 +41,7 @@ void OverTimeBehavior::Load() { m_Action = GetInt("action"); // Since m_Action is a skillID and not a behavior, get is correlated behaviorID. - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); m_ActionBehaviorId = skillTable->GetSkillByID(m_Action).behaviorID; m_Delay = GetFloat("delay"); diff --git a/dGame/dComponents/ActivityComponent.cpp b/dGame/dComponents/ActivityComponent.cpp index aa6a4604d..49ca4faf1 100644 --- a/dGame/dComponents/ActivityComponent.cpp +++ b/dGame/dComponents/ActivityComponent.cpp @@ -10,7 +10,6 @@ #include "WorldPackets.h" #include "EntityManager.h" #include "ChatPackets.h" -#include "Player.h" #include "BitStreamUtils.h" #include "dServer.h" #include "GeneralUtils.h" @@ -47,7 +46,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo if (destroyableComponent) { // First lookup the loot matrix id for this component id. - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([=](CDActivityRewards entry) {return (entry.LootMatrixIndex == destroyableComponent->GetLootMatrixID()); }); uint32_t startingLMI = 0; @@ -71,7 +70,7 @@ ActivityComponent::ActivityComponent(Entity* parent, int32_t activityID) : Compo } } void ActivityComponent::LoadActivityData(const int32_t activityId) { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([activityId](CDActivities entry) {return (entry.ActivityID == activityId); }); bool soloRacing = Game::config->GetValue("solo_racing") == "1"; @@ -84,7 +83,8 @@ void ActivityComponent::LoadActivityData(const int32_t activityId) { if (m_ActivityInfo.instanceMapID == -1) { const auto& transferOverride = m_Parent->GetVarAsString(u"transferZoneID"); if (!transferOverride.empty()) { - GeneralUtils::TryParse(transferOverride, m_ActivityInfo.instanceMapID); + m_ActivityInfo.instanceMapID = + GeneralUtils::TryParse(transferOverride).value_or(m_ActivityInfo.instanceMapID); } } } @@ -107,7 +107,7 @@ void ActivityComponent::Serialize(RakNet::BitStream* outBitStream, bool bIsIniti } void ActivityComponent::ReloadConfig() { - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([this](CDActivities entry) {return (entry.ActivityID == m_ActivityID); }); for (auto activity : activities) { auto mapID = m_ActivityInfo.instanceMapID; @@ -546,14 +546,14 @@ void ActivityInstance::RewardParticipant(Entity* participant) { } // First, get the activity data - auto* activityRewardsTable = CDClientManager::Instance().GetTable(); + auto* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([this](CDActivityRewards entry) { return (entry.objectTemplate == m_ActivityInfo.ActivityID); }); if (!activityRewards.empty()) { uint32_t minCoins = 0; uint32_t maxCoins = 0; - auto* currencyTableTable = CDClientManager::Instance().GetTable(); + auto* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([=](CDCurrencyTable entry) { return (entry.currencyIndex == activityRewards[0].CurrencyIndex && entry.npcminlevel == 1); }); if (!currencyTable.empty()) { diff --git a/dGame/dComponents/BaseCombatAIComponent.cpp b/dGame/dComponents/BaseCombatAIComponent.cpp index 21909d5f2..171834093 100644 --- a/dGame/dComponents/BaseCombatAIComponent.cpp +++ b/dGame/dComponents/BaseCombatAIComponent.cpp @@ -107,10 +107,10 @@ BaseCombatAIComponent::BaseCombatAIComponent(Entity* parent, const uint32_t id): int32_t collisionGroup = (COLLISION_GROUP_DYNAMIC | COLLISION_GROUP_ENEMY); - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); auto componentID = componentRegistryTable->GetByIDAndType(parent->GetLOT(), eReplicaComponentType::CONTROLLABLE_PHYSICS); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); if (physicsComponentTable != nullptr) { auto* info = physicsComponentTable->GetByID(componentID); diff --git a/dGame/dComponents/BuffComponent.cpp b/dGame/dComponents/BuffComponent.cpp index 10ac4ebbe..cdf1d5bc9 100644 --- a/dGame/dComponents/BuffComponent.cpp +++ b/dGame/dComponents/BuffComponent.cpp @@ -164,7 +164,7 @@ void BuffComponent::ApplyBuff(const int32_t id, const float duration, const LWOO const auto& parameters = GetBuffParameters(id); for (const auto& parameter : parameters) { if (parameter.name == "overtime") { - auto* behaviorTemplateTable = CDClientManager::Instance().GetTable(); + auto* behaviorTemplateTable = CDClientManager::GetTable(); behaviorID = behaviorTemplateTable->GetSkillByID(parameter.values[0]).behaviorID; stacks = static_cast(parameter.values[1]); diff --git a/dGame/dComponents/CharacterComponent.cpp b/dGame/dComponents/CharacterComponent.cpp index 70eec0cf7..e4e2ba4bf 100644 --- a/dGame/dComponents/CharacterComponent.cpp +++ b/dGame/dComponents/CharacterComponent.cpp @@ -24,7 +24,7 @@ #include "WorldPackets.h" #include -CharacterComponent::CharacterComponent(Entity* parent, Character* character) : Component(parent) { +CharacterComponent::CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress) : Component(parent) { m_Character = character; m_IsRacing = false; @@ -46,6 +46,7 @@ CharacterComponent::CharacterComponent(Entity* parent, Character* character) : C m_CurrentActivity = eGameActivity::NONE; m_CountryCode = 0; m_LastUpdateTimestamp = std::time(nullptr); + m_SystemAddress = systemAddress; } bool CharacterComponent::LandingAnimDisabled(int zoneID) { @@ -762,14 +763,14 @@ void CharacterComponent::UpdateClientMinimap(bool showFaction, std::string ventu } void CharacterComponent::AwardClaimCodes() { - if (!m_Parent) return; - auto* user = m_Parent->GetParentUser(); + if (!m_Parent || !m_Parent->GetCharacter()) return; + auto* user = m_Parent->GetCharacter()->GetParentUser(); if (!user) return; auto rewardCodes = Database::Get()->GetRewardCodesByAccountID(user->GetAccountID()); if (rewardCodes.empty()) return; - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); for (auto const rewardCode : rewardCodes) { LOG_DEBUG("Processing RewardCode %i", rewardCode); const uint32_t rewardCodeIndex = rewardCode >> 6; @@ -817,3 +818,20 @@ void CharacterComponent::SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId) const { Game::entityManager->DestructEntity(entity); }); } + +const SystemAddress& CharacterComponent::GetSystemAddress() const { + return m_SystemAddress; +} + +void CharacterComponent::SetRespawnPos(const NiPoint3& position) { + if (!m_Character) return; + + m_respawnPos = position; + + m_Character->SetRespawnPoint(Game::zoneManager->GetZone()->GetWorldID(), position); + +} + +void CharacterComponent::SetRespawnRot(const NiQuaternion& rotation) { + m_respawnRot = rotation; +} diff --git a/dGame/dComponents/CharacterComponent.h b/dGame/dComponents/CharacterComponent.h index a44d359d9..01c26f9ab 100644 --- a/dGame/dComponents/CharacterComponent.h +++ b/dGame/dComponents/CharacterComponent.h @@ -11,6 +11,7 @@ #include "tinyxml2.h" #include "eReplicaComponentType.h" #include +#include "Loot.h" enum class eGameActivity : uint32_t; @@ -65,7 +66,7 @@ class CharacterComponent final : public Component { public: static constexpr eReplicaComponentType ComponentType = eReplicaComponentType::CHARACTER; - CharacterComponent(Entity* parent, Character* character); + CharacterComponent(Entity* parent, Character* character, const SystemAddress& systemAddress); ~CharacterComponent() override; void LoadFromXml(tinyxml2::XMLDocument* doc) override; @@ -289,6 +290,22 @@ class CharacterComponent final : public Component { */ void SendToZone(LWOMAPID zoneId, LWOCLONEID cloneId = 0) const; + const SystemAddress& GetSystemAddress() const; + + const NiPoint3& GetRespawnPosition() const { return m_respawnPos; }; + + void SetRespawnPos(const NiPoint3& position); + + const NiQuaternion& GetRespawnRotation() const { return m_respawnRot; }; + + void SetRespawnRot(const NiQuaternion& rotation); + + std::map& GetDroppedLoot() { return m_DroppedLoot; }; + + uint64_t GetDroppedCoins() const { return m_DroppedCoins; }; + + void SetDroppedCoins(const uint64_t value) { m_DroppedCoins = value; }; + /** * Character info regarding this character, including clothing styles, etc. */ @@ -579,6 +596,16 @@ class CharacterComponent final : public Component { std::array m_ClaimCodes{}; void AwardClaimCodes(); + + SystemAddress m_SystemAddress; + + NiPoint3 m_respawnPos; + + NiQuaternion m_respawnRot; + + std::map m_DroppedLoot; + + uint64_t m_DroppedCoins = 0; }; #endif // CHARACTERCOMPONENT_H diff --git a/dGame/dComponents/DestroyableComponent.cpp b/dGame/dComponents/DestroyableComponent.cpp index 64dca4f1d..68271f26e 100644 --- a/dGame/dComponents/DestroyableComponent.cpp +++ b/dGame/dComponents/DestroyableComponent.cpp @@ -81,7 +81,7 @@ DestroyableComponent::~DestroyableComponent() { } void DestroyableComponent::Reinitialize(LOT templateID) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); int32_t buffComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::BUFF); int32_t collectibleComponentID = compRegistryTable->GetByIDAndType(templateID, eReplicaComponentType::COLLECTIBLE); @@ -92,7 +92,7 @@ void DestroyableComponent::Reinitialize(LOT templateID) { if (quickBuildComponentID > 0) componentID = quickBuildComponentID; if (buffComponentID > 0) componentID = buffComponentID; - CDDestructibleComponentTable* destCompTable = CDClientManager::Instance().GetTable(); + CDDestructibleComponentTable* destCompTable = CDClientManager::GetTable(); std::vector destCompData = destCompTable->Query([=](CDDestructibleComponent entry) { return (entry.id == componentID); }); if (componentID > 0) { @@ -251,13 +251,14 @@ void DestroyableComponent::SetMaxHealth(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "health"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -292,13 +293,14 @@ void DestroyableComponent::SetMaxArmor(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(value)); args.Insert("type", "armor"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); @@ -332,13 +334,14 @@ void DestroyableComponent::SetMaxImagination(float value, bool playAnim) { if (playAnim) { // Now update the player bar - if (!m_Parent->GetParentUser()) return; + auto* characterComponent = m_Parent->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("amount", std::to_string(difference)); args.Insert("type", "imagination"); - GameMessages::SendUIMessageServerToSingleClient(m_Parent, m_Parent->GetParentUser()->GetSystemAddress(), "MaxPlayerBarUpdate", args); + GameMessages::SendUIMessageServerToSingleClient(m_Parent, characterComponent->GetSystemAddress(), "MaxPlayerBarUpdate", args); } Game::entityManager->SerializeEntity(m_Parent); } diff --git a/dGame/dComponents/InventoryComponent.cpp b/dGame/dComponents/InventoryComponent.cpp index 5e6af8859..591e05059 100644 --- a/dGame/dComponents/InventoryComponent.cpp +++ b/dGame/dComponents/InventoryComponent.cpp @@ -14,7 +14,6 @@ #include "Character.h" #include "EntityManager.h" #include "ItemSet.h" -#include "Player.h" #include "PetComponent.h" #include "PossessorComponent.h" #include "PossessableComponent.h" @@ -56,10 +55,10 @@ InventoryComponent::InventoryComponent(Entity* parent, tinyxml2::XMLDocument* do return; } - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto componentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::INVENTORY); - auto* inventoryComponentTable = CDClientManager::Instance().GetTable(); + auto* inventoryComponentTable = CDClientManager::GetTable(); auto items = inventoryComponentTable->Query([=](const CDInventoryComponent entry) { return entry.id == componentId; }); auto slot = 0u; @@ -910,11 +909,11 @@ void InventoryComponent::UnEquipItem(Item* item) { void InventoryComponent::EquipScripts(Item* equippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(equippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -925,11 +924,11 @@ void InventoryComponent::EquipScripts(Item* equippedItem) { } void InventoryComponent::UnequipScripts(Item* unequippedItem) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); if (!compRegistryTable) return; int32_t scriptComponentID = compRegistryTable->GetByIDAndType(unequippedItem->GetLot(), eReplicaComponentType::SCRIPT, -1); if (scriptComponentID > -1) { - CDScriptComponentTable* scriptCompTable = CDClientManager::Instance().GetTable(); + CDScriptComponentTable* scriptCompTable = CDClientManager::GetTable(); CDScriptComponent scriptCompData = scriptCompTable->GetByID(scriptComponentID); auto* itemScript = CppScripts::GetScript(m_Parent, scriptCompData.script_name); if (!itemScript) { @@ -1281,7 +1280,7 @@ bool InventoryComponent::IsTransferInventory(eInventoryType type) { } uint32_t InventoryComponent::FindSkill(const LOT lot) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(lot); @@ -1299,8 +1298,8 @@ uint32_t InventoryComponent::FindSkill(const LOT lot) { std::vector InventoryComponent::FindBuffs(Item* item, bool castOnEquip) const { std::vector buffs; if (item == nullptr) return buffs; - auto* table = CDClientManager::Instance().GetTable(); - auto* behaviors = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); + auto* behaviors = CDClientManager::GetTable(); const auto results = table->Query([=](const CDObjectSkills& entry) { return entry.objectTemplate == static_cast(item->GetLot()); diff --git a/dGame/dComponents/LevelProgressionComponent.cpp b/dGame/dComponents/LevelProgressionComponent.cpp index 3a18b19c8..d271f97b3 100644 --- a/dGame/dComponents/LevelProgressionComponent.cpp +++ b/dGame/dComponents/LevelProgressionComponent.cpp @@ -44,7 +44,7 @@ void LevelProgressionComponent::Serialize(RakNet::BitStream* outBitStream, bool } void LevelProgressionComponent::HandleLevelUp() { - auto* rewardsTable = CDClientManager::Instance().GetTable(); + auto* rewardsTable = CDClientManager::GetTable(); const auto& rewards = rewardsTable->GetByLevelID(m_Level); bool rewardingItem = rewards.size() > 0; diff --git a/dGame/dComponents/MissionComponent.cpp b/dGame/dComponents/MissionComponent.cpp index 7219589af..151fcf2f7 100644 --- a/dGame/dComponents/MissionComponent.cpp +++ b/dGame/dComponents/MissionComponent.cpp @@ -266,7 +266,7 @@ void MissionComponent::ForceProgressValue(uint32_t missionId, uint32_t taskType, } bool MissionComponent::GetMissionInfo(uint32_t missionId, CDMissions& result) { - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missions = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -320,8 +320,8 @@ const std::vector MissionComponent::LookForAchievements(eMissionTaskTy return acceptedAchievements; #else - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto tasks = missionTasksTable->Query([=](const CDMissionTasks& entry) { return entry.taskType == static_cast(type); @@ -407,8 +407,8 @@ const std::vector& MissionComponent::QueryAchievements(eMissionTaskTyp } // Find relevent tables - auto* missionTasksTable = CDClientManager::Instance().GetTable(); - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionTasksTable = CDClientManager::GetTable(); + auto* missionsTable = CDClientManager::GetTable(); std::vector result; diff --git a/dGame/dComponents/MissionOfferComponent.cpp b/dGame/dComponents/MissionOfferComponent.cpp index 25d4a7392..7f26ed721 100644 --- a/dGame/dComponents/MissionOfferComponent.cpp +++ b/dGame/dComponents/MissionOfferComponent.cpp @@ -40,7 +40,7 @@ bool OfferedMission::GetAcceptsMission() const { //------------------------ MissionOfferComponent below ------------------------ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot) : Component(parent) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); auto value = compRegistryTable->GetByIDAndType(parentLot, eReplicaComponentType::MISSION_OFFER, -1); @@ -48,7 +48,7 @@ MissionOfferComponent::MissionOfferComponent(Entity* parent, const LOT parentLot const uint32_t componentId = value; // Now lookup the missions in the MissionNPCComponent table - auto* missionNpcComponentTable = CDClientManager::Instance().GetTable(); + auto* missionNpcComponentTable = CDClientManager::GetTable(); auto missions = missionNpcComponentTable->Query([=](const CDMissionNPCComponent& entry) { return entry.id == static_cast(componentId); diff --git a/dGame/dComponents/MovementAIComponent.cpp b/dGame/dComponents/MovementAIComponent.cpp index 1332fd075..8377031af 100644 --- a/dGame/dComponents/MovementAIComponent.cpp +++ b/dGame/dComponents/MovementAIComponent.cpp @@ -244,8 +244,8 @@ float MovementAIComponent::GetBaseSpeed(LOT lot) { return it->second; } - CDComponentsRegistryTable* componentRegistryTable = CDClientManager::Instance().GetTable(); - CDPhysicsComponentTable* physicsComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentRegistryTable = CDClientManager::GetTable(); + CDPhysicsComponentTable* physicsComponentTable = CDClientManager::GetTable(); int32_t componentID; CDPhysicsComponent* physicsComponent = nullptr; diff --git a/dGame/dComponents/PetComponent.cpp b/dGame/dComponents/PetComponent.cpp index 0c377ac75..1af65b4e5 100644 --- a/dGame/dComponents/PetComponent.cpp +++ b/dGame/dComponents/PetComponent.cpp @@ -71,7 +71,7 @@ std::map PetComponent::petFlags = { }; PetComponent::PetComponent(Entity* parentEntity, uint32_t componentId) : Component{ parentEntity } { - m_PetInfo = CDClientManager::Instance().GetTable()->GetByID(componentId); // TODO: Make reference when safe + m_PetInfo = CDClientManager::GetTable()->GetByID(componentId); // TODO: Make reference when safe m_ComponentId = componentId; m_Interaction = LWOOBJID_EMPTY; diff --git a/dGame/dComponents/PhantomPhysicsComponent.cpp b/dGame/dComponents/PhantomPhysicsComponent.cpp index 217a02fb2..b30214152 100644 --- a/dGame/dComponents/PhantomPhysicsComponent.cpp +++ b/dGame/dComponents/PhantomPhysicsComponent.cpp @@ -143,10 +143,10 @@ PhantomPhysicsComponent::PhantomPhysicsComponent(Entity* parent) : PhysicsCompon */ if (!m_HasCreatedPhysics) { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; @@ -260,10 +260,10 @@ void PhantomPhysicsComponent::CreatePhysics() { y = m_Parent->GetVar(u"primitiveModelValueY"); z = m_Parent->GetVar(u"primitiveModelValueZ"); } else { - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); auto componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::PHANTOM_PHYSICS); - CDPhysicsComponentTable* physComp = CDClientManager::Instance().GetTable(); + CDPhysicsComponentTable* physComp = CDClientManager::GetTable(); if (physComp == nullptr) return; diff --git a/dGame/dComponents/PropertyEntranceComponent.cpp b/dGame/dComponents/PropertyEntranceComponent.cpp index 2bb6ea309..ab3bb5daf 100644 --- a/dGame/dComponents/PropertyEntranceComponent.cpp +++ b/dGame/dComponents/PropertyEntranceComponent.cpp @@ -18,7 +18,7 @@ PropertyEntranceComponent::PropertyEntranceComponent(Entity* parent, uint32_t componentID) : Component(parent) { this->propertyQueries = {}; - auto table = CDClientManager::Instance().GetTable(); + auto table = CDClientManager::GetTable(); const auto& entry = table->GetByID(componentID); this->m_MapID = entry.mapID; diff --git a/dGame/dComponents/PropertyManagementComponent.cpp b/dGame/dComponents/PropertyManagementComponent.cpp index 0f6eb5a8a..0dfc04af9 100644 --- a/dGame/dComponents/PropertyManagementComponent.cpp +++ b/dGame/dComponents/PropertyManagementComponent.cpp @@ -14,7 +14,6 @@ #include "Item.h" #include "Database.h" #include "ObjectIDManager.h" -#include "Player.h" #include "RocketLaunchpadControlComponent.h" #include "PropertyEntranceComponent.h" #include "InventoryComponent.h" @@ -177,8 +176,6 @@ bool PropertyManagementComponent::Claim(const LWOOBJID playerId) { auto* entity = Game::entityManager->GetEntity(playerId); - auto* user = entity->GetParentUser(); - auto character = entity->GetCharacter(); if (!character) return false; diff --git a/dGame/dComponents/QuickBuildComponent.cpp b/dGame/dComponents/QuickBuildComponent.cpp index 1e745d8af..2514f194a 100644 --- a/dGame/dComponents/QuickBuildComponent.cpp +++ b/dGame/dComponents/QuickBuildComponent.cpp @@ -33,10 +33,9 @@ QuickBuildComponent::QuickBuildComponent(Entity* entity) : Component(entity) { // Should a setting that has the build activator position exist, fetch that setting here and parse it for position. // It is assumed that the user who sets this setting uses the correct character delimiter (character 31 or in hex 0x1F) auto positionAsVector = GeneralUtils::SplitString(m_Parent->GetVarAsString(u"rebuild_activators"), 0x1F); - if (positionAsVector.size() == 3 && - GeneralUtils::TryParse(positionAsVector[0], m_ActivatorPosition.x) && - GeneralUtils::TryParse(positionAsVector[1], m_ActivatorPosition.y) && - GeneralUtils::TryParse(positionAsVector[2], m_ActivatorPosition.z)) { + const auto activatorPositionValid = GeneralUtils::TryParse(positionAsVector); + if (positionAsVector.size() == 3 && activatorPositionValid) { + m_ActivatorPosition = activatorPositionValid.value(); } else { LOG("Failed to find activator position for lot %i. Defaulting to parents position.", m_Parent->GetLOT()); m_ActivatorPosition = m_Parent->GetPosition(); @@ -328,7 +327,7 @@ float QuickBuildComponent::GetTimeBeforeSmash() { return m_TimeBeforeSmash; } -eQuickBuildState QuickBuildComponent::GetState() { +eQuickBuildState QuickBuildComponent::GetState() const noexcept { return m_State; } diff --git a/dGame/dComponents/QuickBuildComponent.h b/dGame/dComponents/QuickBuildComponent.h index d989bc510..d9cc41900 100644 --- a/dGame/dComponents/QuickBuildComponent.h +++ b/dGame/dComponents/QuickBuildComponent.h @@ -173,7 +173,7 @@ class QuickBuildComponent final : public Component { * Returns the current quickbuild state * @return the current quickbuild state */ - eQuickBuildState GetState(); + [[nodiscard]] eQuickBuildState GetState() const noexcept; /** * Returns the player that is currently building this quickbuild diff --git a/dGame/dComponents/RacingControlComponent.cpp b/dGame/dComponents/RacingControlComponent.cpp index 742563cc6..f3772aad6 100644 --- a/dGame/dComponents/RacingControlComponent.cpp +++ b/dGame/dComponents/RacingControlComponent.cpp @@ -12,7 +12,6 @@ #include "Item.h" #include "MissionComponent.h" #include "ModuleAssemblyComponent.h" -#include "Player.h" #include "PossessableComponent.h" #include "PossessorComponent.h" #include "eRacingTaskParam.h" @@ -54,7 +53,7 @@ RacingControlComponent::RacingControlComponent(Entity* parent) if (Game::zoneManager->CheckIfAccessibleZone((worldID / 10) * 10)) m_MainWorld = (worldID / 10) * 10; m_ActivityID = 42; - CDActivitiesTable* activitiesTable = CDClientManager::Instance().GetTable(); + CDActivitiesTable* activitiesTable = CDClientManager::GetTable(); std::vector activities = activitiesTable->Query([=](CDActivities entry) {return (entry.instanceMapID == worldID); }); for (CDActivities activity : activities) m_ActivityID = activity.ActivityID; } diff --git a/dGame/dComponents/RailActivatorComponent.cpp b/dGame/dComponents/RailActivatorComponent.cpp index e0eb035a6..f269da495 100644 --- a/dGame/dComponents/RailActivatorComponent.cpp +++ b/dGame/dComponents/RailActivatorComponent.cpp @@ -13,7 +13,7 @@ RailActivatorComponent::RailActivatorComponent(Entity* parent, int32_t componentID) : Component(parent) { m_ComponentID = componentID; - const auto tableData = CDClientManager::Instance().GetTable()->GetEntryByID(componentID);; + const auto tableData = CDClientManager::GetTable()->GetEntryByID(componentID);; m_Path = parent->GetVar(u"rail_path"); m_PathDirection = parent->GetVar(u"rail_path_direction"); diff --git a/dGame/dComponents/RenderComponent.cpp b/dGame/dComponents/RenderComponent.cpp index 449fbc4d6..118e48478 100644 --- a/dGame/dComponents/RenderComponent.cpp +++ b/dGame/dComponents/RenderComponent.cpp @@ -27,16 +27,18 @@ RenderComponent::RenderComponent(Entity* const parentEntity, const int32_t compo if (!result.eof()) { auto animationGroupIDs = std::string(result.getStringField("animationGroupIDs", "")); if (!animationGroupIDs.empty()) { - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); auto groupIdsSplit = GeneralUtils::SplitString(animationGroupIDs, ','); for (auto& groupId : groupIdsSplit) { - int32_t groupIdInt; - if (!GeneralUtils::TryParse(groupId, groupIdInt)) { + const auto groupIdInt = GeneralUtils::TryParse(groupId); + + if (!groupIdInt) { LOG("bad animation group Id %s", groupId.c_str()); continue; } - m_animationGroupIds.push_back(groupIdInt); - animationsTable->CacheAnimationGroup(groupIdInt); + + m_animationGroupIds.push_back(groupIdInt.value()); + animationsTable->CacheAnimationGroup(groupIdInt.value()); } } } @@ -165,13 +167,12 @@ float RenderComponent::DoAnimation(Entity* self, const std::string& animation, b auto* renderComponent = self->GetComponent(); if (!renderComponent) return returnlength; - auto* animationsTable = CDClientManager::Instance().GetTable(); + auto* animationsTable = CDClientManager::GetTable(); for (auto& groupId : renderComponent->m_animationGroupIds) { auto animationGroup = animationsTable->GetAnimation(animation, renderComponent->GetLastAnimationName(), groupId); - if (animationGroup.FoundData()) { - auto data = animationGroup.Data(); - renderComponent->SetLastAnimationName(data.animation_name); - returnlength = data.animation_length; + if (animationGroup) { + renderComponent->SetLastAnimationName(animationGroup->animation_name); + returnlength = animationGroup->animation_length; } } if (sendAnimation) GameMessages::SendPlayAnimation(self, GeneralUtils::ASCIIToUTF16(animation), priority, scale); diff --git a/dGame/dComponents/SkillComponent.cpp b/dGame/dComponents/SkillComponent.cpp index b65c7d216..c43813c1d 100644 --- a/dGame/dComponents/SkillComponent.cpp +++ b/dGame/dComponents/SkillComponent.cpp @@ -234,7 +234,7 @@ bool SkillComponent::CastSkill(const uint32_t skillId, LWOOBJID target, const LW // if it's not in the cache look it up and cache it if (pair == m_skillBehaviorCache.end()) { - auto skillTable = CDClientManager::Instance().GetTable(); + auto skillTable = CDClientManager::GetTable(); behaviorId = skillTable->GetSkillByID(skillId).behaviorID; m_skillBehaviorCache.insert_or_assign(skillId, behaviorId); } else { diff --git a/dGame/dComponents/TriggerComponent.cpp b/dGame/dComponents/TriggerComponent.cpp index 6b83ae737..5d4415f87 100644 --- a/dGame/dComponents/TriggerComponent.cpp +++ b/dGame/dComponents/TriggerComponent.cpp @@ -9,7 +9,6 @@ #include "ControllablePhysicsComponent.h" #include "MissionComponent.h" #include "PhantomPhysicsComponent.h" -#include "Player.h" #include "QuickBuildComponent.h" #include "SkillComponent.h" #include "eEndBehavior.h" @@ -22,10 +21,8 @@ TriggerComponent::TriggerComponent(Entity* parent, const std::string triggerInfo std::vector tokens = GeneralUtils::SplitString(triggerInfo, ':'); - uint32_t sceneID; - GeneralUtils::TryParse(tokens.at(0), sceneID); - uint32_t triggerID; - GeneralUtils::TryParse(tokens.at(1), triggerID); + const auto sceneID = GeneralUtils::TryParse(tokens.at(0)).value_or(0); + const auto triggerID = GeneralUtils::TryParse(tokens.at(1)).value_or(0); m_Trigger = Game::zoneManager->GetZone()->GetTrigger(sceneID, triggerID); @@ -191,9 +188,8 @@ void TriggerComponent::HandleFireEvent(Entity* targetEntity, std::string args) { } void TriggerComponent::HandleDestroyObject(Entity* targetEntity, std::string args){ - uint32_t killType; - GeneralUtils::TryParse(args, killType); - targetEntity->Smash(m_Parent->GetObjectID(), static_cast(killType)); + const eKillType killType = GeneralUtils::TryParse(args).value_or(eKillType::VIOLENT); + targetEntity->Smash(m_Parent->GetObjectID(), killType); } void TriggerComponent::HandleToggleTrigger(Entity* targetEntity, std::string args){ @@ -217,9 +213,8 @@ void TriggerComponent::HandleResetRebuild(Entity* targetEntity, std::string args void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - auto position = targetEntity->GetPosition(); - NiPoint3 offset = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), offset); + NiPoint3 position = targetEntity->GetPosition(); + const NiPoint3 offset = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); position += offset; targetEntity->SetPosition(position); @@ -228,8 +223,7 @@ void TriggerComponent::HandleMoveObject(Entity* targetEntity, std::vector argArray){ if (argArray.size() <= 2) return; - NiPoint3 vector = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), vector); + const NiPoint3 vector = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); NiQuaternion rotation = NiQuaternion::FromEulerAngles(vector); targetEntity->SetRotation(rotation); @@ -246,8 +240,7 @@ void TriggerComponent::HandlePushObject(Entity* targetEntity, std::vectorSetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::PUSH); phantomPhysicsComponent->SetDirectionalMultiplier(1); - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(0), argArray.at(1), argArray.at(2), direction); + const NiPoint3 direction = GeneralUtils::TryParse(argArray).value_or(NiPoint3Constant::ZERO); phantomPhysicsComponent->SetDirection(direction); Game::entityManager->SerializeEntity(m_Parent); @@ -260,8 +253,8 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) LOG_DEBUG("Phantom Physics component not found!"); return; } - float forceMultiplier; - GeneralUtils::TryParse(args, forceMultiplier); + const float forceMultiplier = GeneralUtils::TryParse(args).value_or(1.0f); + phantomPhysicsComponent->SetPhysicsEffectActive(true); phantomPhysicsComponent->SetEffectType(ePhysicsEffectType::REPULSE); phantomPhysicsComponent->SetDirectionalMultiplier(forceMultiplier); @@ -280,11 +273,10 @@ void TriggerComponent::HandleRepelObject(Entity* targetEntity, std::string args) void TriggerComponent::HandleSetTimer(Entity* targetEntity, std::vector argArray){ if (argArray.size() != 2) { - LOG_DEBUG("Not ehought variables!"); + LOG_DEBUG("Not enough variables!"); return; } - float time = 0.0; - GeneralUtils::TryParse(argArray.at(1), time); + const float time = GeneralUtils::TryParse(argArray.at(1)).value_or(0.0f); m_Parent->AddTimer(argArray.at(0), time); } @@ -300,7 +292,7 @@ void TriggerComponent::HandlePlayCinematic(Entity* targetEntity, std::vector= 2) { - GeneralUtils::TryParse(argArray.at(1), leadIn); + leadIn = GeneralUtils::TryParse(argArray.at(1)).value_or(leadIn); if (argArray.size() >= 3 && argArray.at(2) == "wait") { wait = eEndBehavior::WAIT; if (argArray.size() >= 4 && argArray.at(3) == "unlock") { @@ -345,12 +337,16 @@ void TriggerComponent::HandleUpdateMission(Entity* targetEntity, std::vector argArray) { if (argArray.size() < 3) return; - int32_t effectID = 0; - if (!GeneralUtils::TryParse(argArray.at(1), effectID)) return; + const auto effectID = GeneralUtils::TryParse(argArray.at(1)); + if (!effectID) return; std::u16string effectType = GeneralUtils::UTF8ToUTF16(argArray.at(2)); + float priority = 1; - if (argArray.size() == 4) GeneralUtils::TryParse(argArray.at(3), priority); - GameMessages::SendPlayFXEffect(targetEntity, effectID, effectType, argArray.at(0), LWOOBJID_EMPTY, priority); + if (argArray.size() == 4) { + priority = GeneralUtils::TryParse(argArray.at(3)).value_or(priority); + } + + GameMessages::SendPlayFXEffect(targetEntity, effectID.value(), effectType, argArray.at(0), LWOOBJID_EMPTY, priority); } void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ @@ -359,8 +355,7 @@ void TriggerComponent::HandleCastSkill(Entity* targetEntity, std::string args){ LOG_DEBUG("Skill component not found!"); return; } - uint32_t skillId; - GeneralUtils::TryParse(args, skillId); + const uint32_t skillId = GeneralUtils::TryParse(args).value_or(0); skillComponent->CastSkill(skillId, targetEntity->GetObjectID()); } @@ -382,17 +377,16 @@ void TriggerComponent::HandleSetPhysicsVolumeEffect(Entity* targetEntity, std::v phantomPhysicsComponent->SetEffectType(effectType); phantomPhysicsComponent->SetDirectionalMultiplier(std::stof(argArray.at(1))); if (argArray.size() > 4) { - NiPoint3 direction = NiPoint3Constant::ZERO; - GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4), direction); + const NiPoint3 direction = + GeneralUtils::TryParse(argArray.at(2), argArray.at(3), argArray.at(4)).value_or(NiPoint3Constant::ZERO); + phantomPhysicsComponent->SetDirection(direction); } if (argArray.size() > 5) { - uint32_t min; - GeneralUtils::TryParse(argArray.at(6), min); + const uint32_t min = GeneralUtils::TryParse(argArray.at(6)).value_or(0); phantomPhysicsComponent->SetMin(min); - uint32_t max; - GeneralUtils::TryParse(argArray.at(7), max); + const uint32_t max = GeneralUtils::TryParse(argArray.at(7)).value_or(0); phantomPhysicsComponent->SetMax(max); } diff --git a/dGame/dComponents/VendorComponent.cpp b/dGame/dComponents/VendorComponent.cpp index dfea33df7..afa3d0132 100644 --- a/dGame/dComponents/VendorComponent.cpp +++ b/dGame/dComponents/VendorComponent.cpp @@ -41,14 +41,14 @@ void VendorComponent::RefreshInventory(bool isCreation) { return; } - auto* lootMatrixTable = CDClientManager::Instance().GetTable(); + auto* lootMatrixTable = CDClientManager::GetTable(); const auto& lootMatrices = lootMatrixTable->GetMatrix(m_LootMatrixID); if (lootMatrices.empty()) return; - auto* lootTableTable = CDClientManager::Instance().GetTable(); - auto* itemComponentTable = CDClientManager::Instance().GetTable(); - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* lootTableTable = CDClientManager::GetTable(); + auto* itemComponentTable = CDClientManager::GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); for (const auto& lootMatrix : lootMatrices) { auto vendorItems = lootTableTable->GetTable(lootMatrix.LootTableIndex); @@ -101,10 +101,10 @@ void VendorComponent::RefreshInventory(bool isCreation) { } void VendorComponent::SetupConstants() { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); int componentID = compRegistryTable->GetByIDAndType(m_Parent->GetLOT(), eReplicaComponentType::VENDOR); - auto* vendorComponentTable = CDClientManager::Instance().GetTable(); + auto* vendorComponentTable = CDClientManager::GetTable(); std::vector vendorComps = vendorComponentTable->Query([=](CDVendorComponent entry) { return (entry.id == componentID); }); if (vendorComps.empty()) return; auto vendorData = vendorComps.at(0); diff --git a/dGame/dGameMessages/GameMessageHandler.cpp b/dGame/dGameMessages/GameMessageHandler.cpp index fa11c0867..64790e316 100644 --- a/dGame/dGameMessages/GameMessageHandler.cpp +++ b/dGame/dGameMessages/GameMessageHandler.cpp @@ -18,7 +18,6 @@ #include "Character.h" #include "ControllablePhysicsComponent.h" #include "dZoneManager.h" -#include "Player.h" #include "CppScripts.h" #include "CDClientDatabase.h" @@ -291,7 +290,7 @@ void GameMessageHandler::HandleMessage(RakNet::BitStream* inStream, const System comp->Progress(eMissionTaskType::USE_SKILL, startSkill.skillID); } - CDSkillBehaviorTable* skillTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillTable = CDClientManager::GetTable(); unsigned int behaviorId = skillTable->GetSkillByID(startSkill.skillID).behaviorID; bool success = false; diff --git a/dGame/dGameMessages/GameMessages.cpp b/dGame/dGameMessages/GameMessages.cpp index 1214c951f..8b4d1f05c 100644 --- a/dGame/dGameMessages/GameMessages.cpp +++ b/dGame/dGameMessages/GameMessages.cpp @@ -20,7 +20,6 @@ #include "WorldPackets.h" #include "Item.h" #include "ZCompression.h" -#include "Player.h" #include "dConfig.h" #include "TeamManager.h" #include "ChatPackets.h" @@ -1117,7 +1116,7 @@ void GameMessages::SendDropClientLoot(Entity* entity, const LWOOBJID& sourceID, // Currency and powerups should not sync if (team != nullptr && currency == 0) { - CDObjectsTable* objectsTable = CDClientManager::Instance().GetTable(); + CDObjectsTable* objectsTable = CDClientManager::GetTable(); const CDObjects& object = objectsTable->GetByID(item); @@ -2584,6 +2583,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //We need to get a new ID for our model first: ObjectIDManager::RequestPersistentID([=](uint32_t newID) { + if (!entity || !entity->GetCharacter() || !entity->GetCharacter()->GetParentUser()) return; LWOOBJID newIDL = newID; GeneralUtils::SetBit(newIDL, eObjectBits::CHARACTER); GeneralUtils::SetBit(newIDL, eObjectBits::PERSISTENT); @@ -2606,7 +2606,7 @@ void GameMessages::HandleBBBSaveRequest(RakNet::BitStream* inStream, Entity* ent //Insert into ugc: std::string str(sd0Data.get(), sd0Size); std::istringstream sd0DataStream(str); - Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); + Database::Get()->InsertNewUgcModel(sd0DataStream, blueprintIDSmall, entity->GetCharacter()->GetParentUser()->GetAccountID(), entity->GetCharacter()->GetID()); //Insert into the db as a BBB model: IPropertyContents::Model model; @@ -4686,8 +4686,8 @@ void GameMessages::HandleBuyFromVendor(RakNet::BitStream* inStream, Entity* enti return; } - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item, eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4778,8 +4778,8 @@ void GameMessages::HandleSellToVendor(RakNet::BitStream* inStream, Entity* entit Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -4828,8 +4828,8 @@ void GameMessages::HandleBuybackFromVendor(RakNet::BitStream* inStream, Entity* Item* item = inv->FindItemById(iObjID); if (!item) return; - CDComponentsRegistryTable* compRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* compRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); int itemCompID = compRegistryTable->GetByIDAndType(item->GetLot(), eReplicaComponentType::ITEM); CDItemComponent itemComp = itemComponentTable->GetItemComponentByID(itemCompID); @@ -5041,7 +5041,7 @@ void GameMessages::HandlePlayEmote(RakNet::BitStream* inStream, Entity* entity) if (emoteID == 0) return; std::string sAnimationName = "deaded"; //Default name in case we fail to get the emote - CDEmoteTableTable* emotes = CDClientManager::Instance().GetTable(); + CDEmoteTableTable* emotes = CDClientManager::GetTable(); if (emotes) { CDEmoteTable* emote = emotes->GetEmote(emoteID); if (emote) sAnimationName = emote->animationName; @@ -5110,13 +5110,8 @@ void GameMessages::HandleSetFlag(RakNet::BitStream* inStream, Entity* entity) { inStream->Read(bFlag); inStream->Read(iFlagID); - auto user = entity->GetParentUser(); - if (user) { - auto character = user->GetLastUsedChar(); - if (!character) return; - - character->SetPlayerFlag(iFlagID, bFlag); - } + auto character = entity->GetCharacter(); + if (character) character->SetPlayerFlag(iFlagID, bFlag); } void GameMessages::HandleRespondToMission(RakNet::BitStream* inStream, Entity* entity) { diff --git a/dGame/dGameMessages/PropertyDataMessage.cpp b/dGame/dGameMessages/PropertyDataMessage.cpp index 29bc8ea93..ab7fe9c3f 100644 --- a/dGame/dGameMessages/PropertyDataMessage.cpp +++ b/dGame/dGameMessages/PropertyDataMessage.cpp @@ -103,7 +103,7 @@ void GameMessages::PropertyDataMessage::Serialize(RakNet::BitStream& stream) con } GameMessages::PropertyDataMessage::PropertyDataMessage(uint32_t mapID) { - const auto propertyTemplate = CDClientManager::Instance().GetTable()->GetByMapID(mapID); + const auto propertyTemplate = CDClientManager::GetTable()->GetByMapID(mapID); TemplateID = propertyTemplate.id; ZoneId = propertyTemplate.mapID; diff --git a/dGame/dInventory/Inventory.cpp b/dGame/dInventory/Inventory.cpp index 4475f77b1..35222beac 100644 --- a/dGame/dInventory/Inventory.cpp +++ b/dGame/dInventory/Inventory.cpp @@ -275,9 +275,9 @@ eInventoryType Inventory::FindInventoryTypeForLot(const LOT lot) { } const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); - auto* itemComponents = CDClientManager::Instance().GetTable(); + auto* itemComponents = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); @@ -293,7 +293,7 @@ const CDItemComponent& Inventory::FindItemComponent(const LOT lot) { } bool Inventory::IsValidItem(const LOT lot) { - auto* registry = CDClientManager::Instance().GetTable(); + auto* registry = CDClientManager::GetTable(); const auto componentId = registry->GetByIDAndType(lot, eReplicaComponentType::ITEM); diff --git a/dGame/dInventory/Item.cpp b/dGame/dInventory/Item.cpp index 4a13cd92c..d3f15315a 100644 --- a/dGame/dInventory/Item.cpp +++ b/dGame/dInventory/Item.cpp @@ -247,7 +247,7 @@ bool Item::IsEquipped() const { } bool Item::Consume() { - auto* skillsTable = CDClientManager::Instance().GetTable(); + auto* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([this](const CDObjectSkills entry) { return entry.objectTemplate == static_cast(lot); @@ -313,12 +313,12 @@ void Item::UseNonEquip(Item* item) { bool success = false; auto inventory = item->GetInventory(); if (inventory && inventory->GetType() == eInventoryType::ITEMS) { - auto* compRegistryTable = CDClientManager::Instance().GetTable(); + auto* compRegistryTable = CDClientManager::GetTable(); const auto packageComponentId = compRegistryTable->GetByIDAndType(lot, eReplicaComponentType::PACKAGE); if (packageComponentId == 0) return; - auto* packCompTable = CDClientManager::Instance().GetTable(); + auto* packCompTable = CDClientManager::GetTable(); auto packages = packCompTable->Query([=](const CDPackageComponent entry) {return entry.id == static_cast(packageComponentId); }); auto success = !packages.empty(); @@ -396,7 +396,7 @@ void Item::Disassemble(const eInventoryType inventoryType) { } void Item::DisassembleModel(uint32_t numToDismantle) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto componentId = table->GetByIDAndType(GetLot(), eReplicaComponentType::RENDER); @@ -468,20 +468,20 @@ void Item::DisassembleModel(uint32_t numToDismantle) { // First iteration gets the count std::map parts; while (currentBrick) { - auto* designID = currentBrick->Attribute("designID"); + const char* const designID = currentBrick->Attribute("designID"); if (designID) { - uint32_t designId; - if (!GeneralUtils::TryParse(designID, designId)) { + const auto designId = GeneralUtils::TryParse(designID); + if (!designId) { LOG("Failed to parse designID %s", designID); continue; } - parts[designId]++; + parts[designId.value()]++; } currentBrick = currentBrick->NextSiblingElement(searchTerm.c_str()); } - auto* brickIDTable = CDClientManager::Instance().GetTable(); + auto* brickIDTable = CDClientManager::GetTable(); // Second iteration actually distributes the bricks for (const auto& [part, count] : parts) { diff --git a/dGame/dInventory/ItemSet.cpp b/dGame/dInventory/ItemSet.cpp index 3364b63b5..1d0867866 100644 --- a/dGame/dInventory/ItemSet.cpp +++ b/dGame/dInventory/ItemSet.cpp @@ -87,10 +87,8 @@ ItemSet::ItemSet(const uint32_t id, InventoryComponent* inventoryComponent) { m_Items = {}; while (std::getline(stream, token, ',')) { - int32_t value; - if (GeneralUtils::TryParse(token, value)) { - m_Items.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) m_Items.push_back(validToken.value()); } m_Equipped = {}; @@ -129,7 +127,7 @@ void ItemSet::OnEquip(const LOT lot) { auto* missionComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; @@ -161,7 +159,7 @@ void ItemSet::OnUnEquip(const LOT lot) { const auto& skillComponent = m_InventoryComponent->GetParent()->GetComponent(); for (const auto skill : skillSet) { - auto* skillTable = CDClientManager::Instance().GetTable(); + auto* skillTable = CDClientManager::GetTable(); const auto behaviorId = skillTable->GetSkillByID(skill).behaviorID; diff --git a/dGame/dMission/Mission.cpp b/dGame/dMission/Mission.cpp index 6799b834f..4ed80bf3a 100644 --- a/dGame/dMission/Mission.cpp +++ b/dGame/dMission/Mission.cpp @@ -24,6 +24,7 @@ #include "eMissionTaskType.h" #include "eMissionLockState.h" #include "eReplicaComponentType.h" +#include "Character.h" #include "CDMissionEmailTable.h" @@ -40,7 +41,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { m_State = eMissionState::UNKNOWN; - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); auto* mis = missionsTable->GetPtrByMissionID(missionId); info = *mis; @@ -51,7 +52,7 @@ Mission::Mission(MissionComponent* missionComponent, const uint32_t missionId) { return; } - auto* tasksTable = CDClientManager::Instance().GetTable(); + auto* tasksTable = CDClientManager::GetTable(); auto tasks = tasksTable->GetByMissionID(missionId); @@ -179,7 +180,7 @@ void Mission::UpdateXml(tinyxml2::XMLElement* element) { } bool Mission::IsValidMission(const uint32_t missionId) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -189,7 +190,7 @@ bool Mission::IsValidMission(const uint32_t missionId) { } bool Mission::IsValidMission(const uint32_t missionId, CDMissions& info) { - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto missions = table->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); @@ -208,8 +209,8 @@ Entity* Mission::GetAssociate() const { return m_MissionComponent->GetParent(); } -User* Mission::GetUser() const { - return GetAssociate()->GetParentUser(); +Character* Mission::GetCharacter() const { + return GetAssociate()->GetCharacter(); } uint32_t Mission::GetMissionId() const { @@ -333,7 +334,7 @@ void Mission::Complete(const bool yieldRewards) { missionComponent->Progress(eMissionTaskType::RACING, info.id, static_cast(eRacingTaskParam::COMPLETE_TRACK_TASKS)); - auto* missionEmailTable = CDClientManager::Instance().GetTable(); + auto* missionEmailTable = CDClientManager::GetTable(); const auto missionId = GetMissionId(); @@ -390,7 +391,7 @@ void Mission::Catchup() { if (type == eMissionTaskType::PLAYER_FLAG) { for (int32_t target : task->GetAllTargets()) { - const auto flag = GetUser()->GetLastUsedChar()->GetPlayerFlag(target); + const auto flag = GetCharacter()->GetPlayerFlag(target); if (!flag) { continue; @@ -413,7 +414,7 @@ void Mission::YieldRewards() { return; } - auto* character = GetUser()->GetLastUsedChar(); + auto* character = GetCharacter(); auto* inventoryComponent = entity->GetComponent(); auto* levelComponent = entity->GetComponent(); @@ -599,8 +600,10 @@ void Mission::SetMissionState(const eMissionState state, const bool sendingRewar if (entity == nullptr) { return; } + auto* characterComponent = entity->GetComponent(); + if (!characterComponent) return; - GameMessages::SendNotifyMission(entity, entity->GetParentUser()->GetSystemAddress(), info.id, static_cast(state), sendingRewards); + GameMessages::SendNotifyMission(entity, characterComponent->GetSystemAddress(), info.id, static_cast(state), sendingRewards); } void Mission::SetMissionTypeState(eMissionLockState state, const std::string& type, const std::string& subType) { diff --git a/dGame/dMission/Mission.h b/dGame/dMission/Mission.h index f7c17003c..d8c104e84 100644 --- a/dGame/dMission/Mission.h +++ b/dGame/dMission/Mission.h @@ -17,6 +17,7 @@ namespace tinyxml2 { enum class eMissionState : int; enum class eMissionLockState : int; class MissionComponent; +class Character; /** * A mission (or achievement) that a player may unlock, progress and complete. @@ -46,7 +47,7 @@ class Mission final * Returns the account owns the entity that is currently progressing this mission * @return the account owns the entity that is currently progressing this mission */ - User* GetUser() const; + Character* GetCharacter() const; /** * Returns the current state of this mission diff --git a/dGame/dMission/MissionPrerequisites.cpp b/dGame/dMission/MissionPrerequisites.cpp index 89d547fd3..b5b811604 100644 --- a/dGame/dMission/MissionPrerequisites.cpp +++ b/dGame/dMission/MissionPrerequisites.cpp @@ -161,7 +161,7 @@ bool MissionPrerequisites::CheckPrerequisites(uint32_t missionId, const std::uno return index->second->Execute(missions); } - auto* missionsTable = CDClientManager::Instance().GetTable(); + auto* missionsTable = CDClientManager::GetTable(); const auto missionEntries = missionsTable->Query([=](const CDMissions& entry) { return entry.id == static_cast(missionId); }); diff --git a/dGame/dMission/MissionTask.cpp b/dGame/dMission/MissionTask.cpp index 604276eca..2fe9bc9fa 100644 --- a/dGame/dMission/MissionTask.cpp +++ b/dGame/dMission/MissionTask.cpp @@ -27,19 +27,15 @@ MissionTask::MissionTask(Mission* mission, CDMissionTasks* info, uint32_t mask) std::string token; while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - parameters.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) parameters.push_back(parameter.value()); } stream = std::istringstream(info->targetGroup); while (std::getline(stream, token, ',')) { - uint32_t parameter; - if (GeneralUtils::TryParse(token, parameter)) { - targets.push_back(parameter); - } + const auto parameter = GeneralUtils::TryParse(token); + if (parameter) targets.push_back(parameter.value()); } } diff --git a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp index cc817cd71..0aad74dd8 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviorMessages/BehaviorMessageBase.cpp @@ -5,7 +5,7 @@ #include "dCommonVars.h" BehaviorMessageBase::BehaviorMessageBase(AMFArrayValue* arguments) { - behaviorId = GetBehaviorIdFromArgument(arguments); + this->behaviorId = GetBehaviorIdFromArgument(arguments); } int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) { @@ -13,12 +13,13 @@ int32_t BehaviorMessageBase::GetBehaviorIdFromArgument(AMFArrayValue* arguments) auto* behaviorIDValue = arguments->Get(key); if (behaviorIDValue && behaviorIDValue->GetValueType() == eAmf::String) { - GeneralUtils::TryParse(behaviorIDValue->GetValue(), behaviorId); + this->behaviorId = + GeneralUtils::TryParse(behaviorIDValue->GetValue()).value_or(this->behaviorId); } else if (arguments->Get(key) && arguments->Get(key)->GetValueType() != eAmf::Undefined) { throw std::invalid_argument("Unable to find behavior ID"); } - return behaviorId; + return this->behaviorId; } int32_t BehaviorMessageBase::GetActionIndexFromArgument(AMFArrayValue* arguments, const std::string& keyName) { diff --git a/dGame/dPropertyBehaviors/ControlBehaviors.cpp b/dGame/dPropertyBehaviors/ControlBehaviors.cpp index c541257ce..5fee358de 100644 --- a/dGame/dPropertyBehaviors/ControlBehaviors.cpp +++ b/dGame/dPropertyBehaviors/ControlBehaviors.cpp @@ -13,6 +13,7 @@ #include "User.h" #include "tinyxml2.h" #include "CDClientDatabase.h" +#include "CharacterComponent.h" // Message includes #include "Action.h" @@ -145,10 +146,12 @@ void ControlBehaviors::ProcessCommand(Entity* modelEntity, const SystemAddress& } else if (command == "moveToInventory") { MoveToInventoryMessage msg(arguments); context.modelComponent->MoveToInventory(msg); + auto* characterComponent = modelOwner->GetComponent(); + if (!characterComponent) return; AMFArrayValue args; args.Insert("BehaviorID", std::to_string(msg.GetBehaviorId())); - GameMessages::SendUIMessageServerToSingleClient(modelOwner, modelOwner->GetParentUser()->GetSystemAddress(), "BehaviorRemoved", args); + GameMessages::SendUIMessageServerToSingleClient(modelOwner, characterComponent->GetSystemAddress(), "BehaviorRemoved", args); SendBehaviorListToClient(context); } else if (command == "updateAction") { diff --git a/dGame/dUtilities/CheatDetection.cpp b/dGame/dUtilities/CheatDetection.cpp index bc50b2ccd..a87157a18 100644 --- a/dGame/dUtilities/CheatDetection.cpp +++ b/dGame/dUtilities/CheatDetection.cpp @@ -2,7 +2,6 @@ #include "Database.h" #include "Entity.h" #include "PossessableComponent.h" -#include "Player.h" #include "Game.h" #include "EntityManager.h" #include "Character.h" @@ -59,13 +58,13 @@ void LogAndSaveFailedAntiCheatCheck(const LWOOBJID& id, const SystemAddress& sys player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), entity->GetCharacter()->GetName().c_str(), entity->GetObjectID()); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the case that the target entity id did not exist, just log the player info. } else if (player) { LOG("Player (%s) (%llu) at system address (%s) with sending player (%llu) does not match their own.", player->GetCharacter()->GetName().c_str(), player->GetObjectID(), sysAddr.ToString(), id); - toReport = player->GetParentUser(); + if (player->GetCharacter()) toReport = player->GetCharacter()->GetParentUser(); // In the rare case that the player does not exist, just log the system address and who the target id was. } else { LOG("Player at system address (%s) with sending player (%llu) does not match their own.", diff --git a/dGame/dUtilities/Loot.cpp b/dGame/dUtilities/Loot.cpp index 25c81e749..b2f96ac3f 100644 --- a/dGame/dUtilities/Loot.cpp +++ b/dGame/dUtilities/Loot.cpp @@ -28,11 +28,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { return; } CachedMatrices.insert(matrixIndex); - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -47,11 +47,11 @@ void Loot::CacheMatrix(uint32_t matrixIndex) { } std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); auto* missionComponent = player->GetComponent(); std::unordered_map drops; @@ -134,11 +134,11 @@ std::unordered_map Loot::RollLootMatrix(Entity* player, uint32_t m } std::unordered_map Loot::RollLootMatrix(uint32_t matrixIndex) { - CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::Instance().GetTable(); - CDItemComponentTable* itemComponentTable = CDClientManager::Instance().GetTable(); - CDLootMatrixTable* lootMatrixTable = CDClientManager::Instance().GetTable(); - CDLootTableTable* lootTableTable = CDClientManager::Instance().GetTable(); - CDRarityTableTable* rarityTableTable = CDClientManager::Instance().GetTable(); + CDComponentsRegistryTable* componentsRegistryTable = CDClientManager::GetTable(); + CDItemComponentTable* itemComponentTable = CDClientManager::GetTable(); + CDLootMatrixTable* lootMatrixTable = CDClientManager::GetTable(); + CDLootTableTable* lootTableTable = CDClientManager::GetTable(); + CDRarityTableTable* rarityTableTable = CDClientManager::GetTable(); std::unordered_map drops; const auto& matrix = lootMatrixTable->GetMatrix(matrixIndex); @@ -216,7 +216,7 @@ void Loot::GiveLoot(Entity* player, std::unordered_map& result, eL } void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, int32_t rating) { - CDActivityRewardsTable* activityRewardsTable = CDClientManager::Instance().GetTable(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -232,7 +232,7 @@ void Loot::GiveActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { @@ -286,7 +286,7 @@ void Loot::DropLoot(Entity* player, Entity* killedObject, std::unordered_map(); + CDActivityRewardsTable* activityRewardsTable = CDClientManager::GetTable(); std::vector activityRewards = activityRewardsTable->Query([activityID](CDActivityRewards entry) { return (entry.objectTemplate == activityID); }); const CDActivityRewards* selectedReward = nullptr; @@ -303,7 +303,7 @@ void Loot::DropActivityLoot(Entity* player, Entity* source, uint32_t activityID, uint32_t minCoins = 0; uint32_t maxCoins = 0; - CDCurrencyTableTable* currencyTableTable = CDClientManager::Instance().GetTable(); + CDCurrencyTableTable* currencyTableTable = CDClientManager::GetTable(); std::vector currencyTable = currencyTableTable->Query([selectedReward](CDCurrencyTable entry) { return (entry.currencyIndex == selectedReward->CurrencyIndex && entry.npcminlevel == 1); }); if (currencyTable.size() > 0) { diff --git a/dGame/dUtilities/Preconditions.cpp b/dGame/dUtilities/Preconditions.cpp index 12059b5bf..bd855962c 100644 --- a/dGame/dUtilities/Preconditions.cpp +++ b/dGame/dUtilities/Preconditions.cpp @@ -40,10 +40,8 @@ Precondition::Precondition(const uint32_t condition) { std::string token; while (std::getline(stream, token, ',')) { - uint32_t value; - if (GeneralUtils::TryParse(token, value)) { - this->values.push_back(value); - } + const auto validToken = GeneralUtils::TryParse(token); + if (validToken) this->values.push_back(validToken.value()); } } diff --git a/dGame/dUtilities/SlashCommandHandler.cpp b/dGame/dUtilities/SlashCommandHandler.cpp index 35c5f7a9d..169426abe 100644 --- a/dGame/dUtilities/SlashCommandHandler.cpp +++ b/dGame/dUtilities/SlashCommandHandler.cpp @@ -53,7 +53,6 @@ #include "Loot.h" #include "EntityInfo.h" #include "LUTriggers.h" -#include "Player.h" #include "PhantomPhysicsComponent.h" #include "ProximityMonitorComponent.h" #include "dpShapeSphere.h" @@ -114,13 +113,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if ((chatCommand == "setgmlevel" || chatCommand == "makegm" || chatCommand == "gmlevel") && user->GetMaxGMLevel() > eGameMasterLevel::CIVILIAN) { if (args.size() != 1) return; - uint32_t level_intermed = 0; + const auto level_intermed = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], level_intermed)) { + if (!level_intermed) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid gm level."); return; } - eGameMasterLevel level = static_cast(level_intermed); + eGameMasterLevel level = static_cast(level_intermed.value()); #ifndef DEVELOPER_SERVER if (user->GetMaxGMLevel() == eGameMasterLevel::JUNIOR_DEVELOPER) { @@ -379,26 +378,27 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "resetmission" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t missionId; - if (!GeneralUtils::TryParse(args[0], missionId)) { + const auto missionId = GeneralUtils::TryParse(args[0]); + if (!missionId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission ID."); return; } auto* missionComponent = entity->GetComponent(); if (!missionComponent) return; - missionComponent->ResetMission(missionId); + missionComponent->ResetMission(missionId.value()); } // Log command to database Database::Get()->InsertSlashCommandUsage(entity->GetObjectID(), chatCommand); if (chatCommand == "setminifig" && args.size() == 2 && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { // could break characters so only allow if GM > 0 - int32_t minifigItemId; - if (!GeneralUtils::TryParse(args[1], minifigItemId)) { + const auto minifigItemIdExists = GeneralUtils::TryParse(args[1]); + if (!minifigItemIdExists) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid Minifig Item Id ID."); return; } + const int32_t minifigItemId = minifigItemIdExists.value(); Game::entityManager->DestructEntity(entity, sysAddr); auto* charComp = entity->GetComponent(); std::string lowerName = args[0]; @@ -458,14 +458,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "unlock-emote" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t emoteID; + const auto emoteID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], emoteID)) { + if (!emoteID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid emote ID."); return; } - entity->GetCharacter()->UnlockEmote(emoteID); + entity->GetCharacter()->UnlockEmote(emoteID.value()); } if (chatCommand == "force-save" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -487,19 +487,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "speedboost" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - float boost; - - if (!GeneralUtils::TryParse(args[0], boost)) { + const auto boostOptional = GeneralUtils::TryParse(args[0]); + if (!boostOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost."); return; } + const float boost = boostOptional.value(); auto* controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; controllablePhysicsComponent->SetSpeedMultiplier(boost); - // speedboost possesables + // speedboost possessables auto possessor = entity->GetComponent(); if (possessor) { auto possessedID = possessor->GetPossessable(); @@ -528,14 +528,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setcontrolscheme" && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - uint32_t scheme; + const auto scheme = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], scheme)) { + if (!scheme) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid control scheme."); return; } - GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme)); + GameMessages::SendSetPlayerControlScheme(entity, static_cast(scheme.value())); ChatPackets::SendSystemMessage(sysAddr, u"Switched control scheme."); return; @@ -575,29 +575,28 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "setinventorysize" || chatCommand == "setinvsize") && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { - uint32_t size; - - if (!GeneralUtils::TryParse(args.at(0), size)) { + const auto sizeOptional = GeneralUtils::TryParse(args[0]); + if (!sizeOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid size."); return; } + const uint32_t size = sizeOptional.value(); eInventoryType selectedInventory = eInventoryType::ITEMS; // a possible inventory was provided if we got more than 1 argument if (args.size() >= 2) { - selectedInventory = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args.at(1), selectedInventory)) { + selectedInventory = GeneralUtils::TryParse(args.at(1)).value_or(eInventoryType::INVALID); + if (selectedInventory == eInventoryType::INVALID) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); + return; + } else { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args.at(1).begin(), args.at(1).end(), args.at(1).begin(), ::toupper); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args.at(1)) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) selectedInventory = static_cast(index); } } - if (selectedInventory == eInventoryType::INVALID) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid inventory."); - return; - } ChatPackets::SendSystemMessage(sysAddr, u"Setting inventory " + GeneralUtils::ASCIIToUTF16(args.at(1)) + @@ -644,48 +643,48 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addmission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->AcceptMission(missionID, true); + if (comp) comp->AcceptMission(missionID.value(), true); return; } if (chatCommand == "completemission" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 0) return; - uint32_t missionID; + const auto missionID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], missionID)) { + if (!missionID) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid mission id."); return; } auto comp = static_cast(entity->GetComponent(eReplicaComponentType::MISSION)); - if (comp) comp->CompleteMission(missionID, true); + if (comp) comp->CompleteMission(missionID.value(), true); return; } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, true); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), true); } if (chatCommand == "setflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 2) { - int32_t flagId; - std::string onOffFlag = args[0]; - if (!GeneralUtils::TryParse(args[1], flagId)) { + const auto flagId = GeneralUtils::TryParse(args.at(1)); + std::string onOffFlag = args.at(0); + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } @@ -693,28 +692,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag type."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, onOffFlag == "on"); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), onOffFlag == "on"); } if (chatCommand == "clearflag" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t flagId; + const auto flagId = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], flagId)) { + if (!flagId) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid flag id."); return; } - entity->GetCharacter()->SetPlayerFlag(flagId, false); + entity->GetCharacter()->SetPlayerFlag(flagId.value(), false); } if (chatCommand == "playeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - int32_t effectID = 0; + const auto effectID = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], effectID)) { - return; - } + if (!effectID) return; // FIXME: use fallible ASCIIToUTF16 conversion, because non-ascii isn't valid anyway - GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID, GeneralUtils::ASCIIToUTF16(args[1]), args[2]); + GameMessages::SendPlayFXEffect(entity->GetObjectID(), effectID.value(), GeneralUtils::ASCIIToUTF16(args.at(1)), args.at(2)); } if (chatCommand == "stopeffect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { @@ -776,34 +773,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmadditem" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { if (args.size() == 1) { - uint32_t itemLOT; + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, 1, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), 1, eLootSourceType::MODERATION); } else if (args.size() == 2) { - uint32_t itemLOT; - - if (!GeneralUtils::TryParse(args[0], itemLOT)) { + const auto itemLOT = GeneralUtils::TryParse(args.at(0)); + if (!itemLOT) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item LOT."); return; } - uint32_t count; - - if (!GeneralUtils::TryParse(args[1], count)) { + const auto count = GeneralUtils::TryParse(args.at(1)); + if (!count) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item count."); return; } InventoryComponent* inventory = static_cast(entity->GetComponent(eReplicaComponentType::INVENTORY)); - inventory->AddItem(itemLOT, count, eLootSourceType::MODERATION); + inventory->AddItem(itemLOT.value(), count.value(), eLootSourceType::MODERATION); } else { ChatPackets::SendSystemMessage(sysAddr, u"Correct usage: /gmadditem "); } @@ -823,9 +818,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit receiverID = playerInfo->id; - LOT lot; + const auto lot = GeneralUtils::TryParse(args.at(1)); - if (!GeneralUtils::TryParse(args[1], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid item lot."); return; } @@ -838,7 +833,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit mailInsert.subject = "Lost item"; mailInsert.body = "This is a replacement item for one you lost."; mailInsert.itemID = LWOOBJID_EMPTY; - mailInsert.itemLOT = lot; + mailInsert.itemLOT = lot.value(); mailInsert.itemSubkey = LWOOBJID_EMPTY; mailInsert.itemCount = 1; Database::Get()->InsertNewMail(mailInsert); @@ -872,46 +867,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit NiPoint3 pos{}; if (args.size() == 3) { - float x, y, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], y)) { + const auto y = GeneralUtils::TryParse(args.at(1)); + if (!y) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid y."); return; } - if (!GeneralUtils::TryParse(args[2], z)) { + const auto z = GeneralUtils::TryParse(args.at(2)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); - pos.SetY(y); - pos.SetZ(z); + pos.SetX(x.value()); + pos.SetY(y.value()); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to %f, %f, %f", entity->GetObjectID(), pos.x, pos.y, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); } else if (args.size() == 2) { - float x, z; - - if (!GeneralUtils::TryParse(args[0], x)) { + const auto x = GeneralUtils::TryParse(args.at(0)); + if (!x) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid x."); return; } - if (!GeneralUtils::TryParse(args[1], z)) { + const auto z = GeneralUtils::TryParse(args.at(1)); + if (!z) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid z."); return; } - pos.SetX(x); + pos.SetX(x.value()); pos.SetY(0.0f); - pos.SetZ(z); + pos.SetZ(z.value()); LOG("Teleporting objectID: %llu to X: %f, Z: %f", entity->GetObjectID(), pos.x, pos.z); GameMessages::SendTeleport(entity->GetObjectID(), pos, NiQuaternion(), sysAddr); @@ -971,10 +967,10 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit float speedScale = 1.0f; if (args.size() >= 1) { - float tempScaleStore; + const auto tempScaleStore = GeneralUtils::TryParse(args.at(0)); - if (GeneralUtils::TryParse(args[0], tempScaleStore)) { - speedScale = tempScaleStore; + if (tempScaleStore) { + speedScale = tempScaleStore.value(); } else { ChatPackets::SendSystemMessage(sysAddr, u"Failed to parse speed scale argument."); } @@ -1017,23 +1013,26 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); characterId = player->GetObjectID(); } time_t expire = 1; // Default to indefinate mute if (args.size() >= 2) { - uint32_t days = 0; - uint32_t hours = 0; - if (!GeneralUtils::TryParse(args[1], days)) { + const auto days = GeneralUtils::TryParse(args[1]); + if (!days) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid days."); return; } + std::optional hours; if (args.size() >= 3) { - if (!GeneralUtils::TryParse(args[2], hours)) { + hours = GeneralUtils::TryParse(args[2]); + if (!hours) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid hours."); return; @@ -1041,11 +1040,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } expire = time(NULL); - expire += 24 * 60 * 60 * days; - expire += 60 * 60 * hours; + expire += 24 * 60 * 60 * days.value(); + expire += 60 * 60 * hours.value_or(0); } - Database::Get()->UpdateAccountUnmuteTime(accountId, expire); + if (accountId != 0) Database::Get()->UpdateAccountUnmuteTime(accountId, expire); char buffer[32] = "brought up for review.\0"; @@ -1109,10 +1108,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit return; } } else { - accountId = player->GetParentUser()->GetAccountID(); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) accountId = user->GetAccountID(); } - Database::Get()->UpdateAccountBan(accountId, true); + if (accountId != 0) Database::Get()->UpdateAccountBan(accountId, true); if (player != nullptr) { Game::server->Disconnect(player->GetSystemAddress(), eServerDisconnectIdentifiers::FREE_TRIAL_EXPIRED); @@ -1140,14 +1141,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "startcelebration" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - int32_t celebration; + const auto celebration = GeneralUtils::TryParse(args.at(0)); - if (!GeneralUtils::TryParse(args[0], celebration)) { + if (!celebration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid celebration."); return; } - GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration); + GameMessages::SendStartCelebrationEffect(entity, entity->GetSystemAddress(), celebration.value()); } if (chatCommand == "buffmed" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { @@ -1201,15 +1202,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit ControllablePhysicsComponent* comp = static_cast(entity->GetComponent(eReplicaComponentType::CONTROLLABLE_PHYSICS)); if (!comp) return; - uint32_t lot; + const auto lot = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], lot)) { + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.pos = comp->GetPosition(); info.rot = comp->GetRotation(); info.spawner = nullptr; @@ -1230,28 +1231,29 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto controllablePhysicsComponent = entity->GetComponent(); if (!controllablePhysicsComponent) return; - LOT lot{}; - uint32_t numberToSpawn{}; - float radiusToSpawnWithin{}; - - if (!GeneralUtils::TryParse(args[0], lot)) { + const auto lot = GeneralUtils::TryParse(args[0]); + if (!lot) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid lot."); return; } - if (!GeneralUtils::TryParse(args[1], numberToSpawn) && numberToSpawn > 0) { + const auto numberToSpawnOptional = GeneralUtils::TryParse(args[1]); + if (!numberToSpawnOptional && numberToSpawnOptional.value() > 0) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid number of enemies to spawn."); return; } + uint32_t numberToSpawn = numberToSpawnOptional.value(); // Must spawn within a radius of at least 0.0f - if (!GeneralUtils::TryParse(args[2], radiusToSpawnWithin) && radiusToSpawnWithin < 0.0f) { + const auto radiusToSpawnWithinOptional = GeneralUtils::TryParse(args[2]); + if (!radiusToSpawnWithinOptional && radiusToSpawnWithinOptional.value() < 0.0f) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid radius to spawn within."); return; } + const float radiusToSpawnWithin = radiusToSpawnWithinOptional.value(); EntityInfo info; - info.lot = lot; + info.lot = lot.value(); info.spawner = nullptr; info.spawnerID = entity->GetObjectID(); info.spawnerNodeID = 0; @@ -1278,12 +1280,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "giveuscore") && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t uscore; - - if (!GeneralUtils::TryParse(args[0], uscore)) { + const auto uscoreOptional = GeneralUtils::TryParse(args[0]); + if (!uscoreOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid uscore."); return; } + const int32_t uscore = uscoreOptional.value(); CharacterComponent* character = entity->GetComponent(); if (character) character->SetUScore(character->GetUScore() + uscore); @@ -1291,9 +1293,9 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit eLootSourceType lootType = eLootSourceType::MODERATION; - int32_t type; - if (args.size() >= 2 && GeneralUtils::TryParse(args[1], type)) { - lootType = static_cast(type); + if (args.size() >= 2) { + const auto type = GeneralUtils::TryParse(args[1]); + lootType = type.value_or(lootType); } GameMessages::SendModifyLEGOScore(entity, entity->GetSystemAddress(), uscore, lootType); @@ -1319,14 +1321,15 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit entity = requestedPlayer->GetOwner(); } - uint32_t requestedLevel; + const auto requestedLevelOptional = GeneralUtils::TryParse(args[0]); uint32_t oldLevel; - // first check the level is valid - if (!GeneralUtils::TryParse(args[0], requestedLevel)) { + // first check the level is valid + if (!requestedLevelOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid level."); return; } + uint32_t requestedLevel = requestedLevelOptional.value(); // query to set our uscore to the correct value for this level auto characterComponent = entity->GetComponent(); @@ -1399,31 +1402,31 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if ((chatCommand == "freemoney" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) && args.size() == 1) { - int64_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(ch->GetCoins() + money, eLootSourceType::MODERATION); + ch->SetCoins(ch->GetCoins() + money.value(), eLootSourceType::MODERATION); } if ((chatCommand == "setcurrency") && args.size() == 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { - int32_t money; + const auto money = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], money)) { + if (!money) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid money."); return; } auto* ch = entity->GetCharacter(); - ch->SetCoins(money, eLootSourceType::MODERATION); + ch->SetCoins(money.value(), eLootSourceType::MODERATION); } // Allow for this on even while not a GM, as it sometimes toggles incorrrectly. - if (chatCommand == "gminvis" && entity->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { + if (chatCommand == "gminvis" && entity->GetCharacter()->GetParentUser()->GetMaxGMLevel() >= eGameMasterLevel::DEVELOPER) { GameMessages::SendToggleGMInvis(entity->GetObjectID(), true, UNASSIGNED_SYSTEM_ADDRESS); return; @@ -1432,17 +1435,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "gmimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsGMImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsGMImmune(state.value()); return; } @@ -1450,53 +1450,47 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "attackimmune" && args.size() >= 1 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* destroyableComponent = entity->GetComponent(); - int32_t state = false; + const auto state = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], state)) { + if (!state) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid state."); return; } - if (destroyableComponent != nullptr) { - destroyableComponent->SetIsImmune(state); - } - + if (destroyableComponent) destroyableComponent->SetIsImmune(state.value()); return; } if (chatCommand == "buff" && args.size() >= 2 && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER) { auto* buffComponent = entity->GetComponent(); - int32_t id = 0; - int32_t duration = 0; - - if (!GeneralUtils::TryParse(args[0], id)) { + const auto id = GeneralUtils::TryParse(args[0]); + if (!id) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff id."); return; } - if (!GeneralUtils::TryParse(args[1], duration)) { + const auto duration = GeneralUtils::TryParse(args[1]); + if (!duration) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid buff duration."); return; } - if (buffComponent != nullptr) { - buffComponent->ApplyBuff(id, duration, entity->GetObjectID()); - } - + if (buffComponent) buffComponent->ApplyBuff(id.value(), duration.value(), entity->GetObjectID()); return; } if ((chatCommand == "testmap" && args.size() >= 1) && entity->GetGMLevel() >= eGameMasterLevel::FORUM_MODERATOR) { ChatPackets::SendSystemMessage(sysAddr, u"Requesting map change..."); - uint32_t reqZone; LWOCLONEID cloneId = 0; bool force = false; - if (!GeneralUtils::TryParse(args[0], reqZone)) { + const auto reqZoneOptional = GeneralUtils::TryParse(args[0]); + if (!reqZoneOptional) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } + const LWOMAPID reqZone = reqZoneOptional.value(); if (args.size() > 1) { auto index = 1; @@ -1507,9 +1501,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit force = true; } - if (args.size() > index && !GeneralUtils::TryParse(args[index], cloneId)) { - ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); - return; + if (args.size() > index) { + const auto cloneIdOptional = GeneralUtils::TryParse(args[index]); + if (!cloneIdOptional) { + ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone id."); + return; + } + cloneId = cloneIdOptional.value(); } } @@ -1547,23 +1545,21 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "createprivate" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 3) { - uint32_t zone; - - if (!GeneralUtils::TryParse(args[0], zone)) { + const auto zone = GeneralUtils::TryParse(args[0]); + if (!zone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid zone."); return; } - uint32_t clone; - - if (!GeneralUtils::TryParse(args[1], clone)) { + const auto clone = GeneralUtils::TryParse(args[1]); + if (!clone) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid clone."); return; } const auto& password = args[2]; - ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone, clone, password); + ZoneInstanceManager::Instance()->CreatePrivateZone(Game::server, zone.value(), clone.value(), password); ChatPackets::SendSystemMessage(sysAddr, GeneralUtils::ASCIIToUTF16("Sent request for private zone with password: " + password)); @@ -1590,14 +1586,14 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 1) { - float time; + const auto time = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], time)) { + if (!time) { ChatPackets::SendSystemMessage(sysAddr, u"Invalid boost time."); return; } else { GameMessages::SendVehicleAddPassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); - entity->AddCallbackTimer(time, [vehicle]() { + entity->AddCallbackTimer(time.value(), [vehicle]() { if (!vehicle) return; GameMessages::SendVehicleRemovePassiveBoostAction(vehicle->GetObjectID(), UNASSIGNED_SYSTEM_ADDRESS); }); @@ -1673,20 +1669,19 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "reforge" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - LOT baseItem; - LOT reforgedItem; + const auto baseItem = GeneralUtils::TryParse(args[0]); + if (!baseItem) return; - if (!GeneralUtils::TryParse(args[0], baseItem)) return; - if (!GeneralUtils::TryParse(args[1], reforgedItem)) return; + const auto reforgedItem = GeneralUtils::TryParse(args[1]); + if (!reforgedItem) return; auto* inventoryComponent = entity->GetComponent(); - - if (inventoryComponent == nullptr) return; + if (!inventoryComponent) return; std::vector data{}; - data.push_back(new LDFData(u"reforgedLOT", reforgedItem)); + data.push_back(new LDFData(u"reforgedLOT", reforgedItem.value())); - inventoryComponent->AddItem(baseItem, 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); + inventoryComponent->AddItem(baseItem.value(), 1, eLootSourceType::MODERATION, eInventoryType::INVALID, data); } if (chatCommand == "crash" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR) { @@ -1740,8 +1735,8 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit VanityUtilities::SpawnVanity(); dpWorld::Reload(); auto entities = Game::entityManager->GetEntitiesByComponent(eReplicaComponentType::SCRIPTED_ACTIVITY); - for (auto entity : entities) { - auto* scriptedActivityComponent = entity->GetComponent(); + for (const auto* const entity : entities) { + auto* const scriptedActivityComponent = entity->GetComponent(); if (!scriptedActivityComponent) continue; scriptedActivityComponent->ReloadConfig(); @@ -1752,19 +1747,20 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "rollloot" && entity->GetGMLevel() >= eGameMasterLevel::OPERATOR && args.size() >= 3) { - uint32_t lootMatrixIndex = 0; - uint32_t targetLot = 0; - uint32_t loops = 1; + const auto lootMatrixIndex = GeneralUtils::TryParse(args[0]); + if (!lootMatrixIndex) return; - if (!GeneralUtils::TryParse(args[0], lootMatrixIndex)) return; - if (!GeneralUtils::TryParse(args[1], targetLot)) return; - if (!GeneralUtils::TryParse(args[2], loops)) return; + const auto targetLot = GeneralUtils::TryParse(args[1]); + if (!targetLot) return; + + const auto loops = GeneralUtils::TryParse(args[2]); + if (!loops) return; uint64_t totalRuns = 0; for (uint32_t i = 0; i < loops; i++) { while (true) { - auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex); + auto lootRoll = Loot::RollLootMatrix(lootMatrixIndex.value()); totalRuns += 1; bool doBreak = false; for (const auto& kv : lootRoll) { @@ -1777,26 +1773,30 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } std::u16string message = u"Ran loot drops looking for " - + GeneralUtils::to_u16string(targetLot) + + GeneralUtils::to_u16string(targetLot.value()) + u", " - + GeneralUtils::to_u16string(loops) + + GeneralUtils::to_u16string(loops.value()) + u" times. It ran " + GeneralUtils::to_u16string(totalRuns) + u" times. Averaging out at " - + GeneralUtils::to_u16string(static_cast(totalRuns) / loops); + + GeneralUtils::to_u16string(static_cast(totalRuns) / loops.value()); ChatPackets::SendSystemMessage(sysAddr, message); } if (chatCommand == "deleteinven" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { eInventoryType inventoryType = eInventoryType::INVALID; - if (!GeneralUtils::TryParse(args[0], inventoryType)) { + + const auto inventoryTypeOptional = GeneralUtils::TryParse(args[0]); + if (!inventoryTypeOptional) { // In this case, we treat the input as a string and try to find it in the reflection list std::transform(args[0].begin(), args[0].end(), args[0].begin(), ::toupper); LOG("looking for inventory %s", args[0].c_str()); for (uint32_t index = 0; index < NUMBER_OF_INVENTORIES; index++) { if (std::string_view(args[0]) == std::string_view(InventoryType::InventoryTypeToString(static_cast(index)))) inventoryType = static_cast(index); } + } else { + inventoryType = inventoryTypeOptional.value(); } if (inventoryType == eInventoryType::INVALID || inventoryType >= NUMBER_OF_INVENTORIES) { @@ -1818,32 +1818,32 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "castskill" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* skillComponent = entity->GetComponent(); if (skillComponent) { - uint32_t skillId; + const auto skillId = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], skillId)) { + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill ID."); return; } else { - skillComponent->CastSkill(skillId, entity->GetObjectID(), entity->GetObjectID()); + skillComponent->CastSkill(skillId.value(), entity->GetObjectID(), entity->GetObjectID()); ChatPackets::SendSystemMessage(sysAddr, u"Cast skill"); } } } if (chatCommand == "setskillslot" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 2) { - uint32_t skillId; - int slot; - auto* inventoryComponent = entity->GetComponent(); + auto* const inventoryComponent = entity->GetComponent(); if (inventoryComponent) { - if (!GeneralUtils::TryParse(args[0], slot)) { + const auto slot = GeneralUtils::TryParse(args[0]); + if (!slot) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting slot."); return; } else { - if (!GeneralUtils::TryParse(args[1], skillId)) { + const auto skillId = GeneralUtils::TryParse(args[1]); + if (!skillId) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting skill."); return; } else { - if (inventoryComponent->SetSkill(slot, skillId)) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); + if (inventoryComponent->SetSkill(slot.value(), skillId.value())) ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot successfully"); else ChatPackets::SendSystemMessage(sysAddr, u"Set skill to slot failed"); } } @@ -1853,13 +1853,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "setfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->SetFaction(faction); + destroyableComponent->SetFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Set faction and updated enemies list"); } } @@ -1868,13 +1868,13 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "addfaction" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { auto* destroyableComponent = entity->GetComponent(); if (destroyableComponent) { - int32_t faction; + const auto faction = GeneralUtils::TryParse(args[0]); - if (!GeneralUtils::TryParse(args[0], faction)) { + if (!faction) { ChatPackets::SendSystemMessage(sysAddr, u"Error getting faction."); return; } else { - destroyableComponent->AddFaction(faction); + destroyableComponent->AddFaction(faction.value()); ChatPackets::SendSystemMessage(sysAddr, u"Added faction and updated enemies list"); } } @@ -1896,7 +1896,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (chatCommand == "setrewardcode" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() == 1) { - auto* cdrewardCodes = CDClientManager::Instance().GetTable(); + auto* cdrewardCodes = CDClientManager::GetTable(); auto id = cdrewardCodes->GetCodeID(args[0]); if (id != -1) Database::Get()->InsertRewardCode(user->GetAccountID(), id); @@ -1905,13 +1905,12 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (chatCommand == "inspect" && entity->GetGMLevel() >= eGameMasterLevel::DEVELOPER && args.size() >= 1) { Entity* closest = nullptr; - eReplicaComponentType component; - std::u16string ldf; bool isLDF = false; - if (!GeneralUtils::TryParse(args[0], component)) { + auto component = GeneralUtils::TryParse(args[0]); + if (!component) { component = eReplicaComponentType::INVALID; ldf = GeneralUtils::UTF8ToUTF16(args[0]); @@ -1923,7 +1922,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit auto closestDistance = 0.0f; - const auto candidates = Game::entityManager->GetEntitiesByComponent(component); + const auto candidates = Game::entityManager->GetEntitiesByComponent(component.value()); for (auto* candidate : candidates) { if (candidate->GetLOT() == 1 || candidate->GetLOT() == 8092) { @@ -1934,7 +1933,7 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit continue; } - if (closest == nullptr) { + if (!closest) { closest = candidate; closestDistance = NiPoint3::Distance(candidate->GetPosition(), reference); @@ -1951,13 +1950,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } } - if (closest == nullptr) { - return; - } + if (!closest) return; Game::entityManager->SerializeEntity(closest); - auto* table = CDClientManager::Instance().GetTable(); + auto* table = CDClientManager::GetTable(); const auto& info = table->GetByID(closest->GetLOT()); @@ -1979,20 +1976,18 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit if (args.size() >= 2) { if (args[1] == "-m" && args.size() >= 3) { - auto* movingPlatformComponent = closest->GetComponent(); + auto* const movingPlatformComponent = closest->GetComponent(); - int32_t value = 0; + const auto mValue = GeneralUtils::TryParse(args[2]); - if (movingPlatformComponent == nullptr || !GeneralUtils::TryParse(args[2], value)) { - return; - } + if (!movingPlatformComponent || !mValue) return; movingPlatformComponent->SetSerialized(true); - if (value == -1) { + if (mValue == -1) { movingPlatformComponent->StopPathing(); } else { - movingPlatformComponent->GotoWaypoint(value); + movingPlatformComponent->GotoWaypoint(mValue.value()); } Game::entityManager->SerializeEntity(closest); @@ -2033,13 +2028,11 @@ void SlashCommandHandler::HandleChatCommand(const std::u16string& command, Entit } if (args.size() >= 3) { - int32_t faction; - if (!GeneralUtils::TryParse(args[2], faction)) { - return; - } + const auto faction = GeneralUtils::TryParse(args[2]); + if (!faction) return; destuctable->SetFaction(-1); - destuctable->AddFaction(faction, true); + destuctable->AddFaction(faction.value(), true); } } else if (args[1] == "-cf") { auto* destuctable = entity->GetComponent(); diff --git a/dMasterServer/InstanceManager.cpp b/dMasterServer/InstanceManager.cpp index a5a6d8dcc..9ae9930ce 100644 --- a/dMasterServer/InstanceManager.cpp +++ b/dMasterServer/InstanceManager.cpp @@ -17,7 +17,8 @@ InstanceManager::InstanceManager(Logger* logger, const std::string& externalIP) { mLogger = logger; mExternalIP = externalIP; - GeneralUtils::TryParse(Game::config->GetValue("world_port_start"), m_LastPort); + m_LastPort = + GeneralUtils::TryParse(Game::config->GetValue("world_port_start")).value_or(m_LastPort); m_LastInstanceID = LWOINSTANCEID_INVALID; } @@ -322,7 +323,7 @@ Instance* InstanceManager::FindPrivateInstance(const std::string& password) { } int InstanceManager::GetSoftCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); @@ -335,7 +336,7 @@ int InstanceManager::GetSoftCap(LWOMAPID mapID) { } int InstanceManager::GetHardCap(LWOMAPID mapID) { - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); diff --git a/dMasterServer/InstanceManager.h b/dMasterServer/InstanceManager.h index b9f1ec5a1..1fc4af439 100644 --- a/dMasterServer/InstanceManager.h +++ b/dMasterServer/InstanceManager.h @@ -134,7 +134,7 @@ class InstanceManager { Logger* mLogger; std::string mExternalIP; std::vector m_Instances; - unsigned short m_LastPort = 3000; + uint16_t m_LastPort = 3000; LWOINSTANCEID m_LastInstanceID; /** diff --git a/dMasterServer/MasterServer.cpp b/dMasterServer/MasterServer.cpp index f15bb9a9d..1fade06e4 100644 --- a/dMasterServer/MasterServer.cpp +++ b/dMasterServer/MasterServer.cpp @@ -89,9 +89,8 @@ int main(int argc, char** argv) { if (!dConfig::Exists("worldconfig.ini")) LOG("Could not find worldconfig.ini, using default settings"); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); LOG("Using net version %i", clientNetVersion); @@ -177,17 +176,6 @@ int main(int argc, char** argv) { // Run migrations should any need to be run. MigrationRunner::RunSQLiteMigrations(); - //Get CDClient initial information - try { - CDClientManager::Instance(); - } catch (CppSQLite3Exception& e) { - LOG("Failed to initialize CDServer SQLite Database"); - LOG("May be caused by corrupted file: %s", (Game::assetManager->GetResPath() / "CDServer.sqlite").string().c_str()); - LOG("Error: %s", e.errorMessage()); - LOG("Error Code: %i", e.errorCode()); - return EXIT_FAILURE; - } - //If the first command line argument is -a or --account then make the user //input a username and password, with the password being hidden. if (argc > 1 && diff --git a/dNavigation/dNavMesh.cpp b/dNavigation/dNavMesh.cpp index ab9ed2d50..f49dd31e5 100644 --- a/dNavigation/dNavMesh.cpp +++ b/dNavigation/dNavMesh.cpp @@ -11,6 +11,7 @@ #include "dZoneManager.h" #include "DluAssert.h" +#include "DetourExtensions.h" dNavMesh::dNavMesh(uint32_t zoneId) { m_ZoneId = zoneId; @@ -30,16 +31,8 @@ dNavMesh::dNavMesh(uint32_t zoneId) { dNavMesh::~dNavMesh() { // Clean up Recast information - if(m_Solid) rcFreeHeightField(m_Solid); - if (m_CHF) rcFreeCompactHeightfield(m_CHF); - if (m_CSet) rcFreeContourSet(m_CSet); - if (m_PMesh) rcFreePolyMesh(m_PMesh); - if (m_PMDMesh) rcFreePolyMeshDetail(m_PMDMesh); if (m_NavMesh) dtFreeNavMesh(m_NavMesh); if (m_NavQuery) dtFreeNavMeshQuery(m_NavQuery); - - if (m_Ctx) delete m_Ctx; - if (m_Triareas) delete[] m_Triareas; } diff --git a/dNavigation/dNavMesh.h b/dNavigation/dNavMesh.h index 600b8b868..8a55c6497 100644 --- a/dNavigation/dNavMesh.h +++ b/dNavigation/dNavMesh.h @@ -2,13 +2,17 @@ #include #include -#include -#include -#include - -#include "DetourExtensions.h" class NiPoint3; +class rcHeightfield; +class rcCompactHeightfield; +class rcContourSet; +class rcPolyMesh; +class rcPolyMeshDetail; +class InputGeom; +class dtNavMesh; +class dtNavMeshQuery; +class rcContext; class dNavMesh { public: @@ -26,24 +30,14 @@ class dNavMesh { float GetHeightAtPoint(const NiPoint3& location, const float halfExtentsHeight = 32.0f) const; std::vector GetPath(const NiPoint3& startPos, const NiPoint3& endPos, float speed = 10.0f); - class dtNavMesh* GetdtNavMesh() { return m_NavMesh; } + bool IsNavmeshLoaded() { return m_NavMesh != nullptr; } private: void LoadNavmesh(); uint32_t m_ZoneId; - uint8_t* m_Triareas = nullptr; - rcHeightfield* m_Solid = nullptr; - rcCompactHeightfield* m_CHF = nullptr; - rcContourSet* m_CSet = nullptr; - rcPolyMesh* m_PMesh = nullptr; - rcConfig m_Config; - rcPolyMeshDetail* m_PMDMesh = nullptr; - - class InputGeom* m_Geometry = nullptr; - class dtNavMesh* m_NavMesh = nullptr; - class dtNavMeshQuery* m_NavQuery = nullptr; + dtNavMesh* m_NavMesh = nullptr; + dtNavMeshQuery* m_NavQuery = nullptr; uint8_t m_NavMeshDrawFlags; - rcContext* m_Ctx = nullptr; }; diff --git a/dNet/AuthPackets.cpp b/dNet/AuthPackets.cpp index 2597c5769..25ccc9029 100644 --- a/dNet/AuthPackets.cpp +++ b/dNet/AuthPackets.cpp @@ -7,8 +7,8 @@ #include "Database.h" #include "ZoneInstanceManager.h" #include "MD5.h" -#include "SHA512.h" #include "GeneralUtils.h" +#include "ClientVersion.h" #include @@ -39,10 +39,9 @@ void AuthPackets::LoadClaimCodes() { auto rcstring = Game::config->GetValue("rewardcodes"); auto codestrings = GeneralUtils::SplitString(rcstring, ','); for(auto const &codestring: codestrings){ - uint32_t code = -1; - if(GeneralUtils::TryParse(codestring, code) && code != -1){ - claimCodes.push_back(code); - } + const auto code = GeneralUtils::TryParse(codestring); + + if (code && code.value() != -1) claimCodes.push_back(code.value()); } } @@ -74,9 +73,8 @@ void AuthPackets::SendHandshake(dServer* server, const SystemAddress& sysAddr, c RakNet::BitStream bitStream; BitStreamUtils::WriteHeader(bitStream, eConnectionType::SERVER, eServerMessageType::VERSION_CONFIRM); - uint32_t clientNetVersion = 171022; const auto clientNetVersionString = Game::config->GetValue("client_net_version"); - if (!clientNetVersionString.empty()) GeneralUtils::TryParse(clientNetVersionString, clientNetVersion); + const uint32_t clientNetVersion = GeneralUtils::TryParse(clientNetVersionString).value_or(171022); bitStream.Write(clientNetVersion); bitStream.Write(861228100); @@ -243,12 +241,12 @@ void AuthPackets::SendLoginResponse(dServer* server, const SystemAddress& sysAdd loginResponse.Write(LUString(Game::config->GetValue("event_7"))); loginResponse.Write(LUString(Game::config->GetValue("event_8"))); - uint16_t version_major = 1; - uint16_t version_current = 10; - uint16_t version_minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), version_major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), version_current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), version_minor); + const uint16_t version_major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + const uint16_t version_current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + const uint16_t version_minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); loginResponse.Write(version_major); loginResponse.Write(version_current); diff --git a/dPhysics/dpEntity.cpp b/dPhysics/dpEntity.cpp index 70bddb40a..cbe3f5e8c 100644 --- a/dPhysics/dpEntity.cpp +++ b/dPhysics/dpEntity.cpp @@ -76,7 +76,7 @@ void dpEntity::CheckCollision(dpEntity* other) { return; } - bool wasFound = (m_CurrentlyCollidingObjects.find(other->GetObjectID()) != m_CurrentlyCollidingObjects.end()); + bool wasFound = m_CurrentlyCollidingObjects.contains(other->GetObjectID()); bool isColliding = m_CollisionShape->IsColliding(other->GetShape()); diff --git a/dPhysics/dpGrid.cpp b/dPhysics/dpGrid.cpp index 1704e068e..8ec944fdd 100644 --- a/dPhysics/dpGrid.cpp +++ b/dPhysics/dpGrid.cpp @@ -8,24 +8,14 @@ dpGrid::dpGrid(int numCells, int cellSize) { CELL_SIZE = cellSize; m_DeleteGrid = true; - //fill x - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells.push_back(std::vector>()); - } - - //fill z - for (int i = 0; i < NUM_CELLS; i++) { - for (int i = 0; i < NUM_CELLS; i++) { - m_Cells[i].push_back(std::forward_list()); - } - } + m_Cells.resize(NUM_CELLS, std::vector>(NUM_CELLS)); } dpGrid::~dpGrid() { if (!this->m_DeleteGrid) return; for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; delete en; en = nullptr; @@ -39,13 +29,12 @@ void dpGrid::Add(dpEntity* entity) { int cellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int cellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); //Add to cell: - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); //To verify that the object isn't gargantuan: if (entity->GetScale() >= CELL_SIZE * 2 || entity->GetIsGargantuan()) @@ -59,23 +48,27 @@ void dpGrid::Move(dpEntity* entity, float x, float z) { int cellX = (int)std::round(x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int cellZ = (int)std::round(z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (cellX < 0) cellX = 0; - if (cellZ < 0) cellZ = 0; - if (cellX >= NUM_CELLS) cellX = NUM_CELLS - 1; - if (cellZ >= NUM_CELLS) cellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + cellX = std::clamp(cellX, 0, NUM_CELLS - 1); + cellZ = std::clamp(cellZ, 0, NUM_CELLS - 1); - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); if (oldCellX == cellX && oldCellZ == cellZ) return; - //Remove from perv cell: - m_Cells[oldCellX][oldCellZ].remove(entity); + //Remove from prev cell: + auto& cell = m_Cells[oldCellX][oldCellZ]; + + // For speed, find the single match and swap it with the last element, then pop_back. + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } //Add to the new cell - m_Cells[cellX][cellZ].push_front(entity); + m_Cells[cellX][cellZ].push_back(entity); } void dpGrid::Delete(dpEntity* entity) { @@ -83,15 +76,18 @@ void dpGrid::Delete(dpEntity* entity) { int oldCellX = (int)std::round(entity->m_Position.x) / dpGrid::CELL_SIZE + NUM_CELLS / 2; int oldCellZ = (int)std::round(entity->m_Position.z) / dpGrid::CELL_SIZE + NUM_CELLS / 2; - if (oldCellX < 0) oldCellX = 0; - if (oldCellZ < 0) oldCellZ = 0; - if (oldCellX >= NUM_CELLS) oldCellX = NUM_CELLS - 1; - if (oldCellZ >= NUM_CELLS) oldCellZ = NUM_CELLS - 1; + // Clamp values to the range [0, NUM_CELLS - 1] + oldCellX = std::clamp(oldCellX, 0, NUM_CELLS - 1); + oldCellZ = std::clamp(oldCellZ, 0, NUM_CELLS - 1); - m_Cells[oldCellX][oldCellZ].remove(entity); + auto& cell = m_Cells[oldCellX][oldCellZ]; + auto toRemove = std::find(cell.begin(), cell.end(), entity); + if (toRemove != cell.end()) { + *toRemove = cell.back(); + cell.pop_back(); + } - if (m_GargantuanObjects.find(entity->m_ObjectID) != m_GargantuanObjects.end()) - m_GargantuanObjects.erase(entity->m_ObjectID); + m_GargantuanObjects.erase(entity->m_ObjectID); if (entity) delete entity; entity = nullptr; @@ -100,8 +96,8 @@ void dpGrid::Delete(dpEntity* entity) { void dpGrid::Update(float deltaTime) { //Pre-update: for (auto& x : m_Cells) { //x - for (auto& y : x) { //y - for (auto en : y) { + for (auto& z : x) { //y + for (auto en : z) { if (!en) continue; en->PreUpdate(); } @@ -110,8 +106,8 @@ void dpGrid::Update(float deltaTime) { //Actual collision detection update: for (int x = 0; x < NUM_CELLS; x++) { - for (int y = 0; y < NUM_CELLS; y++) { - HandleCell(x, y, deltaTime); + for (int z = 0; z < NUM_CELLS; z++) { + HandleCell(x, z, deltaTime); } } } @@ -157,7 +153,7 @@ void dpGrid::HandleCell(int x, int z, float deltaTime) { HandleEntity(en, other); } - for (auto other : m_GargantuanObjects) - HandleEntity(en, other.second); + for (auto& [id, entity] : m_GargantuanObjects) + HandleEntity(en, entity); } } diff --git a/dPhysics/dpGrid.h b/dPhysics/dpGrid.h index 229e7449f..39a9cfe73 100644 --- a/dPhysics/dpGrid.h +++ b/dPhysics/dpGrid.h @@ -1,8 +1,7 @@ #pragma once -#include -#include -#include #include +#include + #include "dCommonVars.h" class dpEntity; @@ -30,7 +29,8 @@ class dpGrid { */ void SetDeleteGrid(bool value) { this->m_DeleteGrid = value; }; - std::vector>> GetCells() { return this->m_Cells; }; + // Intentional copy since this is only used when we delete this class to re-create it. + std::vector>> GetCells() { return this->m_Cells; }; private: void HandleEntity(dpEntity* entity, dpEntity* other); @@ -38,7 +38,7 @@ class dpGrid { private: //cells on X, cells on Y for that X, then another vector that contains the entities within that cell. - std::vector>> m_Cells; + std::vector>> m_Cells; std::map m_GargantuanObjects; bool m_DeleteGrid = true; }; diff --git a/dPhysics/dpWorld.cpp b/dPhysics/dpWorld.cpp index e820eac2c..c9bc742ad 100644 --- a/dPhysics/dpWorld.cpp +++ b/dPhysics/dpWorld.cpp @@ -26,9 +26,15 @@ namespace { void dpWorld::Initialize(unsigned int zoneID, bool generateNewNavMesh) { const auto physSpTilecount = Game::config->GetValue("phys_sp_tilecount"); - if (!physSpTilecount.empty()) GeneralUtils::TryParse(physSpTilecount, phys_sp_tilecount); + if (!physSpTilecount.empty()) { + phys_sp_tilecount = GeneralUtils::TryParse(physSpTilecount).value_or(phys_sp_tilecount); + } + const auto physSpTilesize = Game::config->GetValue("phys_sp_tilesize"); - if (!physSpTilesize.empty()) GeneralUtils::TryParse(physSpTilesize, phys_sp_tilesize); + if (!physSpTilesize.empty()) { + phys_sp_tilesize = GeneralUtils::TryParse(physSpTilesize).value_or(phys_sp_tilesize); + } + const auto physSpatialPartitioning = Game::config->GetValue("phys_spatial_partitioning"); if (!physSpatialPartitioning.empty()) phys_spatial_partitioning = physSpatialPartitioning == "1"; @@ -81,7 +87,7 @@ void dpWorld::Shutdown() { } bool dpWorld::IsLoaded() { - return m_NavMesh->GetdtNavMesh() != nullptr; + return m_NavMesh->IsNavmeshLoaded(); } void dpWorld::StepWorld(float deltaTime) { diff --git a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp index 60b750cf2..357187ef4 100644 --- a/dScripts/02_server/Map/AM/AmDropshipComputer.cpp +++ b/dScripts/02_server/Map/AM/AmDropshipComputer.cpp @@ -33,14 +33,12 @@ void AmDropshipComputer::OnUse(Entity* self, Entity* user) { void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -70,11 +68,9 @@ void AmDropshipComputer::OnDie(Entity* self, Entity* killer) { } void AmDropshipComputer::OnTimerDone(Entity* self, std::string timerName) { - auto* quickBuildComponent = self->GetComponent(); + const auto* const quickBuildComponent = self->GetComponent(); - if (quickBuildComponent == nullptr) { - return; - } + if (!quickBuildComponent) return; if (timerName == "reset" && quickBuildComponent->GetState() == eQuickBuildState::OPEN) { self->Smash(self->GetObjectID(), eKillType::SILENT); diff --git a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp index 0c0f75157..1eaad3c9a 100644 --- a/dScripts/02_server/Map/AM/AmSkullkinTower.cpp +++ b/dScripts/02_server/Map/AM/AmSkullkinTower.cpp @@ -144,13 +144,10 @@ void AmSkullkinTower::OnChildRemoved(Entity* self, Entity* child) { ); for (const auto& mission : missions) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(mission); + if (!missionID) continue; - if (!GeneralUtils::TryParse(mission, missionID)) { - continue; - } - - missionIDs.push_back(missionID); + missionIDs.push_back(missionID.value()); } } diff --git a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp index 3acc9063a..82f1481ab 100644 --- a/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp +++ b/dScripts/02_server/Map/AM/AmTemplateSkillVolume.cpp @@ -12,12 +12,9 @@ void AmTemplateSkillVolume::OnSkillEventFired(Entity* self, Entity* caster, cons const auto missionIDs = GeneralUtils::SplitString(missionIDsVariable, '_'); for (const auto& missionIDStr : missionIDs) { - int32_t missionID = 0; + const auto missionID = GeneralUtils::TryParse(missionIDStr); + if (!missionID) continue; - if (!GeneralUtils::TryParse(missionIDStr, missionID)) { - continue; - } - - missionComponent->ForceProgressTaskType(missionID, 1, 1, false); + missionComponent->ForceProgressTaskType(missionID.value(), 1, 1, false); } } diff --git a/dScripts/02_server/Map/General/PetDigServer.cpp b/dScripts/02_server/Map/General/PetDigServer.cpp index 0ea78e4f4..a55c2f291 100644 --- a/dScripts/02_server/Map/General/PetDigServer.cpp +++ b/dScripts/02_server/Map/General/PetDigServer.cpp @@ -107,7 +107,7 @@ void PetDigServer::HandleXBuildDig(const Entity* self, Entity* owner, Entity* pe return; auto* playerEntity = Game::entityManager->GetEntity(playerID); - if (!playerEntity || !playerEntity->GetParentUser() || !playerEntity->GetParentUser()->GetLastUsedChar()) + if (!playerEntity || !playerEntity->GetCharacter()) return; auto* player = playerEntity->GetCharacter(); diff --git a/dScripts/02_server/Map/General/QbEnemyStunner.cpp b/dScripts/02_server/Map/General/QbEnemyStunner.cpp index 8291f409a..2238c4102 100644 --- a/dScripts/02_server/Map/General/QbEnemyStunner.cpp +++ b/dScripts/02_server/Map/General/QbEnemyStunner.cpp @@ -17,12 +17,12 @@ void QbEnemyStunner::OnQuickBuildComplete(Entity* self, Entity* target) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); auto skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); std::map skillBehaviorMap; // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); skillBehaviorMap.insert(std::make_pair(skill.skillID, behaviorData.behaviorID)); diff --git a/dScripts/ChooseYourDestinationNsToNt.cpp b/dScripts/ChooseYourDestinationNsToNt.cpp index f9ca0a796..b736883c4 100644 --- a/dScripts/ChooseYourDestinationNsToNt.cpp +++ b/dScripts/ChooseYourDestinationNsToNt.cpp @@ -41,11 +41,9 @@ void ChooseYourDestinationNsToNt::SetDestination(Entity* self, Entity* player) { void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sender, int32_t button, const std::u16string& buttonIdentifier, const std::u16string& identifier) { if (button != -1) { const auto newMapStr = GeneralUtils::UTF16ToWTF8(buttonIdentifier).substr(7, -1); - - int32_t newMap = 0; - if (!GeneralUtils::TryParse(newMapStr, newMap)) { - return; - } + const auto newMap = GeneralUtils::TryParse(newMapStr); + + if (!newMap) return; std::u16string strText = u""; @@ -56,7 +54,7 @@ void ChooseYourDestinationNsToNt::BaseChoiceBoxRespond(Entity* self, Entity* sen } self->SetVar(u"teleportString", strText); - self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap)); + self->SetVar(u"transferZoneID", GeneralUtils::to_u16string(newMap.value())); GameMessages::SendDisplayMessageBox(sender->GetObjectID(), true, self->GetObjectID(), u"TransferBox", 0, strText, u"", sender->GetSystemAddress()); } else { diff --git a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp index 389f36211..0220711df 100644 --- a/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp +++ b/dScripts/EquipmentScripts/FireFirstSkillonStartup.cpp @@ -11,12 +11,12 @@ void FireFirstSkillonStartup::OnStartup(Entity* self) { if (!skillComponent) return; // Get the skill IDs of this object. - CDObjectSkillsTable* skillsTable = CDClientManager::Instance().GetTable(); + CDObjectSkillsTable* skillsTable = CDClientManager::GetTable(); std::vector skills = skillsTable->Query([=](CDObjectSkills entry) {return (entry.objectTemplate == self->GetLOT()); }); // For each skill, cast it with the associated behavior ID. for (auto skill : skills) { - CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::Instance().GetTable(); + CDSkillBehaviorTable* skillBehaviorTable = CDClientManager::GetTable(); CDSkillBehavior behaviorData = skillBehaviorTable->GetSkillByID(skill.skillID); // Should parent entity be null, make the originator self. diff --git a/dScripts/ai/FV/FvBrickPuzzleServer.cpp b/dScripts/ai/FV/FvBrickPuzzleServer.cpp index e1f1ac881..f8601e3fa 100644 --- a/dScripts/ai/FV/FvBrickPuzzleServer.cpp +++ b/dScripts/ai/FV/FvBrickPuzzleServer.cpp @@ -7,10 +7,8 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; if (pipeNum != 1) { self->AddTimer("reset", 30); @@ -20,14 +18,12 @@ void FvBrickPuzzleServer::OnStartup(Entity* self) { void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { const auto myGroup = GeneralUtils::UTF16ToWTF8(self->GetVar(u"spawner_name")); - int32_t pipeNum = 0; - if (!GeneralUtils::TryParse(myGroup.substr(10, 1), pipeNum)) { - return; - } + const auto pipeNum = GeneralUtils::TryParse(myGroup.substr(10, 1)); + if (!pipeNum) return; const auto pipeGroup = myGroup.substr(0, 10); - const auto nextPipeNum = pipeNum + 1; + const auto nextPipeNum = pipeNum.value() + 1; const auto samePipeSpawners = Game::zoneManager->GetSpawnersByName(myGroup); @@ -37,7 +33,7 @@ void FvBrickPuzzleServer::OnDie(Entity* self, Entity* killer) { samePipeSpawners[0]->Deactivate(); } - if (killer != nullptr && killer->IsPlayer()) { + if (killer && killer->IsPlayer()) { const auto nextPipe = pipeGroup + std::to_string(nextPipeNum); const auto nextPipeSpawners = Game::zoneManager->GetSpawnersByName(nextPipe); diff --git a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp index c8563b53c..1952831a3 100644 --- a/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp +++ b/dScripts/ai/MINIGAME/SG_GF/SERVER/SGCannon.cpp @@ -2,7 +2,6 @@ #include "EntityManager.h" #include "GameMessages.h" #include "dZoneManager.h" -#include "Player.h" #include "Character.h" #include "ShootingGalleryComponent.h" #include "PossessorComponent.h" diff --git a/dWorldServer/PerformanceManager.cpp b/dWorldServer/PerformanceManager.cpp index 248be54af..052d075bb 100644 --- a/dWorldServer/PerformanceManager.cpp +++ b/dWorldServer/PerformanceManager.cpp @@ -70,7 +70,7 @@ std::map PerformanceManager::m_Profiles = { void PerformanceManager::SelectProfile(LWOMAPID mapID) { // Try to get it from zoneTable - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable) { const CDZoneTable* zone = zoneTable->Query(mapID); if (zone) { diff --git a/dWorldServer/WorldServer.cpp b/dWorldServer/WorldServer.cpp index 6a8ed074d..bb879dbdf 100644 --- a/dWorldServer/WorldServer.cpp +++ b/dWorldServer/WorldServer.cpp @@ -56,7 +56,6 @@ #include "DestroyableComponent.h" #include "Game.h" #include "MasterPackets.h" -#include "Player.h" #include "PropertyManagementComponent.h" #include "AssetManager.h" #include "LevelProgressionComponent.h" @@ -181,7 +180,7 @@ int main(int argc, char** argv) { return EXIT_FAILURE; } - CDClientManager::Instance().LoadValuesFromDatabase(); + CDClientManager::LoadValuesFromDatabase(); Diagnostics::SetProduceMemoryDump(Game::config->GetValue("generate_dump") == "1"); @@ -209,8 +208,7 @@ int main(int argc, char** argv) { UserManager::Instance()->Initialize(); - bool dontGenerateDCF = false; - GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf"), dontGenerateDCF); + const bool dontGenerateDCF = GeneralUtils::TryParse(Game::config->GetValue("dont_generate_dcf")).value_or(false); Game::chatFilter = new dChatFilter(Game::assetManager->GetResPath().string() + "/chatplus_en_us", dontGenerateDCF); Game::server = new dServer(masterIP, ourPort, instanceID, maxClients, false, true, Game::logger, masterIP, masterPort, ServerType::World, Game::config, &Game::lastSignal, zoneID); @@ -607,9 +605,10 @@ void HandlePacketChat(Packet* packet) { inStream.Read(expire); auto* entity = Game::entityManager->GetEntity(playerId); - - if (entity != nullptr) { - entity->GetParentUser()->SetMuteExpire(expire); + auto* character = entity != nullptr ? entity->GetCharacter() : nullptr; + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + user->SetMuteExpire(expire); entity->GetCharacter()->SendMuteNotice(); } @@ -1127,9 +1126,10 @@ void HandlePacket(Packet* packet) { //Mail::HandleNotificationRequest(packet->systemAddress, player->GetObjectID()); //Notify chat that a player has loaded: - { - const auto& playerName = player->GetCharacter()->GetName(); - //RakNet::RakString playerName(player->GetCharacter()->GetName().c_str()); + auto* character = player->GetCharacter(); + auto* user = character != nullptr ? character->GetParentUser() : nullptr; + if (user) { + const auto& playerName = character->GetName(); CBITSTREAM; BitStreamUtils::WriteHeader(bitStream, eConnectionType::CHAT_INTERNAL, eChatInternalMessageType::PLAYER_ADDED_NOTIFICATION); @@ -1143,7 +1143,7 @@ void HandlePacket(Packet* packet) { bitStream.Write(zone.GetMapID()); bitStream.Write(zone.GetInstanceID()); bitStream.Write(zone.GetCloneID()); - bitStream.Write(player->GetParentUser()->GetMuteExpire()); + bitStream.Write(user->GetMuteExpire()); bitStream.Write(player->GetGMLevel()); Game::chatServer->Send(&bitStream, SYSTEM_PRIORITY, RELIABLE, 0, Game::chatSysAddr, false); diff --git a/dZoneManager/Level.cpp b/dZoneManager/Level.cpp index 0a46dc897..9524d908b 100644 --- a/dZoneManager/Level.cpp +++ b/dZoneManager/Level.cpp @@ -14,6 +14,7 @@ #include "CDFeatureGatingTable.h" #include "CDClientManager.h" #include "AssetManager.h" +#include "ClientVersion.h" #include "dConfig.h" Level::Level(Zone* parentZone, const std::string& filepath) { @@ -208,15 +209,15 @@ void Level::ReadSceneObjectDataChunk(std::istream& file, Header& header) { uint32_t objectsCount = 0; BinaryIO::BinaryRead(file, objectsCount); - CDFeatureGatingTable* featureGatingTable = CDClientManager::Instance().GetTable(); + CDFeatureGatingTable* featureGatingTable = CDClientManager::GetTable(); CDFeatureGating gating; - gating.major = 1; - gating.current = 10; - gating.minor = 64; - GeneralUtils::TryParse(Game::config->GetValue("version_major"), gating.major); - GeneralUtils::TryParse(Game::config->GetValue("version_current"), gating.current); - GeneralUtils::TryParse(Game::config->GetValue("version_minor"), gating.minor); + gating.major = + GeneralUtils::TryParse(Game::config->GetValue("version_major")).value_or(ClientVersion::major); + gating.current = + GeneralUtils::TryParse(Game::config->GetValue("version_current")).value_or(ClientVersion::current); + gating.minor = + GeneralUtils::TryParse(Game::config->GetValue("version_minor")).value_or(ClientVersion::minor); const auto zoneControlObject = Game::zoneManager->GetZoneControlObject(); DluAssert(zoneControlObject != nullptr); diff --git a/dZoneManager/Zone.cpp b/dZoneManager/Zone.cpp index 3f306c05f..42ce12152 100644 --- a/dZoneManager/Zone.cpp +++ b/dZoneManager/Zone.cpp @@ -154,7 +154,7 @@ void Zone::LoadZoneIntoMemory() { std::string Zone::GetFilePathForZoneID() { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(this->GetZoneID().GetMapID()); if (zone != nullptr) { std::string toReturn = "maps/" + zone->zoneName; diff --git a/dZoneManager/dZoneManager.cpp b/dZoneManager/dZoneManager.cpp index 3aa35485b..09baabed9 100644 --- a/dZoneManager/dZoneManager.cpp +++ b/dZoneManager/dZoneManager.cpp @@ -29,7 +29,7 @@ void dZoneManager::Initialize(const LWOZONEID& zoneID) { LOT zoneControlTemplate = 2365; - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); if (zoneTable != nullptr) { const CDZoneTable* zone = zoneTable->Query(zoneID.GetMapID()); @@ -208,7 +208,7 @@ uint32_t dZoneManager::GetUniqueMissionIdStartingValue() { bool dZoneManager::CheckIfAccessibleZone(LWOMAPID zoneID) { //We're gonna go ahead and presume we've got the db loaded already: - CDZoneTableTable* zoneTable = CDClientManager::Instance().GetTable(); + CDZoneTableTable* zoneTable = CDClientManager::GetTable(); const CDZoneTable* zone = zoneTable->Query(zoneID); if (zone != nullptr) { return Game::assetManager->HasFile(("maps/" + zone->zoneName).c_str()); diff --git a/tests/dGameTests/GameDependencies.h b/tests/dGameTests/GameDependencies.h index 11c320ba8..5d9c99bf5 100644 --- a/tests/dGameTests/GameDependencies.h +++ b/tests/dGameTests/GameDependencies.h @@ -36,7 +36,7 @@ class GameDependenciesTest : public ::testing::Test { Game::entityManager = new EntityManager(); // Create a CDClientManager instance and load from defaults - CDClientManager::Instance().LoadValuesFromDefaults(); + CDClientManager::LoadValuesFromDefaults(); } void TearDownDependencies() { diff --git a/thirdparty/CMakeLists.txt b/thirdparty/CMakeLists.txt index 11d278c08..40c81544a 100644 --- a/thirdparty/CMakeLists.txt +++ b/thirdparty/CMakeLists.txt @@ -57,3 +57,5 @@ if(UNIX AND NOT APPLE) include_directories(${backtrace_SOURCE_DIR}) endif() endif() + +add_subdirectory(MD5) diff --git a/thirdparty/MD5/CMakeLists.txt b/thirdparty/MD5/CMakeLists.txt new file mode 100644 index 000000000..755b4519b --- /dev/null +++ b/thirdparty/MD5/CMakeLists.txt @@ -0,0 +1,6 @@ +add_library(MD5 "MD5.cpp") + +# Disable deprecation warnings on MD5.cpp for Apple Clang +if (APPLE) + set_source_files_properties("MD5.cpp" PROPERTIES COMPILE_FLAGS "-Wno-deprecated-declarations") +endif() diff --git a/dCommon/MD5.cpp b/thirdparty/MD5/MD5.cpp similarity index 100% rename from dCommon/MD5.cpp rename to thirdparty/MD5/MD5.cpp diff --git a/dCommon/MD5.h b/thirdparty/MD5/MD5.h similarity index 100% rename from dCommon/MD5.h rename to thirdparty/MD5/MD5.h